UWP PushNotificationTrigger不会触发后台任务

时间:2017-04-07 06:37:12

标签: uwp wns

我正在尝试开发一个Windows 10 UWP应用程序,其后台任务由Raw Pushnotification触发器触发。作为测试,我还在应用程序上有一个处理程序,以查看Raw Notification是否实际上正在推送并且它是否有效。以下是代码段:

    PushNotificationChannel _channel = null;

    private async void AppInit()
    {
        _channel = await Common.WNSHelper.GetChannelAsync();
        if (_channel != null)
        {
            _channel.PushNotificationReceived += _channel_PushNotificationReceived;
        }
        await InstallPositionBackgroundTask();
      }

    private  async void _channel_PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args)
    {
        if (args.NotificationType == PushNotificationType.Raw)
        {
            Common.GeneralHelper.SendToast("At App PositionBackgroundTask");
        }
    }

    private async Task InstallPositionBackgroundTask()
    {
        var taskName = "PositionBackgroundTask";

        foreach (var tsk in BackgroundTaskRegistration.AllTasks)
        {
            if (tsk.Value.Name == taskName)
            {
                tsk.Value.Unregister(true);
            }
        }

        var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
        if (cost == BackgroundWorkCostValue.High)
        {
            return;
        }

        var allowed = await BackgroundExecutionManager.RequestAccessAsync();
        if (allowed == BackgroundAccessStatus.AllowedSubjectToSystemPolicy
            || allowed == BackgroundAccessStatus.AlwaysAllowed)
        {
            var builder = new BackgroundTaskBuilder();

            builder.Name = nameof(PositionBackgroundTask.PositionBackgroundTask);
            builder.CancelOnConditionLoss = false;
            builder.TaskEntryPoint = typeof(PositionBackgroundTask.PositionBackgroundTask).FullName;
            builder.SetTrigger(new PushNotificationTrigger());
            BackgroundTaskRegistration task = builder.Register();
            task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);

            Common.GeneralHelper.SendToast("Position Task Installed. " + System.DateTime.Now.ToString());
        }
    }
    private async void button_Click(object sender, RoutedEventArgs e)
    {
        // send it
        var response = await Common.WNSHelper.PushRawAsync<Common.RawRequest>(_channel.Uri, new RawRequest() { RequestType = RawRequestType.RequestPosition, FromDeviceId = _allDevices[0].D_Id }, null);
    }

这是后台任务

namespace PositionBackgroundTask

{
    public sealed class PositionBackgroundTask
    {

        BackgroundTaskDeferral _deferral;
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            Common.GeneralHelper.SendToast("At PositionBackgroundTask");

            var cancel = new System.Threading.CancellationTokenSource();
            taskInstance.Canceled += (s, e) =>
            {
                cancel.Cancel();
                cancel.Dispose();
            };

            _deferral = taskInstance.GetDeferral();
            try
            {
                RawNotification notification = (RawNotification)taskInstance.TriggerDetails;
                //:
                //:
                //:
            }
            finally
            {
                _deferral.Complete();
            }
        }
    }
}

这是清单

<Extension Category="windows.backgroundTasks" EntryPoint="PositionBackgroundTask.PositionBackgroundTask">
  <BackgroundTasks>
    <Task Type="pushNotification" />
  </BackgroundTasks>
</Extension>

以下是发送原始通知的代码

 public static async Task<HttpResponseMessage> PushRawAsync<T>(string channelUri, RawRequest request, T rawData)
{
    // Get App authorization
    string appDataSecret = MYAPPSECRET;
    Uri requestUri = new Uri(@"https://login.live.com/accesstoken.srf"); 

    var client = new System.Net.Http.HttpClient();
    System.Net.Http.HttpResponseMessage response = await client.PostAsync(requestUri, new StringContent(appDataSecret, System.Text.Encoding.UTF8, "application/x-www-form-urlencoded"));
    string responJsonText = await response.Content.ReadAsStringAsync();

    WMNToken token = JsonConvert.DeserializeObject<WMNToken>(responJsonText);

    string requestStr = JsonConvert.SerializeObject(request) + ";" + JsonConvert.SerializeObject(rawData);
    var content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(requestStr)));

    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(token.Token_type, token.Access_token);
    client.DefaultRequestHeaders.Add("X-WNS-Type", "wns/raw");

    response = await client.PostAsync(channelUri, content);
    return response;
}

该应用程序肯定收到通知但后台任务从未。我做错了什么?

更多信息: 看起来推送通知正在打开框但在事件日志中出现此错误

Activation of the app 45737MyName.TestPushNotificationpartofemail_4rhf8erfmecqa!App for the Windows.BackgroundTasks contract failed with error: No such interface supported.

事实证明我没有将IBackgroundTask子类化 应该是这样的

 public sealed class PositionBackgroundTask : IBackgroundTask

1 个答案:

答案 0 :(得分:1)

后台任务需要是IBackgroundTask的子类

公共密封类PositionBackgroundTask: IBackgroundTask