Search code examples
javaandroidandroid-activityandroid-background

Android: how to quit an activity without closing it when click on back button?


I have a subActivity that can be open from my mainActivity.

For some reasons, when the user clicks on the back button go back to my mainActivity, I want my subActivity to remain open in background in order to be able to come back for later.

Questions:

  • how to avoid to close the subActivity when the user clicks back ?
  • how to come back to the mainActivity without restarting it ?
  • how to come back later to my opened activity without re-creating it completely ? (just want to bring it to front)

Thanks !


Solution

  • On you subActivity onBackPressed() add this

    @Override
    public void onBackPressed() {
         Intent i = new Intent(SubActivity.this, MainActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    
        startActivity(i);
    }
    

    on mainActivity :

      private void openSubActivity() {        
    
            Intent intent = new Intent(MainActivity.this,SubActivity.class);
           intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(intent);
    
        }