views:

74

answers:

1

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 the first instance of a widget I want the PreferenceActivity to come up. This was very easy to do from the configuration activity but here is the glitch...

I can't tell when the preference edit is completed!

All examples of widget preferences I see on the net use a manually built preference screen rather than the PreferenceActivity helper class and then listen for the 'save' button being clicked.

How can I do that with the PreferenceActivity since that activity doesn't have a save button. You just use the 'back' button to commit your preferences changes.

Thanks!

A: 

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.

CellsReinvent