Search code examples
xamarinxamarin.androidapplication-lifecyclexamarin-native

Xamarin Native equivalent of Xamarin.Forms App OnSleep and OnResume


I'm working with a Xamarin Native application, and would like to perform some logic when the application is focused / out of focused in android - similar to Xamarin.Forms Application.OnSleep(), and Application.OnResume() (not to be confused with Activity.OnResume, and Activity.OnPause)

Just wondering what solution others have used to solve this scenario (besides migrating to Xamarin.Forms).


Solution

  • [Application]
    public class MyApp : Application, ILifecycleObserver
    {
        [Export, Lifecycle.Event.OnStop]
        public void OnAppBackgrounded()
        {
        }
    
        [Export, Lifecycle.Event.OnStart]
        public void OnAppForegrounded()
        {
        }
    
        public override void OnCreate()
        {
            // For handling when the app goes into the foreground or background
            ProcessLifecycleOwner.Get().Lifecycle.AddObserver(this);
        }
    

    So far it appears to work as expected. ProcessLifecycleOwner is in the Xamarin.Android.Arch.Lifecycle.Extensions nuget package.