Using PreferencesActivity from a widget?

后端 未结 2 1782
孤街浪徒
孤街浪徒 2020-12-18 13:04

The PreferenceActivity seems like a really easy helper class to manage the preferences of an app.

I\'d like to also use that same class from the widget.

On t

相关标签:
2条回答
  • 2020-12-18 13:50

    You should be able to tell when the Preference edits are complete by implementing a SharedPreferences.OnShredPreferenceChangeListener. Using this, you could update only when certain keys are changed, or unconditionally when any are changed. Remember to register it in your PreferenceActivity onCreate and unregister it in the onDestroy.

    In this case, you can do something similar to Android: How do I force the update of all widgets of a particular kind within the listener to cause all of your widgets to update based on a SharedPreference change.

    It's an old question, so this may not be relevant anymore.

    0 讨论(0)
  • 2020-12-18 13:58

    I have been trying to do the same thing and I think I've cracked it. I handle the onBackPressed() event in the PreferenceActivity and perform a widget update from there using sendBroadcast().

    In PreferenceActivity:

    @Override
    public void onBackPressed() {
        Intent intent=getIntent();
        Bundle extras=intent.getExtras();   
        int widgetId=extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
    
        // this is the intent broadcast/returned to the widget
        Intent updateIntent = new Intent(this, WidgetProvider.class);
        updateIntent.setAction("PreferencesUpdated");
        updateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
        sendBroadcast(updateIntent);
    }
    

    In your WidgetProvider:

    @Override
    public void onReceive(Context context, Intent intent) {
        if ("PreferencesUpdated".equals(action)) {
            // update your widget here
            // my widget supports multiple instances so I needed to uniquely identify them like this
            RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.widget);
            int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID);
            updateWidgetView(context, remoteView, appWidgetId);
        }   
    }
    

    NOTE: In 1.5 onBackPressed isn't support so comment out the @Override for onBackPressed and add this code

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d(LOG_TAG, "onKeyDown() "+ keyCode);
        if (keyCode==KeyEvent.KEYCODE_BACK && Integer.parseInt(Build.VERSION.SDK)<5) {
            onBackPressed();
        }
    }
    

    I should add that I'm new to Android development so I may be doing this entirely wrong. All I can say it is works for me :)

    Let me know how you get on.

    0 讨论(0)
提交回复
热议问题