重新启动应用程序时,来自Xamarin Messaging中心的多条消息?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (197)

我有一个Xamarin Forms应用程序,我用它将MessagingCenter一些数据从特定平台发送到Xamarin.Forms应用程序。

在我Page订阅消息base.OnAppearing()和取消订阅base.OnDisappearing()方法。这按预期工作。

我遇到的问题是,当应用程序停止时AndroidOS(例如,当我更改设备的语言时),我开始获取消息的副本。我很困惑为什么会这样,但我注意到base.OnDisappearing()在重新启动应用程序时不会调用该方法。

有谁知道什么可能导致我的问题以及如何解决它?

提问于
用户回答回答于

这是一个适合的例子,因为我们有一个BaseContentPage,从中派生所有页面:

protected override void OnAppearing()
{
    base.OnAppearing();
    var pageOnTop = ModalContentPageOnTop();
    if (pageOnTop == null || pageOnTop == this)
    {
        // do some stuff, like setting up subscriptions
        SetupSubscriptions();
    }
    else
    {
        // Xamarin Forms Appearing/Disappearing Bug
        // Found that when you leave the Android app with a modal page on top of a non-modal page (either minimise the app or lock the device), then Xamarin.Forms does not properly call OnAppearing. 
        // Xamarin.Forms will call OnAppearing on the non-modal page and not on the modal page. This would not only cause message subscriptions to not be set up on the modal page, 
        // but would also set up message subscriptions on the non-modal page. Not good.  Hopefully, this work-around should stop being executed when Xamarin fixes the problem, as we won't 
        // fall into this "else" condition above, because OnAppearing will be called on the right page.

        // NOTE: SendDisappearing and SendAppearing have boolean guards on them. If SendAppearing was called last, calling it again will do nothing.
        // SendDisappearing has the same behaviour. Thus we need to call SendDisappearing first, to be guaranteed that SendAppearing will cause the OnAppearing() method to execute.
        ((IPageController)pageOnTop).SendDisappearing();  // try and correct Xamarin.Forms - the page actually on top was not told it was disappearing - tell it now
        ((IPageController)this).SendDisappearing();  // try and correct Xamarin.Forms - if it thinks the view has appeared when it hasn't, it won't call OnAppearing when it is truly appearing.
        ((IPageController)pageOnTop).SendAppearing();  // try and correct Xamarin.Forms by notifying the correct page that it is appearing
    }
}

ModalContentPageOnTop的样子:

private ContentPage ModalContentPageOnTop()
{
    var page = Navigation.ModalStack.LastOrDefault();
    var navigationPage = page as NavigationPage;
    if (navigationPage != null)
        return navigationPage.CurrentPage as ContentPage;
    return page as ContentPage;
}
用户回答回答于
protected override async void OnAppearing() {
    base.OnAppearing();

    MessagingCenter.Unsubscribe<string>(this, "KeyHere");
    MessagingCenter.Subscribe<string>(this, "KeyHere", string => { }));
}

扫码关注云+社区

领取腾讯云代金券