首页 > 代码库 > 完全关闭App的两种做法

完全关闭App的两种做法

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

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

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

public class ExitAppReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

String action = intent.getAction();

if (action.equals("exit_app")){

if (context != null){

Log.i("exit_app", "onReceive: class = "+context.getClass().getName());

if (context instanceof Activity){

((Activity)context).finish();

}

if (context instanceof Service){

((Service)context).stopSelf();

}

}

}

}

}

public class BaseActivity extends AppCompatActivity {

private static final String TAG = "BaseActivity";

private ExitAppReceiver exitAppReceiver;

@Override

protected void onCreate(@Nullable Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

registerExitAppReceiver();//注册

}

@Override

protected void onDestroy() {

super.onDestroy();

unRegisterExitAppReceiver();//销毁

}

private void registerExitAppReceiver(){

IntentFilter filter = new IntentFilter();

filter.addAction("exit_app");

exitAppReceiver = new ExitAppReceiver();

registerReceiver(exitAppReceiver, filter);

}

private void unRegisterExitAppReceiver(){

unregisterReceiver(exitAppReceiver);

}

}

发送关闭所有Activity广播:

Intent intent = new Intent("exit_app");

sendBroadcast(intent);

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

ActivityCollector源码

public class ActivityCollector {

public static List<Activity> list = new ArrayList<>();

public static void addActivity(Activity activity){

list.add(activity);

}

public static void removeActivity(Activity activity){

list.remove(activity);

}

public static void finishAllActivity(){

for (Activity activity :list) {

if (!activity.isFinishing()){

activity.finish();

}

}

}

}

在BaseActivity中添加和移除:

@Override

protected void onCreate(@Nullable Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

ActivityCollector.addActivity(this);

}

@Override

protected void onDestroy() {

super.onDestroy();

ActivityCollector.removeActivity(this);

}


本文出自 “一剑围城” 博客,请务必保留此出处http://weijiancheng.blog.51cto.com/10190955/1897763

完全关闭App的两种做法