Detecting reboot programmatically in Windows Phone 8.1

徘徊边缘 提交于 2019-12-21 17:39:07

问题


I have a WP 8.1 Runtime which launches a DeviceUseTrigger background task. The problem is that whenever the phone reboots, this task obviously cancels, but the task registration remains in place. So when I launch my app the next time the background task appears to be running when in reality it isn't. I want some way of detecting whenever the phone reboots and/or detect in some way whether or not the task is actually running or not. The code I'm using to check background task registration is as follows:

foreach(IBackgroundTaskRegistration task in BackgroundTaskRegistration.AllTasks.Values)
        {
            if ((task as BackgroundTaskRegistration).Name == myTaskName)
            {
                Debug.WriteLine("Task is already running");
            }
        }

回答1:


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.



来源:https://stackoverflow.com/questions/29717798/detecting-reboot-programmatically-in-windows-phone-8-1

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