I have two (or more) widgets, e.g. A and B, which should launch the same activity passing their appWidgetId in the Intent extras to the activity. This works fine after application install on the first launch from any of the widgets (the activity receives the correct appWidgetId). It also works fine if I press the back button after activity launch and launch the activity from a different widget. However, if I launch the activity from widget A, hit the home button and then launch the activity from widget B (or C or D…) it launches with A’s appWidgetId. I’m baffled as to how to fix this. Here is how I am declaring my PendingIntent:
Intent intent = new Intent(context, WidgetActivity.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
intent.setAction(this.getClass().getName() + System.currentTimeMillis());
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
If I understand correctly, I am successfully setting up unique PendingIntents for each widget. Any help most appreciated!
EDIT:
The accepted answer to this question suggests that:
I believe the problem is that you have a PendingIntent that only differs by extra. PendingIntents are cached, so if you use two with the same action and data, they’ll overwrite each other.
However, my code creates randomized actions to perform and so I think my PendingIntents differ by more than just extras
Looks like I need to brush up on my activity lifecycle events. The answer was the following code put into my Activity:
The problem was that, on Home button press, the Activity was holding onto the original
Intentwhich launched it. Then, when the other widget launched the Activity, the original intent was being reused. The above code simply replaces the original intent with the new one and carries on with the remaining lifecycle events.