android - 来自 xamarin.forms 按钮单击的 Android 推送通知挂起
问题描述
我一直在慢慢尝试进入推送通知并开始了解它们/在我正在构建的应用程序中实现它们。
我已经完成了有关设置 Azure 通知中心和 Firebase、在那里建立连接、发送测试推送等的教程,并且我已经完成了所有这些工作,我能够接收从中心发送的通知到我的应用程序(在我的手机上)。我还能够成功创建一个控制台应用程序,它将通知推送到(我假设)集线器,然后将通知发送到我的应用程序。
我正在尝试做的事情以及这个问题的原因是从控制台应用程序中获取相同的代码并在 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
。
推荐阅读
- swift - 将分数保存到带有附加值的 firebase
- javascript - Google 脚本的格式参数
- angular - 我收到这样的错误:Ionic4 中的“ERROR TypeError: res.Data.map is not a function”
- amazon-ecs - ECS+NLB 不支持动态端口,因此每个 EC2 实例只有 1 个任务?
- java - Cucumber Java (Maven) - FileInputStream - java.lang.NullPointerException
- html - 在 selectionChange 内/之后更改选定的 mat-chips
- google-maps - 从 Google 表格中的地址生成 Google 地图
- c# - 有没有办法根据初始枚举值使用不同的构造函数?
- json - 是否可以将“Omitempty”json 标记作为默认行为?
- meteor - Meteor Atmosphere/Core Package Dependency Resolution Override (jquery, iron-router, blaze)