Using PreferencesActivity from a widget?

后端 未结 2 1783
孤街浪徒
孤街浪徒 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: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.

提交回复
热议问题