Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" ?

like image 408
Foenix Avatar asked Oct 06 '22 02:10

Foenix


2 Answers

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

android:launchMode="singleTop"
like image 86
Shridutt Kothari Avatar answered Oct 10 '22 03:10

Shridutt Kothari


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().

like image 27
andr Avatar answered Oct 10 '22 04:10

andr