Search code examples
androidandroid-activityactivity-finish

A close button that finishes all activities


I have 5 activities in my android app,on last activity i want a close button that exits the app by finishing every activity one by one?


Solution

  • You can do the next steps:

    In the activity where you want to exit do the this:

    Intent intent = new Intent(this, RootActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//this will clear all the stack
    intent.putExtra("extra_exit", true);
    startActivity(intent);
    finish();
    

    and in RootActivity.class's onCreate and onNewIntent:

    public void onCreate(Bundle savedInstance){
        ...
        if(!checkExtraToExit(intent)){
            //do activity initialization
            ...
        }
        ...
    }
    
    public void onNewIntent(Intent intent){
        if(!checkExtraToExit(intent)){
            super.onNewIntent(intent);
        }
    } 
    
    public boolean checkExtraToExit(Intent intent){
        if( intent.getBooleanExtra("extra_exit", false)){
            finish();
            return true;
        }
        return false;
    }