返回键捕获 应用程序退出的两种方式(转)

作为应用程序一个较好的用户体验应该是:在退出应用程序前询问用户是否真正退出?目前普遍做法是,一在退出前询问是否真正退出,二是连续按两下退出。

返回键捕获 应用程序退出的两种方

实现上述两种应用退出方式需要在onkeyDown()来进行捕获返回键

在Activity中,如果需要动态注册广播官方文档建议在onResume()进行注册,在onPause()中取消注册。注册部分代码如下:

应用程序退出方式一:确认退出对话框

public boolean onKeyDown(int keyCode, KeyEvent event) {
       if (keyCode == KeyEvent.KEYCODE_BACK){
           AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
           alertDialog.setTitle("提示");
           alertDialog.setMessage("确认退出马上学Android");
           alertDialog.setPositiveButton("确认",new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialogInterface, int i) {
                   finish();
               }
           });
           alertDialog.setNegativeButton("取消",new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialogInterface, int i) {
                   return;
               }
           });
           alertDialog.show();
       }
       return true;
}
  • 应用程序退出方式二:连续按两次确认退出
    private long exitTime = 0;
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            
            if((System.currentTimeMillis() - exitTime) >2000){
                Toast.makeText(this,"再按一次退出应用程序",Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
     }

    http://chenqichao.me/2014/04/18/037-Android-Tutorial-029/

原文地址:https://www.cnblogs.com/softidea/p/4821153.html