2016-10-03 61 views
0

我正在嘗試使用新的'單進程模型的後臺活動'API來支持我的應用程序與後臺任務。但是,我得到'OnBackgroundActivated'方法'找不到合適的方法來覆蓋'。我的代碼有什麼問題?UWP OnBackgroundActivated,找不到合適的方法覆蓋

public MainPage() 
    { 
     this.InitializeComponent(); 
     Application.Current.EnteredBackground += Current_EnteredBackground; 
    } 

    private async void Current_EnteredBackground(object sender, Windows.ApplicationModel.EnteredBackgroundEventArgs e) 
    { 
     await RegisterBackgroundTask(); 
    } 

    protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args) 
    { 
     // show a toast 
    } 

    private void Page_Loaded(object sender, RoutedEventArgs e) 
    { 

    } 

    private async Task RegisterBackgroundTask() 
    { 
     BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync(); 

     if (backgroundAccessStatus == BackgroundAccessStatus.AllowedSubjectToSystemPolicy || 
      backgroundAccessStatus == BackgroundAccessStatus.AlwaysAllowed) 
     { 
      foreach (var bgTask in BackgroundTaskRegistration.AllTasks) 
      { 
       if (bgTask.Value.Name == "MyTask") 
       { 
        bgTask.Value.Unregister(true); 
       } 
      } 

      var builder = new BackgroundTaskBuilder(); 
      builder.Name = "MyTask"; 
      builder.SetTrigger(new TimeTrigger(15, false)); 

      // use builder.TaskEntryPoint if you want to not use the default OnBackgroundActivated 
      // we’ll register it and now will start work based on the trigger, here we used a Time Trigger 
      BackgroundTaskRegistration task = builder.Register(); 
     } 
    } 

回答

2

這裏的問題是,你正在試圖重寫OnBackgroundActivated方法MainPage類。 MainPage類是從Page Class派生的,但Application.OnBackgroundActivated methodApplication class的一種方法,它在Page類中不存在,所以你得到了no suitable method found to override錯誤。

要解決這個問題,我們需要把OnBackgroundActivated方法App類,如:

sealed partial class App : Application 
{ 
    /// <summary> 
    /// Override the Application.OnBackgroundActivated method to handle background activation in 
    /// the main process. This entry point is used when BackgroundTaskBuilder.TaskEntryPoint is 
    /// not set during background task registration. 
    /// </summary> 
    /// <param name="args"></param> 
    protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args) 
    { 
     //TODO 
    } 
} 

有關單個進程後臺任務的詳細信息,請參閱Support your app with background tasksBackground activity with the Single Process Model

+0

謝謝,它的工作原理。從來沒有這樣想過。我對編程非常陌生,所以很難理解。謝謝! –

相關問題