Search code examples
javaandroidandroid-activitylaunchmode

MainActivity jumps to the top of the stack when app is opened


I'm trying to develop an app with multiple activities, and I'm using the singleInstance launch mode so that there will not be multiple instances of the same activity. However, when I press the home button on the test phone (which calls onStop() but not onDestroy(), and I start the app again (by clicking on the icon), it brings me back to MainActivity. Investigating further, I found that the stack of activities (using the adb shell dumpsys activity | grep -i run command) were unaffected, except for MainActivity, which popped to the top of the stack.

I tried searching for this problem online but saw nothing similar. I might be just overlooking something obvious but I don't know. Thanks for any help!

EDIT ---

I will give an example of what occurs and what I expected. I start off the app at MainActivity, and then navigate to another activity (AboutUs) using a button. However, when I press the home button (on the phone) and click the app icon again, instead of going to AboutUs, it goes to MainActivity. AboutUs is still in the stack, but just under MainActivity. So, the stack was undisturbed except that MainActivity rose to the top. enter image description here

Here is an image of the Profiler from Android Studio. As you can see, I clicked a button to go to AboutUs, and then hit the home button on the phone, which made a gap. After I clicked on the app again, it went back to MainActivity. MainActivity is both single instance and the launcher activity.


Solution

  • Remove the special launch mode singleInstance from the <activity> declaration for MainActivity in your manifest. This special launch mode is the cause of your problem. You should generally avoid the special launch modes singleInstance and singleTask because they cause more problems than they solve. These are only needed in very specific cases (like if you want to write your own HOME screen replacement).