首页 > 代码库 > Android退出事件处理

Android退出事件处理

为了防止用户误点退出键,很多应用都需要按两次退出键才会退出程序。下面介绍两种方法实现:

按照两次退出键的时间判断:

private long lastClickTime = 0;

    @Override
    public void onBackPressed() {
        if (lastClickTime <= 0) {
            Toast.makeText(this, "再按一次后退键退出应用", Toast.LENGTH_SHORT).show();
            lastClickTime = System.currentTimeMillis();
        } else {
            long currentClickTime = System.currentTimeMillis();
            if (currentClickTime - lastClickTime < 2000){
                finish();
            } else {
                Toast.makeText(this, "再按一次后退键退出应用", Toast.LENGTH_SHORT).show();
                lastClickTime = System.currentTimeMillis();
            }
        }

按照是否连续点击退出键判断:

  protected int mFinishCount = 0;

  @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        mFinishCount = 0;
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void finish() {
        mFinishCount++;
        if (mFinishCount == 1) {
            Toast.makeText(this, "再按一次退出!", Toast.LENGTH_LONG).show();
        } else if (mFinishCount == 2) {
            super.finish();
        }
    }

 

Android退出事件处理