当用户在我的应用程序中点击"注销"时,我希望他们进入"登录"活动,并终止应用程序中所有其他正在运行或暂停的活动。
如果用户以前登录过,我的应用程序在启动时会使用共享首选项绕过"登录"活动。因此,FLAG_ACTIVITY_CLEAR_TOP在这种情况下将不起作用,因为当用户被带到那里时,Login活动将位于活动堆栈的顶部。
您可以使用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);
然后你只需在你的应用中的任何地方发送广播
Intent intent = new Intent("CLOSE_ALL");
this.sendBroadcast(intent);
对于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);
它将完全清除以前的所有活动并开始新的活动。
使用FLAG_ACTIVITY_CLEAR_TASK
(API 11+)代替FLAG_ACTIVITY_CLEAR_TOP
:
如果在传递给Context.startActivity()的Intent中设置,则此标志将导致在活动启动之前清除与该活动关联的任何现有任务。也就是说,该活动成为一个空任务的新根,所有旧活动都结束了。这只能与FLAG_ACTIVITY_NEW_TASK一起使用。