在android中的双选项卡上的应用程序退出

时间:2015-01-29 12:35:28

标签: android double exit tap

我想只在连续双击时退出应用程序。我正在使用片段类。我使用下面的代码,但没有工作

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;
}

请指导我如何在应用中实现此功能。

3 个答案:

答案 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)

@Override
public void onBackPressed() {}

在您的活动中,因为负责后退按钮处理的活动

查看this问题,它没有得到接受的答案,但包含一些解决方案

答案 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;
}