How to exit when back button is pressed?

前端 未结 12 1298
名媛妹妹
名媛妹妹 2020-11-27 11:47

When a user presses the back button on an intent, the application should quit. How can I ensure the application quits when the back button is pressed?

12条回答
  •  情书的邮戳
    2020-11-27 12:10

    A better user experience:

    /**
     * Back button listener.
     * Will close the application if the back button pressed twice.
     */
    @Override
    public void onBackPressed()
    {
        if(backButtonCount >= 1)
        {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
        else
        {
            Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
            backButtonCount++;
        }
    }
    

提交回复
热议问题