话不多说直接上代码:
首先我们新建一个工具类用来管理activity
public class CommonAction {
private List<Activity> AllActivitites = new ArrayList<Activity>();
private static CommonAction instance;
public CommonAction() {
}
public synchronized static CommonAction getInstance() {
if (null == instance) {
instance = new CommonAction();
}
return instance;
}
//在Activity基类的onCreate()方法中执行
public void addActivity(Activity activity) {
AllActivitites.add(activity);
}
//注销是销毁所有的Activity
public void OutSign() {
for (Activity activity : AllActivitites) {
if (activity != null) {
activity.finish();
}
}
}
}
接下来在你的MainActivity中进行对于连点两次的退出
// 定义一个变量,来标识是否退出
private static boolean isExit = false;
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
isExit = false;
}
};
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exit();
return false;
}
return super.onKeyDown(keyCode, event);
}
private void exit() {
if (!isExit) {
isExit = true;
Toast.makeText(getApplicationContext(), "再按一次退出程序",
Toast.LENGTH_SHORT).show();
// 利用handler延迟发送更改状态信息
mHandler.sendEmptyMessageDelayed(0, 2000);
} else {
finish();
CommonAction.getInstance().OutSign();
System.exit(0);
}
}
看到这那个工具类 添加 addActivity怎么没用,那是对于那些没销毁的activity使用的。
使用时只需要在activity oncreate时加入这么一句就行了
CommonAction.getInstance().addActivity(this);
网友评论