创建工具类如下:
package com.example.hxd.gittest;
import android.app.Activity;
import java.util.ArrayList;
import java.util.List;
/**
* 统一退出程序的操作
*/
class ActivitySetting {
//创建集合存储打开的Activity
static List<Activity> activityList = new ArrayList<>();
//添加打开的Activity到集合
static void addActivity(Activity activity) {
activityList.add(activity);
}
//移除集合内部的Activity
static void removeActivity(Activity activity) {
activityList.remove(activity);
}
//关闭所有的Activity
static void finishAllActivity() {
for (Activity activity : activityList) {
if (!activity.isFinishing()) {
activity.finish();
//杀死当前应用进程
android.os.Process.killProcess(android.os.Process.myPid());
}
}
}
}
在BaseActivity内部添加如下代码:
package com.example.hxd.gittest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
//添加当前操作的Activity到集合内部
ActivitySetting.addActivity(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
//移除无用的Activity
ActivitySetting.removeActivity(this);
}
}
具体Activity内部代码如下:
btnSecond.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//点击按钮退出程序,杀死进程
ActivitySetting.finishAllActivity();
}
});