Search code examples
c#winrt-xamlwin-universal-apptemplate10

Template10 Resume running services after app suspension


I am developing a UWP template 10 (Hamburger) app which makes use of the Microsoft Band, I thought I had pretty much finished as I have all my services tied up to the Band (through a class library project) and the values are updating on screen perfectly. I then started testing app resume and came across a problem. When I restart an app the user is taken back to the values page but the values no longer update. Basically the connection to the band seems to still be valid but the readingchanged voids are no longer working.

So I added code in the MainPageViewModel OnNavigatedFromAsync method to stop all of the services no problem. But then I found that when resuming the OnNavigatedToAsync method does not get fired so I can't work out how to restart all the services.

I also tried adding the overrides for OnResuming and OnSuspendingAsync in app.xaml.cs but then can't work out how to call methods in the MainPageViewModel from there. Is there a proper way to handle things like this using Template10?


Solution

  • I'm assuming you are using Simulation Dashboard controls in Visual Studio to suspend and then resume your app. Well, then don't use the resume button. It doesn't work as expected. To test resuming of your app, use the suspend button and then open it from the Band's interface (instead of using the resume button). The OnNavigatedToAsync method should then fire just fine.

    Update: Based on the discussion following this answer, I am providing an updated answer on the following lines.

    Set up a static viewmodel property in the App class, like this:

    public static TypeOfMyViewModel MyViewModel;
    

    Then, in the TypeOfMyViewModel constructor, add the following line to set value to the property:

    public TypeOfMyViewModel()
    {
        App.MyViewModel = this;
    }
    

    And, finally, in the OnResuming method just call a method from the ViewModel which will resume your services, like this:

    public override void OnResuming(object s, object e, AppExecutionState previousExecutionState)
    {
        MyViewModel.ResumeServices();
    }