原文地址:http://blog.csdn.net/dyllove98/article/details/8831948
贴代码:
public void exitclick(View view) { AlertDialog.Builder aa=new AlertDialog.Builder(this); aa.setTitle("消息提示"); aa.setMessage("确认退出?"); aa.setIcon(R.drawable.icon); aa.setPositiveButton("确定",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub MainActivity.this.finish(); } }); aa.setNegativeButton("取消", null); aa.create(); aa.show(); //this.finish(); }
还有就是按返回键提示退出,继续贴代码:
private void exitDialog() { AlertDialog.Builder aa=new AlertDialog.Builder(this); aa.setTitle("消息提示"); aa.setMessage("确认退出?"); aa.setIcon(R.drawable.icon); aa.setPositiveButton("确定",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub MainActivity.this.finish(); } }); aa.setNegativeButton("取消", null); aa.create(); aa.show(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { exitDialog(); } return true; }
现在还流行连续按两次返回退出,代码:
/*此段代码有误,
private static boolean isExit=false; private static boolean hasTask=false; Timer tExit=new Timer(); TimerTask task=new TimerTask() { @Override public void run() { // TODO Auto-generated method stub isExit=false; hasTask=false; } }; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { //exitDialog(); if(isExit==false) { isExit=true; Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show(); if(!hasTask) { tExit.schedule(task, 2000); } } else { finish(); System.exit(0); } } //return true; return false; }*/
1. 设置外部变量private static Boolean isExit = false;
2. 添加下列函数到Main Activity中
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(keyCode == KeyEvent.KEYCODE_BACK);
{
exitBy2Click();
}
return false;
}
private void exitBy2Click() {
// TODO Auto-generated method stub
Timer tExit = null;
if (isExit == false) {
isExit = true; // 准备退出
Toast.makeText(this, "Press Back again to quit", Toast.LENGTH_SHORT).show();
tExit = new Timer();
tExit.schedule(new TimerTask() {
public void run() {
isExit = false; // 取消退出
}
}, 2000); // 如果2秒钟内没有按下返回键,则启动定时器取消掉刚才执行的任务
}
else {
finish();
System.exit(0);
}
}