urSus urSus - 3 months ago 20
Android Question

Intent flags - How to start a new activity instance and have others closed

I am not really familiar with intent flags, so please, bear with me.

I am doing an application which displays stuff from a database in a ViewPager. I also have a widget which from time to time pulls out a random row and displays it. Now, when I click on it, I am taken to an activity where the same content is displayed and now I can take action on it.

Everything works, however when I have an activity already running and then click on the widget, it seems it creates a new instance, because when I press the Back button I am not exiting the application but am taken to the previous instance or something.

Is there a way to start a new instance of an activity and if there were some previous instances running close them, using flags?

I played around with CLEAR_TOP and that stuff but I honestly don't know what am I doing.

Thanks!

//EDIT

Intent.FLAG_ACTIVITY_CLEAR_TOP doesn't seem to do anything. Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP seems to bring the previous one to the top and ignores the new one or something. Maybe let me rephrase, I start the activity from launcher icon, then I press the Home button and click on widget and it should bring up a new instance where ViewPager.setCurrentItem sets the correct page (same as in widget). If there were no main activity running before, everything is okay, but if it was running, finish it.

MyWidgetProvider extends AppWidgetProvider

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Log.d("MainActivity", "MyWidgetProvider # onUpdate");

for (int i = 0; i < appWidgetIds.length; i++) {
int appWidgetId = appWidgetIds[i];

Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("from_widget", true);
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
views.setOnClickPendingIntent(R.id.widget_container, pendingIntent);

appWidgetManager.updateAppWidget(appWidgetId, views);
}

}

Answer

There are several ways to do this. If you want to create a new instance and close the current instance (assuming that it is on the top of the activity stack) you need to set Intent.FLAG_ACTIVITY_CLEAR_TOP.

Another alternative would be to reuse the same instance of the activity if it is already on the top of the stack. In this case you need to set both Intent.FLAG_ACTIVITY_CLEAR_TOP and Intent.FLAG_ACTIVITY_SINGLE_TOP. If you do this, Android won't create another instance of the activity, but will call onNewIntent() of your activity to deliver the new Intent.