Android 再按一次退出程序

第一种实现方式

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 boolean isExit;
    private Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                isExit = false;
            }
        };
    }
  public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            if(!isExit){
                isExit = true;
                handler.sendEmptyMessageDelayed(0, 1500);
                Toast.makeText(this, "再按一次推出程序", 1000).show();
                return false;
            }else{
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

最简单的方式 我经常用的

在全局定义一个变量 private boolean isBackPressed;
在Activity中重写onBackPressed() 方法

  @Override
    public void onBackPressed() {
        if (isBackPressed) {
            super.onBackPressed();
            AppManager.getAppManager().finishActivity(LoginActivity.class);
            AppManager.getAppManager().finishAllActivity();
            return;
        }
        isBackPressed = true;
        ToastUtils.showShort("再按一次退出程序");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isBackPressed = false;
            }
        }, 2000);
    }

你可能感兴趣的:(Android 再按一次退出程序)