我做了一个背景任务演示。这是此问题中解决方案的 95% % 副本: Windows Phone 8.1 Background Task - Can't Debug and won't fire
解决方案的完整示例可以在这里下载:http: //1drv.ms/1qCPLMY
问题是当我的事件触发程序终止时。“我的”解决方案可以在这里下载:http: //1drv.ms/1x3z7Mp
所以这是“我的”代码:
首先是实现 IBackgroundTask 的类
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
namespace Tasks
{
public sealed class Upload : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
Debug.WriteLine("Hello IBackgroundTask");
//return;
var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
var textElements = toastXml.GetElementsByTagName("text");
var networkStateChangeEventDetails = (taskInstance.TriggerDetails as Windows.Networking.Connectivity.NetworkStateChangeEventDetails);
if (networkStateChangeEventDetails == null)
return;
textElements[0].AppendChild(toastXml.CreateTextNode("I'm message from your task!"));
ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml));
}
}
}
这是注册后台任务的代码:
private async void Button_Click(object sender, RoutedEventArgs e)
{
Debug.WriteLine("Registering task");
var taskRegistered = false;
var exampleTaskName = "UploadTask";
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == exampleTaskName)
{
//taskRegistered = true;
task.Value.Unregister(true);
// break;
}
}
await BackgroundExecutionManager.RequestAccessAsync();
if (!taskRegistered)
{
Debug.WriteLine("Registering task inside");
var builder = new BackgroundTaskBuilder();
builder.Name = exampleTaskName;
builder.TaskEntryPoint = "Tasks.Upload";
builder.SetTrigger(new SystemTrigger(SystemTriggerType.NetworkStateChange, false));
BackgroundTaskRegistration task = builder.Register();
//task.Completed += new BackgroundTaskCompletedEventHandler(NetworkStateChangeTaskOnCompleted);
//task.Trigger += new BackgroundTaskCompletedEventHandler(NetworkStateChangeTaskOnCompleted);
await new MessageDialog("Task registered!").ShowAsync();
}
}
private void NetworkStateChangeTaskOnCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
{
var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
var textElements = toastXml.GetElementsByTagName("text");
textElements[0].AppendChild(toastXml.CreateTextNode("NetworkStateChangeTaskOnCompleted() =>"));
textElements[0].AppendChild(toastXml.CreateTextNode("I'm message from your task!"));
ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml));
}
我没有例外,也没有错误消息。当事件触发时,程序就终止了。在设备和模拟器上相同。