Search code examples
androidandroid-activityback-stackandroid-navigation

Exit Android application on back button


I have ImageButton with back arrow in header of my application. When user presses it, I call finish() on current Activity. I also have option for user to go home, but I want to somehow clear Activity history, so when user presses back button on home activity, application closes.

I can also put a parameter to the intent, when calling home activity, but what do I call for application to close?


Solution

  • When you go to an activity, save that activityContext some where(say in some array of Contexts).

    When you press the exit button, you can just loop the array and say activity.finish()

    So all the activities in the stack are now finished and the user is out of app.

    Code may be like this:

    public class ActivityStack {
    
        public ArrayList<Context> contextArray=new ArrayList<>(); 
    
        public void setContext(int i,Context context) {
              contextArray.add(context);
        }
    
        public void quitApp() {
               for(context:ContextArray) {
                  context.finish();  
    
                }
        }
    
    }
    

    Edit: From API 16, finishAffinity() method can be used to finish all activities.