Detecting reboot programmatically in Windows Phone 8.1

╄→гoц情女王★ 提交于 2019-12-04 11:13:02

I was able to solve the problem in an almost embarrassingly simple way. The background task cancels when the phone is shutting down so I attached an event handler to the taskInstane.Canceled event in my background task and just added two lines to it:

StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("TaskCancelling.txt" CreateCollisionOption.OpenIfExists);
deferral.Complete();

Then, in the foreground app, the following code runs whenever the app launches:

foreach(IBackgroundTaskRegistration task in BackgroundTaskRegistration.AllTasks.Values)
{
   if ((task as BackgroundTaskRegistration).Name == myTaskName)
   {
      if (await IsFilePresentInLocalDirectory("TaskCancelling.txt"))
      {
         //Task registration is present, but task isn't actually running.
         //Unregister the useless task
         (task as BackgroundTaskRegistration).Unregister(true);
         //Delete the file
         StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("TaskCancelling.txt");
         await file.DeleteAsync();
         //Relaunch the DeviceUseTrigger task
         RelaunchBackgroundTask();
      }
   }
}

private async Task<bool> IsFilePresentInLocalDirectory(string fileName)
{
   try
   {
      StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
      return true;
   }
   catch (Exception exc)
   {
      return false;
   }
}

Pretty self-explanatory, I just create an empty text file to create a sort of log of task cancellation and each time my app launches I check to see it the file is present. If it is, the task is relaunched and the file is deleted.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!