Android 来自 xamarin.forms 按钮的推送通知点击挂起

Android push notification from xamarin.forms button click hangs

我一直在慢慢尝试进入推送通知并开始了解它们/在我正在构建的应用程序中实现它们。

我已经完成了有关设置 Azure 通知中心和 Firebase、在那里建立连接、发送测试推送等的教程,并且我已经完成了所有这些工作,我可以接收从集线器发送到我的应用程序的通知(在我的 phone 上)。我还能够成功创建一个控制台应用程序,将通知推送到(我假设)集线器,然后集线器将通知发送到我的应用程序。

我试图做的,也是这个问题的原因,是从控制台应用程序中获取相同的代码,并在 Xamarin.Forms 的按钮单击方法中实现它,这样我就可以测试发送通过单击按钮推送通知并接收所述通知。

这是我的 xaml(非常基本)

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:d="http://xamarin.com/schemas/2014/forms/design"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         mc:Ignorable="d"
         x:Class="NotificationExample.MainPage">

<StackLayout>
    <!-- Place new controls here -->
    <Label x:Name="Received"
        Text="Welcome to Xamarin.Forms!" 
       HorizontalOptions="Center"
       VerticalOptions="CenterAndExpand" />

    <Button Text="Send Notification"
            Clicked="Button_Clicked"/>
</StackLayout>
</ContentPage>

这是我的 MainPage

背后的代码
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();

        MessagingCenter.Subscribe<string>(this, "Update", (sender) =>
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                Received.Text = sender;
            });
        });
    }

    private void Button_Clicked(object sender, EventArgs e)
    {
        SendTemplateNotificationsAsync().GetAwaiter().GetResult();
    }

    private static async Task SendTemplateNotificationsAsync()
    {
        NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(DispatcherConstants.FullAccessConnectionString, DispatcherConstants.NotificationHubName);
        Dictionary<string, string> templateParameters = new Dictionary<string, string>();

        // Send a template notification to each tag. This will go to any devices that
        // have subscribed to this tag with a template that includes "messageParam"
        // as a parameter
        foreach (var tag in DispatcherConstants.SubscriptionTags)
        {
            templateParameters["messageParam"] = $"Test notification {Guid.NewGuid()}";
            try
            {
                await hub.SendTemplateNotificationAsync(templateParameters, tag);
            }
            catch (Exception ex)
            {
            }
        }
    }
}

当我在按钮点击方法中调用 SendTemplateNotificationAsync 时代码挂起。当在控制台应用程序内部调用并发送通知时,同样的代码可以完美运行。

将它包含在 Xamarin.Forms 项目中与控制台应用程序有什么不同吗?

唯一显着的区别是您现在 运行正在 UI 线程上。并且 运行 在 UI 线程上进行长时间操作可能会冻结并最终导致应用程序崩溃,这听起来像是您正在发生的事情。如果是这样,运行里面的代码Task.Run.