Search code examples
androidandroid-activitystacklifecycle

Remove Activities from Stack


In Main, there are buttons to start A and X

          /--> A --> B
         / 
    Main
         \
          \--> X 

There is a button in B to take it from B --> X. If that happens, A and B should be removed from the activity stack, so that pressing back in X returns to Main


Solution

  • Try this on Activity X

    @Override
    public void onBackPressed(){
    Intent i = new Intent(X.this, Main.class);
    i.setFlags(FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(i); 
    }
    

    It Will Clear the Activity Stack and launches the Main Activity. So if you press back from Activity B it goes to Activity A. Back in Activity X will launch your Main Activity with no history in your stack.