Sudheesh B Nair在这个问题上有一个很好的(和被接受的)答案,我认为这应该有一个更好的选择,例如;
测量经过的时间并检查自上次反向按下以来是否经过了毫秒(例如2000)有什么问题。以下代码示例用于存储时间被调用;TIME_INTERVAL
System.currentTimeMillis();
onBackPressed()
private static final int TIME_INTERVAL = 2000; // # milliseconds, desired time passed between two back presses.
private long mBackPressed;
@Override
public void onBackPressed()
{
if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis())
{
super.onBackPressed();
return;
}
else { Toast.makeText(getBaseContext(), "Tap back button in order to exit", Toast.LENGTH_SHORT).show(); }
mBackPressed = System.currentTimeMillis();
}
回到公认的答案批评;使用一个标志
来指示它是否在最后(比如2000)毫秒内按下并设置- 重置是通过 的方法,这是我脑海中出现的第一件事。但是,当活动关闭时,应取消该操作,并删除 .TIME_INTERVAL
Handler
postDelayed()
postDelayed()
Runnable
为了删除 ,它不得被声明为匿名,并且与成员一起声明为成员。那么方法就可以适当地调用。Runnable
Handler
removeCallbacks()
Handler
下面的示例是演示;
private boolean doubleBackToExitPressedOnce;
private Handler mHandler = new Handler();
private final Runnable mRunnable = new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
};
@Override
protected void onDestroy()
{
super.onDestroy();
if (mHandler != null) { mHandler.removeCallbacks(mRunnable); }
}
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
mHandler.postDelayed(mRunnable, 2000);
}
感谢@NSouth的贡献;为了防止即使在应用程序关闭后也出现Toast消息,可以声明为成员 - 例如 - 并且可以通过调用前取消。Toast
mExitToast
mExitToast.cancel();
super.onBackPressed();