Exit android app on back pressed

后端 未结 12 1952
逝去的感伤
逝去的感伤 2021-01-30 10:57

I am building an Android App. How to exit an Android App when back is pressed. Android version is 2.3.3 and above. The Android App goes to previous activity which i don\'t want.

12条回答
  •  终归单人心
    2021-01-30 11:41

    Some Activities you don't actually want to open again when the back button is pressed, such as Splash Screen Activity, Welcome Screen Activity and Confirmation Windows. Actually, you don't need this in the activity stack. You can do this using=> open Manifest.xml file and add an attribute

    android:noHistory="true"

    to these activities.

    
    
    

    OR

    Sometimes you want to close the entire application on a certain back button press. Here the best practice is to open up the home window instead of exiting the application. For that, you need to override the onBackPressed() method. Usually, this method opens up the top activity in the stack.

    @override
    public void onBackPressed(){
    Intent a = new Intent(Intent.ACTION_MAIN);
    a.addCategory(Intent.CATEGORY_HOME);
    a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(a);
    }
    

    OR

    On back button pressed you want to exit that activity and also you don't want to add this to the activity stack. Call finish() inside the onBackPressed() method. It will not close the entire application, it will just go to the previous activity in the stack.

    onBackPressed() - Called when the activity has detected the user's press of the back key.

    public void onBackPressed() {
      finish();
    }
    

提交回复
热议问题