Back to main activity from notification-created activity

Aha, I simply need to use PendingIntent.getActivities() instead of getActivity(). Also worth mentioning is TaskStackBuilder

Here is some code:

    Intent backIntent = new Intent(ctx, MainActivity.class);

    Intent intent = new Intent(ctx, ConversationActivity.class);
    intent.putExtra("whatever", whatever);
    final PendingIntent pendingIntent = PendingIntent.getActivities(ctx, UNIQUE_REQUEST_CODE++,
            new Intent[] {backIntent, intent}, PendingIntent.FLAG_ONE_SHOT);

Just tested it. It works like a charm. I initially suspected that there might be a problem if the app is already running, and you go to a notification. I.e. say you activity stack is (topmost on the right):

[MainActivity] [SomeActivity]

and you click a notification for ConversationActivity. Would you get:?

[MainActivity] [SomeActivity] [MainActivity] [ConversationActivity]

Well, it turns out you magically get

[MainActivity] [SomeActivity] [ConversationActivity]

which is what I wanted, but I have no idea how it does that. I haven’t set any special options on any of the activities. Oh well!

Leave a Comment