使用下面的引用,我試圖做一個UWP應用後臺任務:UWP計時器底色任務不會運行
https://docs.microsoft.com/en-us/windows/uwp/launch-resume/create-and-register-a-background-task
https://docs.microsoft.com/en-us/windows/uwp/launch-resume/run-a-background-task-on-a-timer-
https://www.youtube.com/watch?v=H18HrUin46I
一切正常在強制後臺任務以調試模式運行時顯示在YouTube視頻中,但應用程序上的調試/發佈版本無法自行啓動15分鐘的後臺任務。下面的代碼:
MainPage.xaml.cs中
using TimerBG;
bool taskRegistered = false;
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == nameof(BG))
{
task.Value.Unregister(true);
}
}
if(!taskRegistered)
{
Setup();
}
public async static void Setup()
{
BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync();
var builder = new BackgroundTaskBuilder();
builder.Name = nameof(BG);
builder.TaskEntryPoint = typeof(BG).ToString();
TimeTrigger trig = new TimeTrigger(15, false);
builder.SetTrigger(trig);
SystemCondition userCondition = new SystemCondition(SystemConditionType.UserNotPresent);
builder.AddCondition(userCondition);
builder.CancelOnConditionLoss = false;
builder.Register();
}
BG.cs
using Windows.ApplicationModel.Background;
using Windows.Storage;
namespace TimerBG
{
public sealed class BG : IBackgroundTask
{
BackgroundTaskDeferral _deferral;
public async void Run(IBackgroundTaskInstance taskInstance)
{
_deferral = taskInstance.GetDeferral();
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile sampleFile = await storageFolder.GetFileAsync("sample.txt");
await FileIO.WriteTextAsync(sampleFile, DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString());
_deferral.Complete();
}
}
}
包清單後臺任務的屬性設置爲 「定時器」 與入口點「TimerBG。 BG」。
任何幫助將不勝感激。
您的意思是有「用戶**不**」存在的條件嗎? –
我剛剛看到基於此文檔(https://docs.microsoft.com/en-us/uwp/api/Windows.ApplicationModel.Background.SystemConditionType),並且現在在發佈代碼上測試UserPresent。 – detailCode
好的,切換到條件SystemConditionType.UserPresent。在VS調試中運行應用程序,後臺任務不會觸發並觸發我的中斷點。我創建了按鈕來檢查任務是否已註冊,並且是。我錯過了什麼? – detailCode