0
我正在尝试开发一个Windows 10 UWP应用程序,该应用程序具有由原始Pushnotification触发器触发的后台任务。作为测试,我还在应用程序上有一个处理程序,以查看原始通知实际上是否正确推送并运行。以下是代码片段:UWP PushNotificationTrigger不会触发后台任务
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;
}
的代码应用程序definitel y收到通知,但从不后台任务。我做错了什么?
更多信息: 看起来像推送通知被击中框,但得到这个错误在事件日志中
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
你能否在没有通知的情况下运行后台任务?也就是说,你可以使用代码/按钮点击手动触发它... – Laith
从我读的内容来看,Visual Studio中无法触发推送通知。实际上我有一个TimeTrigger事件后台任务,我可以在Visual Studio中测试它。有没有办法实际运行推送通知后台任务? – dreamfly
我只是想确保你已经看到你的后台任务代码被一个备用触发器触发。 – Laith