How to exit when back button is pressed?

前端 未结 12 1273
名媛妹妹
名媛妹妹 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:12

    First of all, Android does not recommend you to do that within the back button, but rather using the lifecycle methods provided. The back button should not destroy the Activity.

    Activities are being added to the stack, accessible from the Overview (square button since they introduced the Material design in 5.0) when the back button is pressed on the last remaining Activity from the UI stack. If the user wants to close down your app, they should swipe it off (close it) from the Overview menu.

    Your app is responsible to stop any background tasks and jobs you don't want to run, on onPause(), onStop() and onDestroy() lifecycle methods. Please read more about the lifecycles and their proper implementation here: http://developer.android.com/training/basics/activity-lifecycle/stopping.html

    But to answer your question, you can do hacks to implement the exact behaviour you want, but as I said, it is not recommended:

    @Override
     public void onBackPressed() {
    
    // make sure you have this outcommented
    // super.onBackPressed();
     Intent intent = new Intent(Intent.ACTION_MAIN);
     intent.addCategory(Intent.CATEGORY_HOME);
     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     startActivity(intent);
    }
    

提交回复
热议问题