Clear All Activities in a Task

Clear all activities in a task?

Yes that should work fine. You could use:

  • FLAG_ACTIVITY_CLEAR_TOP
  • FLAG_ACTIVITY_SINGLE_TOP
  • FLAG_ACTIVITY_CLEAR_TASK
  • FLAG_ACTIVITY_NEW_TASK

which ensures that if an instance is already running and is not top then anything on top of it will be cleared and it will be used, instead of starting a new instance (this useful once you've gone Welcome activity -> Activity A and then you want to get back to Welcome from A, but the extra flags shouldn't affect your case above).

How to clear all associated tasks?

I found that all my activities were added to a single task and we can remove task by calling below method-

finishAndRemoveTask()

More

This is how we can check in terminal activity stack and associated task-

adb shell dumpsys activity activities

Clear the entire history stack and start a new activity on Android

In API level 11 a new Intent Flag was added just for this: Intent.FLAG_ACTIVITY_CLEAR_TASK

Just to clarify, use this:

Java

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

Kotlin

intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK

Unfortunately for API lvl <= 10, I haven't yet found a clean solution to this.
The "DontHackAndroidLikeThis" solution is indeed pure hackery. You should not do that. :)

Edit:
As per @Ben Pearson's comment, for API <=10 now one can use IntentCompat class for the same. One can use IntentCompat.FLAG_ACTIVITY_CLEAR_TASK flag to clear task. So you can support pre API level 11 as well.

Android: Remove all the previous activities from the back stack

The solution proposed here worked for me:

Java

Intent i = new Intent(OldActivity.this, NewActivity.class);
// set the new task and clear flags
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);

Kotlin

val i = Intent(this, NewActivity::class.java)
// set the new task and clear flags
i.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(i)

However, it requires API level >= 11.



Related Topics



Leave a reply



Submit