首页 > 代码库 > 退出应用的2种方式

退出应用的2种方式

实现退出方式要activity的 boolean onKeyDown(int keyCode, KeyEvent event) 方法里实现

直接见代码吧:

方法一:

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //退出方法一
        if(keyCode == KeyEvent.KEYCODE_BACK){
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setTitle("提示");
            dialog.setMessage("确定要残忍地退出应用?");
            dialog.setPositiveButton("确定",new DialogInterface.OnClickListener(){
                @Override
                public void onClick(DialogInterface dialog, int which) {
                   finish();
                }
            });
            dialog.setNegativeButton("取消",new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                      return ;
                }
            });
            dialog.show();
        }
        
        return super.onKeyDown(keyCode, event);
    }



方法二:

private long existTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //退出方法二
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
           if(System.currentTimeMillis()-existTime > 2000){
               Toast.makeText(this,"再按一次退出应用",Toast.LENGTH_SHORT).show();
               existTime =  System.currentTimeMillis();
           }else {
               finish();
           }
           return true; //退出
        }
        return super.onKeyDown(keyCode, event);
    }



退出应用的2种方式