KeyEvent事件-再按一次退出 常见对话框退出
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
new AlertDialog.Builder(KeyEventTestActivity.this)
.setMessage("要退出吗")
.setNegativeButton("退出", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setPositiveButton("再看看",null)
.show();
return true;/**不会再退出了*/
}
return super.onKeyDown(keyCode, event);
}
有多个页面时 需要用intent强制退出
@Override
public void onBackPressed() {
if ((System.currentTimeMillis() - mExitTime) > 2000) {
Toast.makeText(this, "再次点击返回键退出界面",
Toast.LENGTH_SHORT).show();
mExitTime = System.currentTimeMillis();
} else {
goHome(this);
}
}
/**
* 回到桌面
*
* @param context 上下文
*/
public static void goHome(Context context) {
try {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startMain);
} catch (Exception e) {
e.printStackTrace();
}
}