Search code examples
androidwidgetpreferenceactivity

Widget using PreferenceActivity not adding to home screen


I'm writing a widget that is configured using a PreferenceActivity. The widget needs to be configured once - it relies on an api that uses oauth authentication. The flow is as follows:

  1. Drag widget to homescreen
  2. PreferenceActivity appears, does a request for a request token and redirects to the browser
  3. User authenticates with the website and then I have a callback to the PreferenceActivty
  4. Widget requests the access token and saves it
  5. Widget refreshes and closes the PreferenceActivty

The issue is with step 5 - the closing happens but the widget is not added to the home screen! The thing is, if I do this process and then add another widget to the home screen, the code sees that we're already authenticated and it calls the same function to do the refresh/close the PreferenceActivity. This time it works and is added to the home screen!!

I can't work out where the issue is here. I did have this working using a normal Activity and not a PreferenceActivity, but I don't understand why that would be an issue. Was thinking I should call setResult(RESULT_OK... ) when the PreferenceActivity ends to start the browser in step 2, but it doesn't work. I thought because it works from onCreate but not from a callback (when an asynctask is finished) it was because it wasn't running on the UI thread, but forcing it to by calling runOnUiThread didn't work either...

Code for step 5 is:

    private static void refreshWidgetAndShowHomeScreen(final Activity activity, int appWidgetId) {
// ... code that does refresh

Intent showHome = new Intent(Intent.ACTION_MAIN);
showHome.addCategory(Intent.CATEGORY_HOME);
showHome.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);

activity.setResult(RESULT_OK, showHome);
activity.finish();
activity.startActivity(showHome);
}

The function is static because I'm writing the widget for android API 7+, so it's called from both the Activity itself and from a Fragment for versions greater than Honeycomb.


Solution

  • After a lot of attempts to persuade this to work, I ended up doing the following in onCreate the first time the widget is run, so it is added to the screen immediately. The code closes the activity then immediately restarts it.

    Visually, it looks okay. But this sucks because if the user can't authenticate or doesn't want to any more, there will be a dead widget left on their screen. Suggestions welcome...

    Workaround:

    final Intent intent2 = getIntent();
    intent2.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
    setResult(RESULT_OK, intent2);
    finish();
    startActivity(intent2);