我做了一个Background Taks演示。这个问题的解决方案的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));
}
我没有异常,也没有错误消息。当事件触发时,程序才会终止。设备和仿真器上都相同。
答案 0 :(得分:2)
我检查了你的项目,你需要改进几件事:
Task.Upload
(而不是Tasks.Upload
)。还要记住在 package.appxmanifest 文件中更改声明中的条目。正如我在此更改后尝试的那样,您的应用应该可以正常运行。