Search code examples
uwpwns

UWP PushNotificationTrigger won't trigger background task


I am trying to develop a Windows 10 UWP app that has a background task to be triggered by a Raw Pushnotification trigger. As a test, I also have a handler on the app to see if the Raw Notification is actually pushing properly and it worked. Here are the code snippets:

    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);
    }

Here's the background task

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();
            }
        }
    }
}

Here's the manifest

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

Here's the code to send the raw notification

 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;
}

The App definitely received the notification but the background task never. What did I do wrong?

More Info: Looks like the push notification is hitting the box but got this error in the event log

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

And it turns out I didn't subclass IBackgroundTask Should be like this

 public sealed class PositionBackgroundTask : IBackgroundTask

Solution

  • Background tasks need to be a subclass of IBackgroundTask

    public sealed class PositionBackgroundTask : IBackgroundTask