Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear specific activity from the stack history?

Tags:

android

Suppose I have an application containing activities named A,B,C,D. Now, consider A has been launched as the root activity and B has been launched from A and C has been launched from B and D has been launched from C. Now I have a button named "Remove" in the activity D. If suppose, I press the button "Remove" in the activity D, then the activity B and activity C should be removed from the history stack. On Pressing back key from the activity D should display activiy A instead of C. I don't know how to implement this. Can anyone help me to resolve this problem?

like image 874
Prasath Avatar asked Feb 15 '11 09:02

Prasath


People also ask

How do I delete activity from Stack?

The easiest way is to give the LoginActivity a “android:noHistory = true” attribute in the manifest file. That instructs Android to remove the given activity from the history stack thereby avoiding the aforementioned behavior altogether.

How do I start activity and clear back stack?

Declare Activity A as SingleTop by using [android:launchMode="singleTop"] in Android manifest. Now add the following flags while launching A from anywhere. It will clear the stack.

How can I see activity stack?

Just open the perspective Windows->Open Perspective-> Hierarchy View In the list you can see the all the connected devices and emulators and the activity stack. And in addition in the tree view you can see much more information about the view itself.


2 Answers

I'm not sure you can directly programmatically remove activities from the history, but if you use startActivityForResult() instead of startActivity(), then depending on the return value from your activity, you can then immediately finish() the predecessor activity to simulate the behaviour you want. By using this method in all your activities, you can have this behaviour cascading the activity stack to allow you to go from activity D to activity A.

I know this isn't your situation, but in future if you know before you start the activity that you don't want the predecessor to remain, you can call finish() immediately after startActivity().

Please see the section called "Lifetime of the New Screen" in Common Tasks and How to do Them in Android

like image 58
RivieraKid Avatar answered Sep 21 '22 07:09

RivieraKid


I agree with @RivieraKid, but I think of another way: When you press "Remove" you set a custom flag to true.

Override the back key event:

public void onBackPressed() {   if (!remove){     super.onBackPressed();   }else{     Intent goToA = new Intent((this,ActivityA.class););     goToA.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);     startActivity(goToA);   } } 

Do you think this does what you want?

Good luck.

like image 21
mdelolmo Avatar answered Sep 22 '22 07:09

mdelolmo