方法一:按两次退出程序
/**
* 按返回按钮
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
long thisTime = System.currentTimeMillis();
if(thisTime > mBackTime && (thisTime-mBackTime)<3000 && mBackTime!=0){
tag = 1;
tag_page = -1;
if(null!=Constant.gongDanInfoArr){
Constant.gongDanInfoArr.clear();
Constant.gongDanInfoArr= null;
}
stopService(new Intent(this, GPSService.class));
ReceiveGongDanService.myTag = 0;
finish();
}else{
Toast.makeText(this, "再按一次退出系统!", Toast.LENGTH_SHORT).show();
mBackTime = thisTime;
}
}
return false;
}
方法二:提示退出程序
/**
* 按返回按钮
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// 创建退出对话框
AlertDialog isExit = new AlertDialog.Builder(this).create();
// 设置对话框标题
isExit.setTitle("温馨提示");
// 设置对话框消息
isExit.setMessage("确定要退出吗?");
// 添加选择按钮并注册监听
isExit.setButton("确定", listener);
isExit.setButton2("取消", listener);
// 显示对话框
isExit.show();
}
return false;
}
/** 监听对话框里面的button点击事件 */
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
tag = 1;
tag_page = -1;
if(null!=Constant.gongDanInfoArr){
Constant.gongDanInfoArr.clear();
Constant.gongDanInfoArr = null;
}
finish();
break;
case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框
break;
default:
break;
}
}
};
方法三:模拟QQ,微信等退出sss
1.将程序退出到后台运行,只是假退出
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(false);
return true;
}
return super.onKeyDown(keyCode, event);
}
2.将程序完全退出/**
* 退出程序
*/
public void quit(){
stopService(new Intent(this, GPSService.class));
stopService(new Intent(this, ReceiveGongDanService.class));
finish();
}