Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Clear Activity Stack

I'm having several activities in my application. and flow is very complicated. When I click the Logout application navigates to login Screen and from there user can exit by cancel button (calling system.exit(0) )

when I exit or back button, the system invokes an activity from stack :( how can I clear all the activities in the stack when I reach Login screen? calling finish() is not practical as there are so many activities and some activities should no be closed when they are active such as native camera invoking activity.

validateuser logoutuser = new validateuser();
logoutuser.logOut();
Intent loginscreen = new Intent(homepage.this, Login2.class);
(homepage.this).finish();
loginscreen.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(loginscreen);
like image 676
Jay Mayu Avatar asked Oct 06 '22 13:10

Jay Mayu


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 do I delete all previous activities?

For API 11+ you can use Intent. FLAG_ACTIVITY_CLEAR_TASK|Intent. FLAG_ACTIVITY_NEW_TASK like this: It will totally clears all previous activity(s) and start new activity.


2 Answers

Most of you are wrong. If you want to close existing activity stack regardless of what's in there and create new root, correct set of flags is the following:

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

From the doc:

public static final int FLAG_ACTIVITY_CLEAR_TASK
Added in API level 11

If set in an Intent passed to Context.startActivity(), this flag will cause any existing task that would be associated with the activity to be cleared before the activity is started. That is, the activity becomes the new root of an otherwise empty task, and any old activities are finished. This can only be used in conjunction with FLAG_ACTIVITY_NEW_TASK.

like image 97
Cynichniy Bandera Avatar answered Oct 12 '22 22:10

Cynichniy Bandera


When you call startActivity on the last activity you could always use

Intent.FLAG_ACTIVITY_CLEAR_TOP

as a flag on that intent.

Read more about the flag here.

like image 26
David Olsson Avatar answered Oct 13 '22 00:10

David Olsson