For an unknown reason, I can't get my application leaving properly so that when I push the home button and the app icon again, I resume where I was in the app. I would like to force the application to restart on the first Activity.
I suppose this has something to do with onDestroy() or maybe onPause() but I don't know what to do.
The solution marked as 'answer' works but has one disadvantage that was critical for me. With FLAG_ACTIVITY_CLEAR_TOP your target activity will get onCreate called before your old activity stack receives onDestroy. While I have been clearing some necessary stuff in onDestroy I had to workaroud.
This is the solution that worked for me:
The idea is to fire a PendingIntent via AlarmManager that will be invoked a bit later, giving old activity stack some time to clear up.
After hard thinking and testing I finally got the right way of calling my activity to recreate when the app is left with the home button :
in the manifest
That does the trick...(better than when it is put in onResume which is called each time you launch the app, even the first time, causing a double display)
Marc's answer works great, except in my case where my main activity has a launchMode of singleTop. Once I run this intent and then navigate to new Activities and press the home button on the device, then launch my app again from the app icon, I end up creating a new instance of the main Activity, with my previous activity on the back stack.
According to this question it's because the intents don't match. Looking at
adb dumpsys activity
, I see that from my standard android launcher, the package is null, whereas when I do as Marc suggests, the intent package is the name of my package. This difference causes them to not match and to start a new instance when the app icon is tapped again and the main activity isn't on top.However, on other launchers, like on Kindle, the package is set on the launcher intent, so I needed a generic way to handle launchers. I added static methods like such:
with a go home mechanism like this:
then in the main activity defined in my manifest, I added this line:
this works for me on kindle and my phone, and lets me properly reset the app w/o adding another instance of the main activity.
The following code is work for me, it can restart full app perfectly!
Here is an example to restart your app in a generic way by using the PackageManager:
FLAG_ACTIVITY_CLEAR_TOP
didn't work for me because I had to support 2.3.3. My first solution was:This almost works, but not quite.
Since I have a base Activity, I added a kill broadcast that closes all my running activities.
All of my activities extend from this class, so
restarts the app. Tested on genymotion v10, v16, v21 and Nexus 5 with v22.
Edit: this does not remove an activity if it is destroyed at the time of sending the intent. I'm still looking for a solution.