Foenix
Foenix

Reputation: 991

Remove all activities except the first one

I want to program Home button, so it will remove all Activities in stack, except one. I did it like in here: How to finish every activity on the stack except the first in Android

public boolean onOptionsItemSelected(MenuItem item) {
    int itemId = item.getItemId();
    switch (itemId) {
    case android.R.id.home:
        Intent intent = new Intent(this, AMainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        startActivity(intent);
        break;
...

but this way doesn't suit me, because it removes ALL Activities (including the first one) and starts the first one again. For example - if I check user password in onCreate(), he would be asked again. How to remove all Activities from stack, but so the first one will not be "touched" ?

Upvotes: 5

Views: 1451

Answers (3)

Shridutt Kothari
Shridutt Kothari

Reputation: 7394

add following property to your AMainActivity's Activity tag in your manifest.xml.

android:launchMode="singleTop"

Upvotes: 2

andr
andr

Reputation: 16054

Yes, according to the documentation of Intent.FLAG_ACTIVITY_CLEAR_TOP:

The currently running instance of activity B in the above example will either receive the new intent you are starting here in its onNewIntent() method, or be itself finished and restarted with the new intent. If it has declared its launch mode to be "multiple" (the default) and you have not set FLAG_ACTIVITY_SINGLE_TOP in the same intent, then it will be finished and re-created; for all other launch modes or if FLAG_ACTIVITY_SINGLE_TOP is set then this Intent will be delivered to the current instance's onNewIntent().

So, use additional Intent flag:

intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

And your activity should not be recreated. Instead, it will just get the new intent delivered via a call to onNewIntent().

Upvotes: 2

AAnkit
AAnkit

Reputation: 27549

You can use ExcludeFromRecent = "true" flag in Activities declaration in manifest, which you don’t want to be in Stack.

Upvotes: 0

Related Questions