Android - 在注销时终止所有活动

Jas*_*gar 6 android

当用户在我的应用程序中点击"Logout"时,我希望他们进入"Login"活动并终止我的应用程序中的所有其他正在运行或暂停的活动.

如果用户之前已登录,我的应用程序正在使用共享首选项绕过启动时的"登录"活动.因此,FLAG_ACTIVITY_CLEAR_TOP在这种情况下不起作用,因为当用户被带到那里时,Login活动将位于活动堆栈的顶部.

Kar*_*Øie 12

您可以使用BroadcastReceiver在其他活动中侦听"终止信号"

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

在您的活动中,您注册了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);
Run Code Online (Sandbox Code Playgroud)

然后,您只需从应用中的任何位置发送广播

Intent intent = new Intent("CLOSE_ALL");
this.sendBroadcast(intent);
Run Code Online (Sandbox Code Playgroud)


mad*_*adx 8

对于API 11+,您可以这样使用Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK:

Intent intent = new Intent(this, MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

它将完全清除所有以前的活动并开始新的活动.