我尝试在单一流程模型中使用新的&#;;背景活动' API支持我的应用程序与后台任务。但是,我得到了,没有找到合适的方法来覆盖'在' 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();
}
}
答案 0 :(得分:3)
此处的问题是您尝试覆盖OnBackgroundActivated
课程中的MainPage
方法。 MainPage
类派生自Page Class,但Application.OnBackgroundActivated method是Application 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 tasks和Background activity with the Single Process Model。