Search code examples
windows-phone-8.1live-tilelost-focusstartmenu

When App Loses Focus, Do This


I have a method that I need to run when my app loses focus. Specifically, I need to update my live tile every time the user goes to the start menu. How can I trigger this method whenever the user either presses the back button or the start menu button?

I thought if I put it in the OnSuspending(object sender, SuspendingEventArgs e) method in App.xaml.cs that it would work, but it turns out this is not the case!! The closes I have found is when the app launches, but that doesn't really do what I want.


Solution

  • The Suspending event is the thing you are looking for:

    When the user moves an app to the background, the OS waits a few seconds to see whether the user immediately switches back to the app. If the user does not switch back, the OS suspends the app.

    But this event is not being raised while you are debugging and you send your app to background. Normally (without debuging) it should work fine. Remember only that you have limited time to perform actions in this event, also don't forget to obtain a deferral and release it:

    private async void OnSuspending(object sender, SuspendingEventArgs e)
    {
       var deferral = e.SuspendingOperation.GetDeferral();
       // do your code here
       deferral.Complete();
    }