1、定义一个继承自Application的ExitApplication类
package com.example.weather;
import android.app.Activity;
import android.app.Application;
import java.util.ArrayList;
import java.util.List;
public class ExitApplication extends Application {
private List<Activity> activityList = new ArrayList<>();
private static ExitApplication instance;
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);
}
}
2、定义一个时间
private long exitTime;
3、在启动Activity中添加初始时间
exitTime=System.currentTimeMillis();
4、在每个Activity的onCreate()中添加这一句
ExitApplication.getInstance().addActivity(MainActivity.this);
5、在需要“再按一次(返回键)实现退出(应用程序)”的Activity中重写onBackPressed()方法
@Override
public void onBackPressed() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
}
else{
ExitApplication.getInstance().exit();
}
}