JimVanB
JimVanB

Reputation: 1225

Start new activity from notification in existing task

My app receives pushes and opens different activities according to the push type.

I use TaskStackBuilder for a pending Intent to create a synthetic backstack in conjunction with android:parentActivityNamein my manifest.

So far, so easy. When the App is not started, all works as expected. But if the app is in background (task is running), the pending Intent also starts my desired activity with the defined parent from the manifest, but resets the existing task. The problem is that other activities that were started by the user in the meantime are also cleared. enter image description here

So what a want to achieve is:

  1. if the app is not started, open the desired activity with the synthetic backstack (MainActivity)
  2. if the app is running, respect the current task order and just push the desired activity on top of it.

I can't seem to make it work with the TaskStackBuilder.

I'd be happy for some insights.

Upvotes: 4

Views: 2395

Answers (2)

BekaBot
BekaBot

Reputation: 510

Try using PendingIntent.getActivities with FLAG_ONE_SHOT, this way I was able to open stack of activities with correct navigation

Upvotes: 0

David Wasser
David Wasser

Reputation: 95578

You can't really do this with TaskStackBuilder. It isn't designed for that. It always resets the task to begin with.

I would do the following:

  • Have the Notification start an Activity. Don't use TaskStackBuilder and don't create any artificial back-stack. This Activity will run in the application's current task if the application is currently active, and it will be put on top of the most recent Activity that is open.
  • In onCreate() of this new Activity, check if this Activity is the root of the task using isTaskRoot(). If this Activity is the root of the task, this means that the app was not active prior to launching this Activity. In this case, you can create an artificial back-stack using TaskStackBuilder and launch the thing again the way you want it (this will reset the task).

Upvotes: 6

Related Questions