2016-10-03 79 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

谢谢,它的工作原理。从来没有这样想过。我对编程非常陌生,所以很难理解。谢谢! –

相关问题