-->

Detecting reboot programmatically in Windows Phone

2020-07-19 03:19发布

问题:

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.