我想爲我的UWP應用程序使用後臺任務。UWP中的後臺任務
下面的代碼是在Windows Mobile的我的背部按鈕單擊事件:
private async void MainPage_BackRequested(object sender, BackRequestedEventArgs e)
{
var access= await BackgroundExecutionManager.RequestAccessAsync();
var task = new BackgroundTaskBuilder
{
Name="My task",TaskEntryPoint=typeof(backGroundTask.Class1).ToString()
};
trigger = new ApplicationTrigger();
task.SetTrigger(trigger);
task.Register();
//var result = await trigger.RequestAsync();
if (Frame.CanGoBack)
{
Frame.GoBack();
e.Handled = true;
}
}
public void Run(IBackgroundTaskInstance taskInstance)
{
_deferral = taskInstance.GetDeferral();
clearData();
count1 = 0;
getDownloadedSongs();
dispatcherTimer1.Tick += DispatcherTimer1_Tick;
dispatcherTimer1.Interval = new TimeSpan(0, 0, 3);
dispatcherTimer1.Start();
_deferral.Complete();
}
DispatcherTimer dispatcherTimer1 = new DispatcherTimer();
private async void DispatcherTimer1_Tick(object sender, object e)
{
try
{
clearData();
}
catch (Exception ex)
{
}
}
但這種代碼是不工作,當我點擊後退按鈕。根據期望後臺任務代碼應該工作,但它不工作。我究竟做錯了什麼?
發生這種情況是因爲在註冊後臺任務之前應用程序正在關閉......不建議在後臺請求的後臺任務或需要時間的任何其他代碼註冊後臺任務。嘗試在用戶實際存在應用程序之前,在其他事件上註冊後臺任務。 – Pratyay
感謝您的回覆..現在我正在註冊此另一個按鈕單擊事件..仍然無法正常工作..我必須缺少的東西 –
您是否聲明瞭appx清單中的後臺任務? 'backgroundTask.Class1'是一個公共可激活的WinRT組件嗎?你也可以澄清你真正想要完成的事情嗎?我想知道如果ExtendedExectuion是一個更好的方法來你的情況。 –