Search code examples
androidandroid-intentandroid-activityback-stack

Clearing the full Android activity stack on older SDKs (that lack FLAG_ACTIVITY_CLEAR_TASK)


I've done qui a bit of reading and searching on SO, but can't find a way to clear the current activity stack. The context of my app is an activity started by a a background service / notification.

Imagine that my app allows you to organise a list of people. A few hours ago, you were viewing person X in the "View" activity, that's now the top of your stack. At some point in the future, the service triggers and I popup a new "Notify" activity for person Y. From there you can edit person Y's details.

When you finish this activity, it would be a confusing user experience to pop the stack and end up viewing person X. Ideally I'd like to go back to whatever the user was doing (email etc...), or at least to my app's home.

I tried starting "Notify" with FLAG_ACTIVTY_NEW_TASK but that doesn't seem to help: when the task finishes it simply goes back to the previous task. What I want seems to be Android 3's new FLAG_ACTIVITY_CLEAR_TASK, which doesn't exist in previous SDKs.

Does anyone have a suggestion to achieve that?


Solution

  • If you already have an instance of your app's home running in the stack, when activity Y finishes you could start your app's home (using startActivity()) with the flag FLAG_ACTIVITY_CLEAR_TOP. As it's already on the stack, instead of creating a new instance of it, this would bring you back to your app's home and clear the stack on top of it.