Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notifying live wallpaper service about changes in settings

Tags:

android

I'm creating a live wallpaper by extending WallpaperService and Engine classes. The wallpaper doesn't change frequently, so to avoid unnecessary CPU usage, I only draw the wallpaper on certain events (touch, visibilityChanged, etc.). I'm also using PreferenceFragment to generate a settings activity for the wallpaper.

Problem: when user changes a preference in the settings activity, I like the wallpaper to get notified and redraw itself ASAP using the new settings. But since I only read the settings and draw the wallpaper on certain events, the change in wallpaper doesn't happen until those events are fired.

Would appreciate solutions :) thnx.

Anybody? :(

like image 883
Sahand Seifi Avatar asked Sep 20 '25 05:09

Sahand Seifi


1 Answers

You got two options. Either check the preference values in onVisibilityChanged() and update the wallpaper accordingly. Or use an OnSharedPreferenceChangeListener to let your Engine know when the user has changed the preference.


Example of the latter.

Let your Engine implement the OnSharedPreferenceChangeListener interface.

private class MyEngine extends Engine implements OnSharedPreferenceChangeListener {

    // A reference to our shared prefs;
    private SharedPreferences mPreferences;

    @Override
    public void onCreate(SurfaceHolder surfaceHolder) { 
        super.onCreate(surfaceHolder);

        mPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        // Register an OnSharedPreferenceChangeListener to our shared prefs
        mPreferences.registerOnSharedPreferenceChangeListener(this);         

        // Your existing code ...            
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        // Don't forget to unregister the listener
        mPreferences.unregisterOnSharedPreferenceChangeListener(this);  
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

        // Whenever the user changes a setting, this method will be called.
        // So do what needs to be done here, like redrawing the wallpaper
        redrawWallpaper();
    }
}
like image 93
Ole Avatar answered Sep 22 '25 20:09

Ole