Search code examples
androidandroid-activityandroid-lifecycle

How to close Activities


I have 4 Activities and each one has different objects which can get from server. The main purpose is when I submit final data in activity 4, Activity 1 must be called again. I have tested several methods, backing from D activity to Main activity is easy but I would like to clear all previous Activities too which makes this question different.

App Activity cycle

At this time I have to close activity B and C. If I just finish activity D and start Activity A in a new intent, the previous Activities are alive and whenever I want to come back from app I can see those activities again. How can I close multiple activities at the same time?

Final purpose


Solution

  • 2 lines on Activity D can do the magic.

    In your onBackPressed() method of Activity D.

    Add theses lines

    @Override
         public void onBackPressed() {    
                startActivity(new Intent(Activity_D.this,Activity_A.class));
                finishAffinity();
            }
    

    FinishAffinity will clear all opened Activities. So only Activity A will remained open