Android双击退出

时间:2022-05-25 01:16:52

重写返回键

private long tempTime = 0;

/**
* 双击退出
*/
@Override
public void onBackPressed() {
long firstClick = System.currentTimeMillis();
if (firstClick - tempTime < 500) {
ToastUtil.cancel();
super.onBackPressed();
} else {
ToastUtil.show(this, "再按一次退出");
}
tempTime = firstClick;
}

Toast工具类

package com.bitmain.btccom.utils;

import android.content.Context;
import android.widget.Toast; /**
* Created by kongqw on 2015/11/21.
*/
public final class ToastUtil { private static Toast mToast; // 工具类私有化
private ToastUtil() {
} // 单例模式 显示Toast
public static void show(Context context, String text) {
if (null == mToast) {
mToast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
}
mToast.setText(text);
mToast.show(); } // 关闭Toast
public static void cancel() {
if (null != mToast)
mToast.cancel();
}
}