Close all running activities in an android application?

后端 未结 11 1773
死守一世寂寞
死守一世寂寞 2020-12-11 19:19

I create one application and never use finish() for each activity. If my user clicks on the logout button it goes to the previous page.

How can I close my previous

11条回答
  •  不知归路
    2020-12-11 19:43

    EDIT

    Sam Janz answer is cleaner than this method. Use the intent flags to your advantage

    When the user presses log out:

    Intent intent = new Intent(this,MyHomeActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putBooleanExtra("finishApplication", true);
    startActivity(intent);
    

    Then in MyHomeActivity (Your start activity) in onResume:

    if(getIntent().getBooleanExtra("finishApplication", false){
       finish();
    }
    

    This way you don't have to have checks in all your activity's only the Home activity.


    Dirtier option:

    Create a static boolean variable in a singleton somewhere (probably in a class that extends application);

    public static boolean loggingOut = false;
    

    When the user presses log out set this to true and call finish on that activity.

    YourApplication.loggingOut = true;
    finish();
    

    In each activity in onResume()

    if(loggingOut){
       finish();
    }
    

    Ensure you set this boolean back to false in your main/start up activity:

    if(loggingOut){
       finish();
       YourApplication.loggingOut = false;
    }
    

    If you also want the back button to do it, override onBackPressed(), that would then also do

    @Override
    public void onBackPressed(){
         YourApplication.loggingOut = true;
         super.onBackPressed();
    }
    

提交回复
热议问题