1

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).

Chris Klepeis
  • 9,783
  • 16
  • 83
  • 149
  • https://developer.android.com/guide/components/activities/activity-lifecycle#alc doesn't MainActivity have onStart(), onResume(), onPause() methods? – Ricardo Dias Morais Mar 02 '20 at 15:00
  • 2
    Just understood what you meant, you want application level OnSleep/OnResume, i sugest you use a LifecycleObserver. take a look at this: https://stackoverflow.com/questions/28691986/application-level-onresume-android – Ricardo Dias Morais Mar 02 '20 at 15:03
  • could it work ? – Leo Zhu Mar 06 '20 at 08:36
  • @LeoZhu-MSFT Thanks for the reply. I posted an answer as well that I found this morning. I have to test it further, but it looks promising. – Chris Klepeis Mar 06 '20 at 16:53

2 Answers2

1

when the application is focused / out of focused in android

Do you mean you want to listener the application is running in foreground or background ?

If yes,you could use IActivityLifecycleCallbacks to listen the status.

Application registration ActivityLifecycleCallbacks, such, when each activity in the app lifecycle occurs, the Application can be listening to. The number of public void onActivityStarted(activity activity) and public void onActivityStopped(activity activity) of an activity can be used to determine whether the app is in the foreground. Because when the app is in the foreground, an activity must have started onActivityStarted but not onActivityStopped, so the statistics of the number of activities opened in the app must be 1. When the app switches to the background, activityStartCount will be 0.

so write a Helper classes :

public class AppFrontBackHelper
{

    public static OnAppStatusListener mOnAppStatusListener;
    private LifecycleCallBack lifecycleCallBack;
    public AppFrontBackHelper()
    {

    }
    /**
     * Register status listener, only used in Application
     * @param application
     * @param listener
     */
    public void register(Application application, OnAppStatusListener listener)
    {
        mOnAppStatusListener = listener;
        lifecycleCallBack = new LifecycleCallBack();
        application.RegisterActivityLifecycleCallbacks(lifecycleCallBack);
    }

    public void unRegister(Application application) => application.UnregisterActivityLifecycleCallbacks(lifecycleCallBack);

    public interface OnAppStatusListener
    {
        void onFront();
        void onBack();
    }
    public class LifecycleCallBack : Java.Lang.Object, Application.IActivityLifecycleCallbacks
    {

        public int activityStartCount { get; private set; }

        public void OnActivityCreated(Activity activity, Bundle savedInstanceState)
        {
        }

        public void OnActivityDestroyed(Activity activity)
        {
        }

        public void OnActivityPaused(Activity activity)
        {
        }

        public void OnActivityResumed(Activity activity)
        {
        }

        public void OnActivitySaveInstanceState(Activity activity, Bundle outState)
        {
        }

        public void OnActivityStarted(Activity activity)
        {
            activityStartCount++;
            //A value from 1 to 0 indicates cutting from the background to the foreground
            if (activityStartCount == 1)
            {

                if (mOnAppStatusListener != null)
                {
                    mOnAppStatusListener.onFront();
                }
            }
        }

        public void OnActivityStopped(Activity activity)
        {
            activityStartCount--;
            //A value from 1 to 0 indicates cutting from the foreground to the background
            if (activityStartCount == 0)
            {
                //from foreground to background
                if (mOnAppStatusListener != null)
                {
                    mOnAppStatusListener.onBack();
                }
            }
        }
    }

}

then custom an Application and regist the listener :

[Application]
public class MyApplication : Application,AppFrontBackHelper.OnAppStatusListener
{
    protected MyApplication(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
    {
    }
    public override void OnCreate()
    {
        base.OnCreate();
        AppFrontBackHelper appFrontBackHelper = new AppFrontBackHelper();
        appFrontBackHelper.register(this, this);
    }
    public void onBack()
    {
        Toast.MakeText(this, "from front to back", ToastLength.Short).Show();
    }



    public void onFront()
    {
        Toast.MakeText(this, "from back to front", ToastLength.Short).Show();
    }


}
Leo Zhu
  • 15,726
  • 1
  • 7
  • 23
1
[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.

Chris Klepeis
  • 9,783
  • 16
  • 83
  • 149