0

当用户双击硬件后退按钮时,我试图退出我的应用程序,我在我的应用程序中使用了以下代码:

    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
        Dashboard_Activity.this.finish();
        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);

在这里,当用户双击硬件后退按钮时,相同的活动会一次又一次地出现,但应用程序不会退出。你能帮我解决这个问题吗?

4

3 回答 3

0

尝试以下操作:

private static long back_pressed;

    @Override
    public void onBackPressed()
    {
        if (back_pressed + 2000 > System.currentTimeMillis()) super.onBackPressed();
        else Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
        back_pressed = System.currentTimeMillis();
    }

资源

于 2015-05-26T09:36:12.360 回答
0

在 Oncreate 之外的代码中的任何位置尝试此方法,为我工作

        @Override
        public void onBackPressed() 
        {
            try
            {

            //pop up Window closed. 
            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);

            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }   
于 2015-05-26T09:40:47.233 回答
0

首先,创建SplashScreenActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    finish();
}

然后在您的活动中(或在 BaseActivity 中)将此变量添加为类成员:

private long milis;

并覆盖onBackPressed():

@Override
public void onBackPressed() {
    if(milis + 2000 > System.currentTimeMillis()){
        Intent intent = new Intent(this, SplashScreenActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }else{
        milis = System.currentTimeMillis();
    }
}
于 2015-05-26T09:42:00.177 回答