19.再按一次退出应用

转载请注明出处 http://blog.csdn.net/qq_31715429/article/details/50977996
本文出自:猴菇先生的博客

方法一(最麻烦):
(1). Exit.java:

package com.monkey.mushroom.utils;

import android.os.Handler;
import android.os.HandlerThread;

public class Exit {
    private boolean isExit = false;
    /**
     * 退出应用广播
     **/
    public static final String EXIT_APP_MESSAGE_INTENT = "android.intent.action.Exit_App";
    private Runnable task = new Runnable() {
        @Override
        public void run() {
            isExit = false;
        }
    };

    public void doExitInOneSecond() {
        isExit = true;
        HandlerThread thread = new HandlerThread("doTask");
        thread.start();
        new Handler(thread.getLooper()).postDelayed(task, 1000);
    }

    public boolean isExit() {
        return isExit;
    }

    public void setExit(boolean isExit) {
        this.isExit = isExit;
    }
}

(2). MainActivity.java:

private Exit mExit = new Exit();

@Override
public void onBackPressed() {
    if (mExit.isExit()) {
        finish();
        System.exit(0);
    } else {
        mExit.doExitInOneSecond();
        ToastUtil.show(this, "再按一次退出应用");
    }
}

方法二(最经典):

private boolean isExit = false;

@Override
public void onBackPressed() {
    if (isExit) {
        finish();
        System.exit(0);
    } else {
        isExit = true;
        ToastUtil.show(this, R.string.exit);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isExit = false;
            }
        }, 2000);
    }
}

方法三(最简单):

private long exitTime = 0;

@Override
public void onBackPressed() {
    if((System.currentTimeMillis()- exitTime)>2000){
        ToastUtil.show(this, R.string.exit);
        exitTime = System.currentTimeMillis();
    }else{
        super.onBackPressed();
    }
}

你可能感兴趣的:(Android)