Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've read through several posts about using this, but must be missing something as it's not working for me. My activity A has launchmode="singleTop" in the manifest. It starts activity B, with launchmode="singleInstance". Activity B opens a browser and receives and intent back, which is why it's singleInstance. I'm trying to override the back button so that the user is sent back to the activity A, and can then press Back to leave the activity, rather than back to activity B again.

// activity B @Override public boolean onKeyDown(int keyCode, KeyEvent event)  {  if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR   && keyCode == KeyEvent.KEYCODE_BACK   && event.getRepeatCount() == 0) onBackPressed();  return super.onKeyDown(keyCode, event); } @Override public void onBackPressed() {  startActivity(new Intent(this, UI.class)  .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));  return; } 

After returning from the browser, the stack is... A,B,Browser,B

I expect this code to change the stack to... A ... so that pressing back once more takes the user back to the Home Screen.

Instead it seems to change the stack to... A,B,Browser,B,A ...as though those flags aren't there.

I tried calling finish() in activity B after startActivity, but then the back button takes me back to the browser again!

What am I missing?

like image 471
piusvelte Avatar asked Dec 03 '10 05:12

piusvelte


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.


1 Answers

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:

@Override public 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); }        
like image 127
Jesper Bischoff-Jensen Avatar answered Oct 14 '22 08:10

Jesper Bischoff-Jensen