当我打开设备后立即登录我的设备时,我正在尝试运行后台任务。现在它只在我已经登录时运行,然后我重新登录。
我可以看到任务在调试时已经完美注册,但仍然不知道为什么它在启动时不起作用。
async void RequestBackgroundAccess()
{
BackgroundAccessStatus backgroundStatus = await BackgroundExecutionManager.RequestAccessAsync();
if (backgroundStatus != BackgroundAccessStatus.Denied && backgroundStatus != BackgroundAccessStatus.Unspecified)
{
RegisterBackgroundThread();
}
else
{
Debug.WriteLine("[Background Access] Denied.");
}
}
void RegisterBackgroundThread()
{
var taskRegistered = false;
var exampleTaskName = "Bot";
foreach (var bgTask in BackgroundTaskRegistration.AllTasks)
{
if (bgTask.Value.Name == exampleTaskName)
{
taskRegistered = true;
Debug.WriteLine("[Background Task] Registered.");
break;
}
}
if (taskRegistered == false)
{
Debug.WriteLine("[Background Task] Registering...");
var builder = new BackgroundTaskBuilder();
builder.Name = exampleTaskName;
builder.TaskEntryPoint = "Tasks.Bot";
builder.SetTrigger(new SystemTrigger(SystemTriggerType.UserPresent, false));
BackgroundTaskRegistration task = builder.Register();
Debug.WriteLine("[Background Task] Registered.");
}
}
Bot.cs
namespace Tasks
{
public sealed class Bot : IBackgroundTask
{
BackgroundTaskDeferral serviceDeferral;
public void Run(IBackgroundTaskInstance taskInstance)
{
this.serviceDeferral = taskInstance.GetDeferral();
ToastNotification("Starting...");
}
void ToastNotification(String message)
{
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
stringElements[0].AppendChild(toastXml.CreateTextNode(message));
ToastNotification toast = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier().Show(toast);
}
}
}
答案 0 :(得分:1)
我取消注册后台任务并重新注册,它解决了我遇到的问题。
答案 1 :(得分:0)
请参考这个问题..我相信它与你的相关:
祝你好运!