6

When a user taps "Logout" within my application, I would like them to be taken to the "Login" activity and kill all other running or paused activities within my application.

My application is using Shared Preferences to bypass the "Login" activity on launch if the user has logged in previously. Therefore, FLAG_ACTIVITY_CLEAR_TOP will not work in this case, because the Login activity will be at the top of the activity stack when the user is taken there.

Jason Fingar
  • 3,358
  • 1
  • 21
  • 27

3 Answers3

12

You could use a BroadcastReceiver to listen for a "kill signal" in your other activities

http://developer.android.com/reference/android/content/BroadcastReceiver.html

In your Activities you register a BroadcastReceiver

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("CLOSE_ALL");
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    // close activity
  }
};
registerReceiver(broadcastReceiver, intentFilter);

Then you just send a broadcast from anywhere in your app

Intent intent = new Intent("CLOSE_ALL");
this.sendBroadcast(intent);
Karl-Bjørnar Øie
  • 5,554
  • 1
  • 24
  • 30
8

For API 11+ you can use Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK like this:

Intent intent = new Intent(this, MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);

It will totally clear all previous activity(s) and start new activity.

madx
  • 6,723
  • 4
  • 55
  • 59
2

Instead of FLAG_ACTIVITY_CLEAR_TOP use FLAG_ACTIVITY_CLEAR_TASK (API 11+ though):

If set in an Intent passed to Context.startActivity(), this flag will cause any existing task that would be associated with the activity to be cleared before the activity is started. That is, the activity becomes the new root of an otherwise empty task, and any old activities are finished. This can only be used in conjunction with FLAG_ACTIVITY_NEW_TASK.

kabuko
  • 36,028
  • 10
  • 80
  • 93