Search code examples
androidwidgetandroid-broadcast

Update widget when preferences changed using custom broadcast


I need to update my app's widget every time the settings are changed by the user.

I have a settings activity:

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

public class SettingsActivity extends Activity implements SharedPreferences.OnSharedPreferenceChangeListener {

public static final String customIntent = "CUSTOM_SETTINGS_CHANGED";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Display the fragment as the main content.
    getFragmentManager().beginTransaction()
            .replace(android.R.id.content, new MainActivity.SettingsFragment())
            .commit();
}

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                                      String key) {
    Intent intent = new Intent();
    intent.setAction(customIntent);
    this.sendBroadcast(intent);
    }
}

I've added that custom intent to the manifest:

<action android:name="CUSTOM_SETTINGS_CHANGED" />

But the widget is not updated immediately after the settings are changed. So my custom broadcast either is not sent or not received. What's wrong with my code?


Solution

  • I've used a different approach.

    In my main activity I've added this:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        <...>
        SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
            public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
                Intent intent = new Intent();
                intent.setAction(customIntent);
                sendBroadcast(intent);
            }
        };
        <...>
    }
    

    It seems that onSharedPreferenceChanged was never called for some reason. I don't know why but at least I've found a way to make this work.