Detect app closing
Solution 1
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.
Solution 2
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");
}
ispiro
Updated on June 04, 2022Comments
-
ispiro almost 2 years
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.
-
ispiro over 6 yearsDo you happen to know if
onSleep
will be raised when a user taps the X to close the application from the list of running applications? (or swipes up on iOS) -
Gerald Versluis over 6 yearsAs stated in the quote, the
OnSleep
should be raised under normal circumstances. So it might be worth some trouble to investigate this by adding some debug output to see what happens in your code. -
Gerald Versluis over 6 yearsNo problem! Just make sure to accept it as an aswer whenever you can if it helped :)