long currentBackPressedTime;
private int countTime;
@Override
public void onBackPressed() {
if (System.currentTimeMillis() - currentBackPressedTime > 2000) {
AvcApplication.the().showToast(this, "再按一次返回键退出程序");
countTime = 0;
currentBackPressedTime = System.currentTimeMillis();
} else {
// 默认是2秒内完成所有点击,才执行操作
// 以下语句使每一次点击与它的上一次点击时间都可相差2秒,也会执行操作
// currentBackPressedTime = System.currentTimeMillis();
countTime++;
}
// countTime记录点击返回键的次数
if (countTime >= 1) {
//dosth
countTime = 0;
currentBackPressedTime = 0;
}
}
上面是写在返回键的回调中的代码,
逻辑:第一次点击后获取的当前时间减去0肯定大于2000
然后给currentBackPressedTime赋值,
然后再次点击获取的当前时间减去前面赋值的currentBackPressedTime在2秒内的话
countTime++ (如果只要点击两次的话 这里也可以直接dosth)
最后判断countTime的值来dosth (第二次成功点击才能++,所有countTime的值等于次数减1)