请求用户允许关闭
应用程序。
您可以通过以下方式进行操作;
/**
* Exit the app if user select yes.
*/
private void doExit() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
AppDemoActivity.this);
alertDialog.setPositiveButton("Yes", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.setNegativeButton("No", null);
alertDialog.setMessage("Do you want to exit?");
alertDialog.setTitle("AppTitle");
alertDialog.show();
}
哪个是询问用户的好地方,
他是否想退出应用程序
他什么时候点击后退按钮的?
因为,您想在用户单击后退硬按钮时提示用户,正如其他人所建议的,您可以覆盖onBackPressed() https://developer.android.com/reference/android/app/Activity.html#onBackPressed()方法并从那里调用上面的方法;
@Override
public void onBackPressed() {
doExit();
}
正如建议的@Martyn https://stackoverflow.com/questions/6290599/prompt-user-when-back-button-is-pressed/6293317#comment7347547_6290629,您可以使用onKeyDown https://developer.android.com/reference/android/app/Activity.html#onKeyDown(int,%20android.view.KeyEvent)达到同样的目的;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK) {
doExit();
}
return super.onKeyDown(keyCode, event);
}
该应用程序还应该询问用户是否
尝试通过按钮退出应用程序
(在应用程序本身),而不是后硬
钥匙。
为此,请致电doExit()
来自按钮的 onClick;
Button exitButton = (Button)findViewById(R.id.exitButton);
exitButton.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(View v) {
doExit();
}
});
相关信息:
- 实施有效的导航 https://developer.android.com/training/implementing-navigation/