androidandroid-activityactivity-stack

How to manage Activity instances in Android


I have an initial activity O and one more activity A in which i can select to go to activities A1,A2,A3 and for example fill in a form in each of them. So i follow this path:

O>A>A1>A>A2>A>A3

While i am at A3 i want to press the back button and go to O again but i will have to pass from every instance of A (let's assume i use finish() or no history in the manifest for A1,A2,A3 so they will be not present in the stack)

how can i declare that A will only have one instance (the last one) in the stack, so that if i press back button twice i will go to O again?


Solution

  •   @Override
    public void onBackPressed() {
        Intent intent = new Intent(this,O.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }