UWP PushNotificationTrigger 不会触发后台任务
UWP PushNotificationTrigger won't trigger background task
我正在尝试开发一个 Windows 10 UWP 应用程序,它有一个由原始推送通知触发器触发的后台任务。作为测试,我在应用程序上也有一个处理程序,以查看原始通知是否确实正确推送并且有效。以下是代码片段:
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;
}
App确实收到了通知,但后台任务从未收到。我做错了什么?
更多信息:
看起来推送通知已成功,但在事件日志中出现此错误
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
后台任务需要是 IBackgroundTask
的子class
public 密封 class PositionBackgroundTask : IBackgroundTask
我正在尝试开发一个 Windows 10 UWP 应用程序,它有一个由原始推送通知触发器触发的后台任务。作为测试,我在应用程序上也有一个处理程序,以查看原始通知是否确实正确推送并且有效。以下是代码片段:
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;
}
App确实收到了通知,但后台任务从未收到。我做错了什么?
更多信息: 看起来推送通知已成功,但在事件日志中出现此错误
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
后台任务需要是 IBackgroundTask
的子classpublic 密封 class PositionBackgroundTask : IBackgroundTask