2017-03-16 16 views
0

使用下面的引用,我試圖做一個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」。

任何幫助將不勝感激。

+2

您的意思是有「用戶**不**」存在的條件嗎? –

+0

我剛剛看到基於此文檔(https://docs.microsoft.com/en-us/uwp/api/Windows.ApplicationModel.Background.SystemConditionType),並且現在在發佈代碼上測試UserPresent。 – detailCode

+0

好的,切換到條件SystemConditionType.UserPresent。在VS調試中運行應用程序,後臺任務不會觸發並觸發我的中斷點。我創建了按鈕來檢查任務是否已註冊,並且是。我錯過了什麼? – detailCode

回答

1

找到了解決辦法看完文章後:如果使用後臺任務的應用程序是使用Visual Studio部署

https://docs.microsoft.com/en-us/windows/uwp/launch-resume/debug-a-background-task

後臺任務和Visual Studio包部署

,並且版本(主要和/或次要)然後更新,隨後用Visual Studio重新部署應用程序可能導致應用程序的後臺任務停滯。

  • 如果已經部署使用Visual Studio和它的後臺任務的應用程序現在都停止,重啓或註銷/登錄獲取應用程序的後臺任務再次合作:這可以如下補救。