4

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.

JimVanB
  • 1,215
  • 1
  • 13
  • 29

2 Answers2

6

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).
David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • I came up with a different solution, that enables a flag in my singleton activity helper if my root activity was started. When I create my PendingIntent, I check for this flag. If it was set, then I don't use `TaskStackBuilder` but a normal Intent. This works as expected, but I think your solution is more elegant. I now use a PushOpenActivity that either routes to the real target via normal Intent or builds the activity stack. For everyone using this solution, remember setting `android:noHistory="true"` in your manifest to this activity. – JimVanB Aug 26 '16 at 10:43
0

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

BekaBot
  • 480
  • 1
  • 7
  • 19