android studio 点击返回键退出程序的方法

  • Post author:
  • Post category:其他


  • 方法一:2秒内点击两次返回键退出
private long exitTime = 0;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){   
        if((System.currentTimeMillis()-exitTime) > 2000){  
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();                                
            exitTime = System.currentTimeMillis();   
        } else {
            finish();
            System.exit(0);
        }
        return true;   
    }
    return super.onKeyDown(keyCode, event);
}
  • 方法二:弹框退出
    请添加图片描述
private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            new AlertDialog.Builder(this)
                    .setTitle("确定退出吗?")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    })
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            finish();
                            System.exit(0);
                        }
                    })
                    .show();

        }
        return super.onKeyDown(keyCode, event);
    }
  • 这里用的是默认的弹框,当然你也可以自定义

    参考



版权声明:本文为afufufufu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。