思路
将所有的activity添加到list集合中,通过点击事件对list集合中的activity进行遍历退出,*后应用退出。

Demo图片展示

%title插图%num

实现
创建一个ExitApplication类 对所有Activity的退出进行管理
public class ExitApplication extends Application{
private List<Activity> activityList = new ArrayList<>();
private static ExitApplication instance;

public ExitApplication(){}
public static ExitApplication getInstance(){
if(null == instance){
instance = new ExitApplication();
}
return instance;
}

//添加Activity到容器中
public void addActivity(Activity activity){
//Log.i(“activity”, “size:” + activityList.size());
//Log.i(“activity”, “name:” + activity.getIntent());
activityList.add(activity);
}

//遍历所有Activity并finish
public void exit(){
for(Activity activity : activityList){
//依次关闭
activity.finish();
//Log.i(“activity”, “del_size:” + activityList.size());
//Log.i(“activity”, “del_name:” + activity.getIntent());
}
//强制退出
System.exit(0);
}
}

在MainActivity,SecondActivity等Activity中将Activity添加进集合中(可以将exitActivity()方法抽取到BaseActivity中,在Demo中我抽取到BaseActivity中了)
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
exitActivity();

private void initView() {
//此处均为findViewById操作,跟主题无关,代码省略
}

private void initData() {
//跟主题无关,代码省略
}

//退出此Acitvity
private void exitActivity() {
ExitApplication.getInstance().addActivity(MainActivity.this);
}
}

在SecondActivity中和此MainActivity中的代码相同。

在有退出按钮的ThirdActivity中,实现点击按钮应用退出操作
public class ThirdActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
initView();
initData();
exitActivity();

private void initView() {
//此处均为findViewById操作,跟主题无关,代码省略
}

private void initData() {
//跟主题无关,代码省略
}

//退出此Acitvity
private void exitActivity() {
ExitApplication.getInstance().addActivity(ThirdActivity.this);
}

//点击按钮退出应用程序 在此按钮属性中设置了onClick = logout
public void logout(View view){
ExitApplication.getInstance().exit();
}
}