Android 双击退出应用程序

Android About 1,141 words

双击退出程序

方式一:

private boolean isExit;
private Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        isExit = false;
    }
};
@Override
public void onBackPressed() {
    if (mFm.getBackStackEntryCount() != 0) {//添加fragment时会用到
        super.onBackPressed();
        return;
    }
    if (!isExit) {
        isExit = true;
        Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
        mHandler.sendEmptyMessageDelayed(0, 2000);
    } else {
        finish();
    }
}

方式二:

private long currentBackPressedTime = 0;
// 退出间隔
private static final int BACK_PRESSED_INTERVAL = 2000;
//重写onBackPressed()方法,继承自退出的方法
@Override
public void onBackPressed() {
    // 判断时间间隔
    if (System.currentTimeMillis() - currentBackPressedTime > BACK_PRESSED_INTERVAL) {
        currentBackPressedTime = System.currentTimeMillis();
        Toast.makeText(this, "再按一次返回键退出程序", Toast.LENGTH_SHORT).show();
    } else {
        // 退出
        super.onBackPressed();
    }
}

退出到桌面

不是真实退出程序。

调用activitymoveTaskToBack(boolean nonRoot);方法。

moveTaskToBack(true);
Views: 3,964 · Posted: 2019-04-09

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh