我想只在连续双击时退出应用程序。我正在使用片段类。我使用下面的代码,但没有工作
private long lastPressedTime;
private static final int PERIOD = 2000;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
switch (event.getAction()) {
case KeyEvent.ACTION_DOWN:
if (event.getDownTime() - lastPressedTime < PERIOD) {
finish();
} else {
Toast.makeText(getApplicationContext(), "Press again to exit.",
Toast.LENGTH_SHORT).show();
lastPressedTime = event.getEventTime();
}
return true;
}
}
return false;
}
请指导我如何在应用中实现此功能。
答案 0 :(得分:0)
删除onKeydown中的实现并尝试此代码
@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();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
答案 1 :(得分:0)
答案 2 :(得分:0)
试试这个:
private boolean doubleBackToExitPressedOnce;
@Override
public void onBackPressed() {
Log.i(tag, "Start: On Back Pressed!");
if (doubleBackToExitPressedOnce) {
Log.i(tag, "Double Back Pressed!");
super.onBackPressed();
return;
}
doubleBackToExitPressedOnce = true;
Toast.makeText(this, R.string.msg_exit, Toast.LENGTH_SHORT).show();
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2500);
}
别忘了在onResume中添加这一行:
@Override
protected void onResume() {
doubleBackToExitPressedOnce = false;
}