It occurred to me that under some circumstances our app seems to be restarted from scratch after being backgrounded. I managed to track to issue down to
MainActivity.OnCreate being called multiply under the following circumstances
- App is installed from APK and then ran from the installer, after backgrounding the app and starting it from the home screen it’s reset to scratch
- This behavior persists until the app is killed and then restarted from the home screen
- App is run from Google Play app, after backgrounding the app and starting it from the home screen it’s reset to scratch
- If the app is backgrounded and then started from Play Store it’s started correctly
- App is run from home screen, after backgrounding the app and starting it from Google Play it’s reset to scratch
When the app is foregrounded from the same launcher it has been started initially,
OnCreate is not called again. There is at least one question reporting a similar behavior, unfortunately there is no answer providing a solution for the behavior.
MainActivity.OnCreate is called, the instance of
MainActivity seems to be a different instance than the initial one, since private members that are set in
null when I’m trying to log them, anyway, the application context does not seem to be recreated from scratch, because
AppCenter seems to be initialized right away on the second run, Xamarin.Forms starts up way quicker and static variables keep their values.
Is there any way to prevent this behavior and just keep a single instance of
Congratulations! You’ve been bit by a long-standing, nasty Android bug which has been around since the dawn of time and is still broken, even though countless issues have been opened about it and the behaviour is reproducible and well-documented.
See the following:
- Re-launch of Activity on Home button, but…only the first time
- App restarts rather than resumes
In September 2019, one of these issues was marked “fixed” with this comment:
Thanks for reporting this issue. The issue has been fixed and it will
become available in a future Android release.
So hopefully we will no longer be seeing this in Android Z 😉
There is a workaround documented in my answer to
Re-launch of Activity on Home button, but…only the first time
in your android manifest set on the activity tag
It will have consequences on how you handle notifications, and in some cases onActivityResult