做项目的时候,涉及到一个注销登录的过程,这时候需要关闭之前打开的所有Activity。仅finish当前Activity显然是不够的,需要把返回栈中的Activity一个个销毁。我实践过的方法有两种:

1、基础类BaseActivity中注册广播接收器,接受关闭所有Activity的广播

2、基础类BaseActivity中将Activity加入一个集合中,并提供一个静态finishAll的方法统一关闭

备注:App中所有Activity直接或间接继承自BaseActivity。


一、使用广播接收器发送统一销毁广播

ExitAppReceiver 广播接收器代码:

publicclassExitAppReceiverextendsBroadcastReceiver{@OverridepublicvoidonReceive(Contextcontext,Intentintent){Stringaction=intent.getAction();if(action.equals("exit_app")){if(context!=null){if(contextinstanceofActivity){((Activity)context).finish();}if(contextinstanceofService){((Service)context).stopSelf();}}}}}

BaseActivity中注册销毁广播接收器:

publicclassBaseActivityextendsAppCompatActivity{privatestaticfinalStringTAG="BaseActivity";privateExitAppReceiverexitAppReceiver;@OverrideprotectedvoidonCreate(@NullableBundlesavedInstanceState){super.onCreate(savedInstanceState);registerExitAppReceiver();//注册}@OverrideprotectedvoidonDestroy(){super.onDestroy();unRegisterExitAppReceiver();//销毁}privatevoidregisterExitAppReceiver(){IntentFilterfilter=newIntentFilter();filter.addAction("exit_app");exitAppReceiver=newExitAppReceiver();registerReceiver(exitAppReceiver,filter);}privatevoidunRegisterExitAppReceiver(){unregisterReceiver(exitAppReceiver);}}


发送关闭所有Activity广播:

Intent intent = new Intent("exit_app");

sendBroadcast(intent);

二、采用ActivityCollector(方法参考郭霖《第一行代码》第2版)

ActivityCollector源码

publicclassActivityCollector{publicstaticList<Activity>list=newArrayList<>();publicstaticvoidaddActivity(Activityactivity){list.add(activity);}publicstaticvoidremoveActivity(Activityactivity){list.remove(activity);}publicstaticvoidfinishAllActivity(){for(Activityactivity:list){if(!activity.isFinishing()){activity.finish();}}}}

在BaseActivity中添加和移除:

@OverrideprotectedvoidonCreate(@NullableBundlesavedInstanceState){super.onCreate(savedInstanceState);ActivityCollector.addActivity(this);}@OverrideprotectedvoidonDestroy(){super.onDestroy();ActivityCollector.removeActivity(this);}