androidandroid-intentandroid-activityandroid-notificationsandroid-task

Activity with launchMode singleTop or singleTask is always recreated


The MainActivity in my app has a launchMode of singleTop defined in the manifest file. Whenever I click a notification my MainActivity is re-created and the old instance is destroyed. MainActivity is visible and in the foreground when the notification is clicked, so I would assume the intent would be passed to the current instance's onNewIntent(), but this never happens. Here is the intent I create:

Intent resultIntent = new Intent(App.getInstance(), MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(App.getInstance());
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = PendingIntent.getActivity(App.getInstance(), 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

I sometimes add the FLAG_ACTIVITY_CLEAR_TOP and FLAG_ACTIVITY_SINGLE_TOP to the intent like so:

resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

I have also tried using the singleTask launchMode also with those flags and the same behavior has happened. Could someone lend some insight on this behavior?


Solution

  • You don't need to create a new TaskStackBuilder. Try intent which acts like you want to restart the application, but singleTop will keep it from doing so:

    Intent resultIntent = new Intent(App.getInstance(), MainActivity.class);
    resultIntent.setAction(Intent.ACTION_MAIN);
    resultIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    
    PendingIntent resultPendingIntent = PendingIntent.getActivity(App.getInstance(), 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);