在按下后退按钮两次之前关闭活动

时间:2016-08-19 07:36:33

标签: android android-fragments

我想在按两次后退按钮后关闭应用程序。我有不同的片段加载活动。我只想在主(主)片段和用户按下两次按钮时关闭应用程序。但它不能正常工作。这是关闭活动的代码: -

@Override
public void onBackPressed() {

    if (getFragmentManager().getBackStackEntryCount() == 0) {
        //super.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);

    } else {
        backFlag = 1;
        getFragmentManager().popBackStack();
    }

给我“两次按回按钮”的信息,但片段没有转移到主片段。请帮我解决这个问题

  

编辑问题

if (getFragmentManager().getBackStackEntryCount() == 0) {
        super.onBackPressed();

    } else {
        getFragmentManager().popBackStack();
    }

1 个答案:

答案 0 :(得分:0)

您可以通过再次按下两秒间隔来尝试此替代方法来实现此目的:

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