Back to main activity from notification-created activity

后端 未结 9 2114
粉色の甜心
粉色の甜心 2020-11-30 04:33

I\'m trying to implement the behaviour described here, where a notification (or whatever) starts an \"internal\" activity in your app, and then when the user pressed back it

9条回答
  •  迷失自我
    2020-11-30 05:04

    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);
        backIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    
        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!

提交回复
热议问题