Manipulating task back stack in android

109 Views Asked by At

`

public void SignOut(View view) {
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }

`I have an android application. Activities are like -> A->B->C->D->E. Activity A have login page. So on moving to next activity, that is B, i don't finish activity A. Stack grows like: A,B,C,D then activity D is finished and E is started. In activity E, I have a sign out button. Till now my stack is: A,B,C,E. On pressing sign-out, E is popped out. I want to clear the activity stack at this point and want to start my first activity i.e. A which is asking for login. I can't achieve this. My stack becomes A,B,C,A after sign out. I want the stack to be A only. Please help. Thanks in advance.

1

There are 1 best solutions below

1
On

I have solved the issue.

Along with the above mentioned code, inside my main activity class, in onRestart() function, i added the code:

getIntent().setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

This ensured that whenever this activity is called, like in my case, it is called from last activity. At this point, it is already either in onPaused() state and then in onStop() state if the next activity fully covered it, and it will be Restarted again. At this point, clear the back stack of activity A (that is all the activities on top of A) if it has anything on the stack for a fresh start.