Xamarin.Android 架构组件:未获得生命周期事件的回调

Xamarin.Android Architecture Components: Not getting callbacks for lifecycle events

我正在尝试使用体系结构组件包来检测应用程序何时进入后台或前台状态。问题是没有调用回调。在下面的示例代码中,未调用方法 onApplicationForegroundedonApplicationBackgrounded

namespace POC.Droid
{
    [Application]
    public class MyApp : Application, ILifecycleObserver
    {
        static readonly string TAG = "MyApp";

        public MyApp(IntPtr handle, Android.Runtime.JniHandleOwnership ownerShip) : base(handle, ownerShip)
        {
        }

        public override void OnCreate()
        {
            base.OnCreate();
            ProcessLifecycleOwner.Get().Lifecycle.AddObserver(this);
        }

        [Lifecycle.Event.OnStop]
        public void onAppBackgrounded()
        {
            Log.Debug(TAG, "App entered background state.");
        }

        [Lifecycle.Event.OnStart]
        public void onAppForegrounded()
        {
            Log.Debug(TAG, "App entered foreground state.");
        }
    }
}

我的 Xamarin 版本是 8.2.0.16(Visual Studio 社区),Xamarin.Android.Arch.Lifecycle.Extensions 版本是 1.0.0。我正在使用 Nougat 设备 (7.0) 进行测试。

如果你在活动中需要它这里的活动:

protected override void OnStart(){
            base.OnStart();
            Log.Debug(logTag, "MainActivity.OnStart() called, the activitiy is active");
        }

        protected override void OnPause()
        {
            base.OnPause();
            Log.Debug(logTag, "MainActivity.OnPause() called, the activity in background");
        }

        protected override void OnStop()
        {
            base.OnStop();
            Log.Debug(logTag, "MainActivity.OnStop() called, the activity is in background because of other activiy or app");
        }

        protected override void OnResume()
        {
            base.OnResume();
            Log.Debug(logTag, "MainActivity.OnResume() called, the activity stated");
        }

        protected override void OnRestart()
        {
            base.OnRestart();
            Log.Debug(logTag, "MainActivity.OnRestart() called,  the activity is startet");
        }

        protected override void OnDestroy()
        {
            base.OnDestroy();
            Log.Debug(logTag, "MainActivity.OnDestroy() called, activity is destroyed");
        }

对于 Xamarin Forms,您将在 app.xaml.cs 中找到应用所需的事件。

protected override void OnStart ( ) {
            // Handle when your app starts
        }

        protected override void OnSleep ( ) {
            // Handle when your app sleeps
        }

        protected override void OnResume ( ) {
            // Handle when your app resumes
        }

我过去使用过那个包,但是我更喜欢 James Montemagno 的实现,它可以作为一个名为 "Plugin.CurrentActivity" 的 nuget 包找到。它创建一个应用程序 class 并为您实现 ILifecycle 事件。

来自描述:

Provides a simple solution for getting access to the current Activity of the application when developing a Plugin for Xamarin. This will lay down a base "application" class for developers in their Android application with boilerplate code to get them started. Can be used with Android API 14+


* 我假设您没有使用 Xamarin.Forms。这非常适合原生 Xamarin Android 项目。


Link to the Github page

TL;DR 请用 [Export]

注释您的生命周期回调

这里有更详细的描述:

一般情况下,要调用生命周期观察者的方法,请确保相关包存在。这是我的一部分 packages.config:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Xamarin.Android.Arch.Core.Common" version="26.1.0" targetFramework="monoandroid81" />
  <package id="Xamarin.Android.Arch.Core.Runtime" version="1.0.0.1" targetFramework="monoandroid81" />
  <package id="Xamarin.Android.Arch.Lifecycle.Common" version="26.1.0" targetFramework="monoandroid81" />
  <package id="Xamarin.Android.Arch.Lifecycle.Extensions" version="1.0.0.1" targetFramework="monoandroid81" />
  <package id="Xamarin.Android.Arch.Lifecycle.Runtime" version="1.0.3.1" targetFramework="monoandroid81" />

这是 Visual Studio 中的样子:

为了能够设置生命周期观察者,我们需要一个生命周期所有者。在应用程序级别,这可以是 ProcessLifecycleOwner,就像原始海报显示的那样。

这里是一个稍微修改过的版本:

using System;
using Android.App;
using Android.Arch.Lifecycle;
using Android.Util;
using Java.Interop;

namespace Stopwatch_AAC
{
    [Application]
    public class MyApp : Application, ILifecycleObserver
    {
        const string TAG = "MyApp";

        public MyApp(IntPtr handle, Android.Runtime.JniHandleOwnership ownerShip) : base(handle, ownerShip)
        {
        }

        public override void OnCreate()
        {
            base.OnCreate();
            ProcessLifecycleOwner.Get().Lifecycle.AddObserver(this);
        }

        [Lifecycle.Event.OnStop]
        [Export]
        public void Stopped()
        {
            Log.Debug(TAG, "App entered background state.");
        }

        [Lifecycle.Event.OnStart]
        [Export]
        public void Started()
        {
            Log.Debug(TAG, "App entered foreground state.");
        }
    }
}

如您所见,您使用例如 [Lifecycle.Event.OnStop] 注释您的生命周期方法。另外请注意,您需要使用 [Export]。请确保在您的项目中引用了 Mono.Android.Export,如下面的屏幕截图所示。

如果你想要 activity 的生命周期观察者,我建议扩展 AppCompatActivity,因为它是生命周期所有者:

using Android.App;
using Android.Arch.Lifecycle;
using Android.OS;
using Android.Support.V7.App;
using Android.Util;
using Java.Interop;

namespace Stopwatch_AAC
{

    [Activity(Label = "Minimal", Exported = true, MainLauncher = true)]
    public class Minimal : AppCompatActivity, ILifecycleObserver
    {
        const string TAG = "Stopwatch_AAC";

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Lifecycle.AddObserver(this);
            Log.Debug(TAG, Lifecycle.CurrentState.ToString());
        }

        [Lifecycle.Event.OnAny]
        [Export]
        public void Hello()
        {
            Log.Debug(TAG, Lifecycle.CurrentState.ToString());
        }
    }
}