简体   繁体   中英

How to clear the activity stack in android?

I'm having a requirement where i can press a logout button from any activity in the application,the thing is when I press the logout button I need to get the login screen without showing the previous activities. I am using:

intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP )

I am starting the activity like this:

public void onClick(View v) {
  try
  {
      Intent intent = new Intent(getContext(), Login.class);
      v.getRootView().getContext().startActivity(intent);
      intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
      removeSessionFiles();
      //startActivity (new Intent(getApplicationContext(), Activity1.class));
  }
  catch (Exception e)
  {
    String str = e.toString();
  }
}

I get to the login screen when I press the logout button, but when I press back button on the device it is showing the previous activities - I should go to the Android home screen when I press back button in the login screen. Please can you suggest a solution for this?

As dinash said above the flag should be set before the activity is started...whats the point of setting the flag after starting the activity....the code should look something like this,

Intent intent = new Intent(getContext(), Login.class);
intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
      v.getRootView().getContext().startActivity(intent);

      removeSessionFiles();

setFlags before calling startActivity will solve your problem

public void onClick(View v) {

try { 
Intent intent = new Intent(getContext(), Login.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP ); 
v.getRootView().getContext().startActivity(intent);
removeSessionFiles(); 
} catch (Exception e) {
String str = e.toString();
}
}

ho man just put the flag setting line just before the startactivity line... This wil solve your problem...

Hope this helps...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM