How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack? How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack? java java

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?


I have started Activity A->B->C->D.When the back button is pressed on Activity D I want to go to Activity A. Since A is my starting point and therefore already on the stack all the activities in top of A is cleared and you can't go back to any other Activity from A.

This actually works in my code:

@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {    if (keyCode == KeyEvent.KEYCODE_BACK) {        Intent a = new Intent(this,A.class);        a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);        startActivity(a);        return true;    }    return super.onKeyDown(keyCode, event);}       


@bitestar has the correct solution, but there is one more step:

It was hidden away in the docs, however you must change the launchMode of the Activity to anything other than standard. Otherwise it will be destroyed and recreated instead of being reset to the top.


For this, I use FLAG_ACTIVITY_CLEAR_TOP flag for starting Intent
(without FLAG_ACTIVITY_NEW_TASK)

and launchMode = "singleTask" in manifest for launched activity.

Seems like it works as I need - activity does not restart and all other activities are closed.