简体   繁体   中英

(Windows phone 10) Handle Application state

I am developing application in windows phone 10

For some reason, I must handle application state (go to background, enter foreground). I have handle event suspend and resume at App.xaml.cs but it does not works, OnSuspending and OnResuming are not reached. Please help me check my source code and show me how to handle those events.

Here is my code:

public App()
    {
        Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
            Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
            Microsoft.ApplicationInsights.WindowsCollectors.Session);
        this.InitializeComponent();
        this.Suspending += OnSuspending;
        Application.Current.Suspending += new SuspendingEventHandler(OnSuspending);
        Application.Current.Resuming += new EventHandler<Object>(OnResuming);

    }

    private void OnSuspending(Object sender, Windows.ApplicationModel.SuspendingEventArgs e)
    {
        var deferral = e.SuspendingOperation.GetDeferral();
        //TODO: Save application state and stop any background activity
        deferral.Complete();


    }
    private void OnResuming(object sender, object e)
    {
        // do some thing
    }

You should use the Lifecycle Events dropdown of Visual Studio 2015. It lets you choose between Suspend , Resume or Suspend and Shutdown states.

Whenever you run your app in debug, it never goes to suspended state on its own.

Some doc here: https://blogs.windows.com/buildingapps/2016/04/28/the-lifecycle-of-a-uwp-app/

You are subscribing to suspend event twice

 this.Suspending += OnSuspending;
 Application.Current.Suspending += new SuspendingEventHandler(OnSuspending);

better leave classic

 this.Suspending += OnSuspending;
 this.Resuming += App_Resuming;

And also same way add resuming event

 private void App_Resuming(object sender, object e)
    {
       // TODO
    }

Do you debug is suspend/resume event works like it's described in this article:
How to trigger suspend, resume, and background events for Windows Store apps in Visual Studio

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