当我在打开设备后立即登录我的设备时,我正在尝试运行我的后台任务.现在它只在我已经登录时运行,然后我重新登录.
我可以看到任务在调试时完全注册,但仍然不知道为什么它在启动时不起作用.
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);
}
}
}
最佳答案 请参考这个问题..我相信它与你的相关:
Uwp execute backgroundtask at user login
祝好运!