1

`

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.

Jhanak Didwania
  • 581
  • 2
  • 5
  • 12
  • You don't need to call `finish()`. Activity A is already in the stack, `FLAG_ACTIVITY_CLEAR_TOP ` should clear all Activities on-top of Activity A. How do you start Activity E? – HedeH Jul 01 '18 at 12:19
  • @HedShafran Yeah you are right, I just missed it. I started activity E after finishing activity D as i would never need activity D again in the same application flow. – Jhanak Didwania Jul 01 '18 at 12:29

1 Answers1

1

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.

Jhanak Didwania
  • 581
  • 2
  • 5
  • 12
  • I have found a still better solution. Just override the onRestart() method of the mainActivity class which is having the login button: getIntent().setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Then whenever this activity is resumed from activity stack, all activity on it's top will be cleared. No need to set intent flag for main activity in any other activity. – Jhanak Didwania Jul 01 '18 at 12:45