Xamarin 应用程序生命周期与 MessagingCenter

问题描述

在此 Xamarin 活动中,在 OnCreate 期间完成 MessagingCenter 订阅,在 OnDestroy 期间取消订阅。当应用程序加载它订阅并按下后退按钮时 OnDestroy 在 OnBackpressed 之后调用。所以循环似乎是正确的。但是,每次按下返回键并再次启动应用程序时,注册函数retrieveSorterScan 都会被额外调用一次。重新启动 10 次后,即使调用了取消订阅/订阅,它也会被调用 10 次。我认为归结为以下功能组合。这里可能有什么问题?

edit删除 OnBackpressed 后,它具有相同的行为,所以这不是问题。

[Activity(Label = "RopsSorterapp",Icon = "@drawable/icon",Theme = "@style/MainTheme",LaunchMode = LaunchMode.SingleTask,MainLauncher = true,ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation,Screenorientation = Screenorientation.Landscape)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity {

    protected override void OnCreate(Bundle bundle)
    {            
        base.OnCreate(bundle);
        Forms.Init(this,bundle);            
        Instance = this;

        app = new App();
        LoadApplication(app);

        MessagingCenter.Instance.Subscribe<Forms.Application,SorterScan>(Forms.Application.Current,INFO,app.MainPage.retrieveSorterScan);
    }

    protected override void OnDestroy()
    {
        base.OnDestroy();

        MessagingCenter.Instance.Unsubscribe<Forms.Application,string>(Forms.Application.Current,INFO);
    }

解决方法

在您的情况下,您在 SubscribeUnsubscribe 中传递了两种不同类型的参数。所以它们是两种不同的信息。您在 OnCreate 中订阅的消息永远不会被取消订阅。

所以你只需像下面这样修改它

MessagingCenter.Instance.Unsubscribe<Forms.Application,SorterScan>(Forms.Application.Current,INFO);