简体   繁体   中英

Page and App events behavior in Windows Phone 8.1 Runtime

I'm having trouble managing the life cycle of my app because I'm unsure exactly which events and functions pertaining to the page/app lifecycle run when. It'd be nice if Microsoft tabulated it all somewhere. To be specific, here's what I think I know and what I don't know about the behavior of the each of the following events/functions:

Page.Page() (constructor): Runs when the page is created for the first time. Unsure if it runs only once while the app is running, or each time I navigate to the page within a single session.

Page.OnNavigatedTo() : Runs when the page is created and each time it is navigated to.

Page.OnNavigatedFrom() : Runs when the user leaves the page. Does not run when the user presses the Start button or the lock screen button while the page is displaying.

App.App() (constructor): Runs only once when the app is launched.

App.Resuming : Fires when the app is brought into view after being minimized/suspended, or when the user unlocks the screen and the app comes into view. Does not run when the app is started for the first time.

App.Suspending : Fires when the user presses the back button on the home page (ie the app is no longer in view) and when the start button is pressed.

Anything I missed or got wrong? The reason I'm trying to be sure is that my app has a page which runs background audio player which in turn needs a carefully managed system of event subscription/unsibscription, and it often behaves awkwardly if I hit the start button while on that page. And another issue is that I have a static object in my App.xaml.cs which I'm using across the app and which exposes some events. Right now I'm subscribing/unsubscribing to the events on each page like so:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    App.globalObject.Event1 += Event1_handler;
}

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    App.globalObject.Event1 -= Event1_handler;
}

But I'm unsure if this is the correct approach (obviously I'm trying to ensure that I'm only subscribed to an event once to avoid the event handler running multiple times). Should I just subscribe to the event once in the page's constructor instead?

Edit: I'm using a project template with the SuspensionManager and NavigationHelper classes included, in case that changes anything.

Your code and logic looks OK to me, but as igrali suggested in comments, you can always "clear" the handler before subscribing. It's kinda hacky, but it will do the job

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    App.globalObject.Event1 -= Event1_handler;
    App.globalObject.Event1 += Event1_handler;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM