我正在编写一个依赖通知工作的 Windows 桌面应用程序。但是,当我收到通知时,通道上的事件处理程序代码 PushNotificationReceived 似乎并没有真正触发。在将其 uri 发送到我的服务器之前,调用以下代码来获取通道:
internal async Task<PushNotificationChannel> GetChannel()
{
PushNotificationChannel pnc;
try
{
pnc = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
if (_channel == null || !pnc.Uri.Equals(_channel.Uri))
{
_channel = pnc;
_channel.PushNotificationReceived += OnPushNotificationReceived;
Debug.WriteLine(_channel.Uri);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
_channel = null;
}
dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
return _channel;
}
这样,无论何时创建或更新通道(通过不同的通道 uri),它都应该将新通道的 PushNotificationReceived 事件分配给以下内容(这基本上是从 msdn 的示例中提取的):
void OnPushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs e)
{
string typeString = String.Empty;
string notificationContent = String.Empty;
switch (e.NotificationType)
{
//
//other notification types omitted for brevity
//
case PushNotificationType.Toast:
notificationContent = e.ToastNotification.Content.GetXml();
typeString = "Toast";
// Setting the cancel property prevents the notification from being delivered. It's especially important to do this for toasts:
// if your application is already on the screen, there's no need to display a toast from push notifications.
e.Cancel = true;
break;
}
Debug.WriteLine("Received notification, with payload: {0}", notificationContent);
string text = "Received a " + typeString + " notification, containing: " + notificationContent;
var ignored = dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
MainPage.Current.ClearBanner();
});
}
重要的是,“MainPage.Current”是对应用程序主页作为静态变量的引用。清晰的横幅行只是从主页中删除了一个粉红色的横幅(只是试图让一些简单的工作开始)。
但是,代码似乎永远不会触发(没有调试语句,粉红色横幅仍然存在)。我成功地获得了 toast 通知,点击它会将焦点设置到我的应用程序上,所以它绝对不会去错地方。
有什么我做错了或者有什么方法可以自己调试通知吗?