App.xaml.cs ctor is called when OnResume() should be called

Viewed 920

If I navigate in my App and go back to the Android LaunchScreen with the HomeButton the OnSleep() Hook is called, which is fine. If I navigate back into the App using the Android TaskManager OnResume() is called. If I navigate in my App with the Hardware BackButton then also OnSleep() is called which is fine, but if I navigate back into my app then the OnCreate Method in the MainActivity is called which recreated the App.

        global::Xamarin.Forms.Forms.Init (this, bundle);
        DisplayCrashReport();
        LoadApplication (new Gtue.Mobile.App ());

That should not happen. In the ctor of App.xaml I initialize stuff which only should be initialized once. I tried every LaunchMode for the MainAcitivity, nothing helped.

Is there a way to find out if the App was already initialized?

2 Answers

I came across this issue when observing my App.xaml.cs constructor was being called when I was pressing the home button on my Android device and then clicking my app.

The well detailed answer above details the correct "anticipated behaviour", but this was not the case for me.

I was getting this kind of flow when using the home button or back button -

**On Debug Start**
MainActivity:OnCreate
XF:AppCtor
XF:OnStart
MainActivity:OnResume

**Press Home Button**
MainActivity:OnPause
XF:OnSleep

**Launch App via Click on App Icon**
MainActivity:OnCreate
XF:AppCtor

Searching eventually led me to -

App restarts rather than resumes

Which in turn resulted in the following Xamarin code at the top of MainActivity OnCreate -

        if (!IsTaskRoot)
        {
            string action = Intent.Action;
            if (Intent.HasCategory(Android.Content.Intent.CategoryLauncher) &&
                !string.IsNullOrEmpty(Intent.Action) &&
                action == Android.Content.Intent.ActionMain)
            {
                Finish();
                return;
            }
        }

Which seems to solve the initial reload at least.

I also combined this with -

 LaunchMode = LaunchMode.SingleTask

To stop some double activity shenanigans when clicking on a notification in notification screen.

Related