Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear backstack of a task and leave only the new activity?

Tags:

android

I want to clear the backstack when I start new Activity intent.

The exact case of my problem is as following: I have activities like this A > B > C > D > E "A" is a registration activity and "B" is a confirm registration activity. I want that when user start activity "B" that he can't back to activity "A" anymore, also when user reach activity "C", both activity "A" and "B" would be useless, I don't need user back to them anymore.

Also when user moves to activity "D" from "C", he can get back to "C" but if he moved further to "E" activity, he can't get back to any of the previous "C" or "D" activities.

After a lot of research, the best I got is to use flag: FLAG_ACTIVITY_NO_HISTORY, But it has two problems for my case:

  1. At activity "A" if user navigate away from my application (for example to home screen), it destroy that activity and hence all information that user entered is lost!
  2. Activity "C" I want keep it in history (backstack) if while user navigate to "D" activity but when user move to "E" activity I want remove it.

I can't find a solution for this problem till now, I think it would be easier if there something to clear the backstack of current task!

My minimum SDK support is 5.

Thanks in advance.

like image 591
Elkfrawy Avatar asked Oct 24 '12 15:10

Elkfrawy


People also ask

How do you exclude activity from the Backstack?

simple solution for API >= 15 to API 23 user activity name in intent. Show activity on this post. To remove activity from back stack inside manifest add android:noHistory="true" to your activity inside the manifest file.


1 Answers

If you are using API level 11 or higher you can simply add the FLAG_ACTIVITY_CLEAR_TASK on your intent, which will clear all the other activities in your task.

Otherwise, this might help: Clearing the full Android activity stack on older SDKs (that lack FLAG_ACTIVITY_CLEAR_TASK)

Another approach, would be for you to finish the activities you no longer want the user to be able to return to. For instance, if you call ActivityA.finish() before moving to B, the activity will be removed from the task.

When you start the activity D, you can start it using startActivityForResult() from C, and when you close D, send the result to C, and then finish activity C before navigating to E.

like image 89
kleinsenberg Avatar answered Nov 14 '22 23:11

kleinsenberg