当应用程序暂停时,WNS 推送通知从不触发 Activated 事件

WNS push notification never fires Activated event when app is suspended

我开始头晕目眩:我有一个 windows phone 8.1 通用应用程序。在 App.xaml.cs 中,我实现了以下方法:

public sealed partial class App : Application
{
    public static bool isSuspended = false;

    public App()
    {
        this.InitializeComponent();
        this.Suspending += this.OnSuspending;
        this.Resuming += this.OnResuming;
    }

    private void OnSuspending(object sender, SuspendingEventArgs e)
    {
        SuspendingDeferral deferral = e.SuspendingOperation.GetDeferral();
        App.isSuspended = true;

        // TODO: Save application state and stop any background activity
        deferral.Complete();
    }

    private async void OnResuming(object sender, object e)
    {
        App.isSuspended = false;
    }
}

在我的 MainPageVM(它是一个视图模型)中,我实现了以下方法:

private async void onPushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args)
{
    switch (args.NotificationType)
    {
        case PushNotificationType.Toast:
            if (App.isSuspended)
            {
                args.ToastNotification.Activated += this.toastNotification_Activated;
            }
            else
            {
                args.Cancel = true;
                this.manageNotification(args.ToastNotification.Content)
            }
            break;
        case PushNotificationType.Raw:
            break;
    }
}

private void toastNotification_Activated(ToastNotification sender, object args)
{
    ToastActivatedEventArgs tArgs = (ToastActivatedEventArgs)args;
    this.manageNotification(tArgs.Arguments);
}

当应用被杀死或应用在前台时,它运行良好。当应用程序在后台时出现问题:当用户单击通知时,toastNotification_Activated 永远不会被引发。

我错过了什么?

当您的应用程序 已暂停 时,这意味着它不是 运行 (app lifecycle at MSDN). In this case when the notification comes it's not intercepted by the event you have declared, like MSDN says:

Note This procedure applies only to running apps. Notifications that the system sends when the app is not running and the handler is not implemented are delivered normally—tiles are updated, toast is shown, and raw notifications are delivered to background tasks (if implemented).

如果你想在后台处理通知,那么你可能会想到声明一个Background Task for it