ispiro
ispiro

Reputation: 27673

Detect app closing

How can I run code when my Xamarin.Forms (PCL) app is closing? (Similar to Windows' Application.ApplicationExit event.)

There are actions that need to be done prior to the application exiting, and the application might be terminated by the user or by the device needing the resources.

Upvotes: 2

Views: 15070

Answers (2)

Gerald Versluis
Gerald Versluis

Reputation: 34013

From the Xamarin.Forms lifecycle documentation:

Note that there is no method for application termination. Under normal circumstances (ie. not a crash) application termination will happen from the OnSleep state, without any additional notifications to your code.

In you App.xaml.cs you will find the OnSleep method which hooks into the respective equivalent on each platform.

protected override void OnSleep()
{
    // TODO write code when your app goes to bed
}

But there is no guarantee this is called in all scenarios where the app is really being closed. So, if possible, you should probably find an alternative.

Upvotes: 7

Gusman
Gusman

Reputation: 15151

On mobile applications a true application exit cannot be detected as the process is terminated, what you can detect is when the application goes background (even an application swipe is detected as entering background, only "Force close" isn't trapped).

To detect the background state you can override the OnSleep function on your Application:

protected override void OnSleep()
{
    Debug.WriteLine ("OnSleep");
}

Upvotes: 4

Related Questions