Search code examples
androidandroid-activitydestroy

Android: Multiple Activities and OnDestroy Question


I have a few dozen activities: 1-Main, 1-Animation, 10-Other's and it's sub-sets of more activities (couple of dozen).

From the Main, you can go to any of the Others via buttons.

The Others call sub-set activities and they call the Animation activity.

Each of the activities, including sub-sets and Animation, has a button to return to the Main activity.

All buttons take user to correct activity.

The issue: From the Main activity, I want to quit via using the device's Back key. But, what happens is that it steps backward through all the previous activities.

The "return to main" buttons (in each activity) has finish and onDestroy in it. So, I'm not sure why those screen/activities aren't destroyed...?

Any comments/suggestions/clarifications is appreciated - thanks

[adding code snippet]

Note: I moved/added/deleted the finish, onDestroy, onStop... tried many ways so what shows in the snippet is only one way I tried...

    //  ---------------------------------------------------------
mainMenu.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // do something
        Intent Maincode = new Intent();
          Maincode.setClassName(
                              "com.bt.test",
                              "com.bt.test.Maincode");
        //  startActivity(Maincode); // go to maincode  
          finish();
          onStop();
        onDestroy();
        startActivity(Maincode); // go to maincode  
    }
}); // end -----------------------------------------------

Solution

  • Could you post your onClick handler for the return to main button?

    You should be doing something like this:

    Intent i = new Intent(this, MainActivity.class);
    startActivity(i);
    finish();
    

    Edit: You could also try setting this flag:

    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    

    This should clear the activity stack between the calling and receiving activity if the receiving activity is already in the stack somewhere.