0

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.

When 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 OnCreate are 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 MainActivity active?

Paul Kertscher
  • 9,416
  • 5
  • 32
  • 57
  • I've also updated the linked question: https://stackoverflow.com/questions/38119936/app-is-not-maintaining-the-state-after-installation-xamarin-android – David Wasser Feb 18 '20 at 16:17

2 Answers2

1

in your android manifest set on the activity tag

android:launchMode="singleTop"

It will have consequences on how you handle notifications, and in some cases onActivityResult

Lena Bru
  • 13,521
  • 11
  • 61
  • 126
1

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:

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

David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • 1
    Took sime time to sort everything out (missed the `return` which caused side-effects), but I think I employed the work-around correctly now. Thank you very much :) – Paul Kertscher Feb 19 '20 at 11:02