Search code examples
androidandroid-activitynotificationsandroid-pendingintent

How can I programmatically show activity on the top of task stack?


My application starts a foreground service which keeps connection to server. It shows notification with pendingIntent which show in MainActivity. When I (user) tap on application icon (on desktop or application list) it shows the "task stack". I mean if was launched MainActivity it shows it, if user go to activity B or C (or launch some other activities) it shows it (I mean top activity from task stack). There is a problem - if user taps on notification they see again MainActivity (on the top of the stack) but I expect top of task stack (activity B,C or other which was launched by user at the end).

Half solves when I set attribute for MainActivity "singleTask", now it's always root of task stack, BUT I'm losing all activities (B, C and other which user launched). Solution like in Reuse Activity on Top of Stack similarly, but I need only one activity at root.

Maybe my logic is wrong and I need some another way to resolve this problem. But I want to know how can I programmatically show task stack (top activity) like application icon does?


Solution

  • The documentation Tasks and Back Stack describes how to handle navigation correctly.

    In short, if users tap on your navigation and you take them to an Activity in your app, when they click Back they should up in your app's Activity hierarchy until they reach the Home screen. They should never go to the stack in another task. That is, if they're in your app in Activity C, and you send a notification which they click that takes them to Activity A, then clicking Back should take them to the parent of A, and not to C. If they want to go to C, they can use Recents.

    On older platforms, Recents isn't available.

    This is by design.

    To construct the proper synthetic back stack, use TaskStackBuilder