Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UWP page lifecycle

I have app with multiple pages, connected with navigateto logic.

One of pages contains media element with webcam binding. After entering to background mode (for example, by minimizing app thought clicking system menu), camera element stopped. So, I subscribe to
Windows.ApplicationModel.Core.CoreApplication.LeavingBackground event and reinitialize camera. Everything is ok if current page is page with this subscription and camera element. If current page is another page, and app is restored, LeavingBackground this event occurs anyway, so hidden page trying to reinitialize camera.

I tried to set this.NavigationCacheMode = NavigationCacheMode.Disabled, so instance of page that contains media element and subscription to LeavingBackground event theoretically have to be disposed after NavigatedTo event according MSDN. But it's work other way that I'm not understand.

It seems that camera page instantiated once, and forever, and will receive LeavingBackgound event always - that's bad for me.

I tried to compare Window.Current.Content.GetType() with type of page that contains camera element, but sometimes this type contains type of another pages, but sometimes it shifted with Content.Content, so I'm stuck.

like image 278
Dmitry Andreev Avatar asked Oct 28 '25 17:10

Dmitry Andreev


2 Answers

I would assume you have to unregister the event handler when navigating away from that page:

public sealed partial class WebCamPage
{
    public WebCamPage()
    {
        InitializeComponent();
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        Windows.ApplicationModel.Core.CoreApplication.LeavingBackground += OnLeavingBackground;
    }

    protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
    {
        Windows.ApplicationModel.Core.CoreApplication.LeavingBackground -= OnLeavingBackground;
    }

    private void OnLeavingBackground(object sender, LeavingBackgroundEventArgs e)
    {
        // Your code here.
    }
}
like image 71
Laith Avatar answered Oct 30 '25 13:10

Laith


You need to handle the Suspending and Resuming events to clean-up and re-initialize the camera correctly, like it is shown in the camera sample app:

https://github.com/Microsoft/Windows-universal-samples/blob/master/Samples/CameraStarterKit/cs/MainPage.xaml.cs

Thanks, Stefan Wick - Windows Developer Platform

like image 29
Stefan Wick MSFT Avatar answered Oct 30 '25 14:10

Stefan Wick MSFT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!