Search code examples
androidback-stack

Android: Remove all the previous activities from the back stack


When i am clicking on Logout button in my Profile Activity i want to take user to Login page, where he needs to use new credentials.

Hence i used this code:

Intent intent = new Intent(ProfileActivity.this,
        LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

in the onButtonClick of the Logout button.

But the problem is when i click device back button on the Login Activity it takes me to the ProfileActivity. I was expecting the application should close when i press device back button on LoginActivity.

What am i doing wrong?

I also added android:launchMode="singleTop" in the manifest for my LoginActivity

Thank You


Solution

  • The solution proposed here worked for me:

    Java

    Intent i = new Intent(OldActivity.this, NewActivity.class);
    // set the new task and clear flags
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(i);
    

    Kotlin

    val i = Intent(this, NewActivity::class.java)
    // set the new task and clear flags
    i.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
    startActivity(i)
    

    However, it requires API level >= 11.