第一种:
private long exitTime = 0;
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(getApplicationContext(), "再按一次退出程序",
Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
ActivityStack.create().AppExit(TabMainActivity.this);
}
return true;
}
return super.dispatchKeyEvent(event);
}
第二种:
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK&& event.getAction()==KeyEvent.ACTION_DOWN) {
showLoginOutDialog();
return true;
}
return super.dispatchKeyEvent(event);
}
/**
* 退出程序
*/
private void showLoginOutDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("温馨提示");
dialog.setMessage("您确定要退出客户端吗?");
dialog.setPositiveButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.setNegativeButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MainActivity.this.finish();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
}).create();
dialog.show();
}