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