Del via


Xamarin.Forms App Lifecycle

The Application base class provides the following features:

Lifecycle methods

The Application class contains three virtual methods that can be overridden to respond to lifecycle changes:

  • OnStart - called when the application starts.
  • OnSleep - called each time the application goes to the background.
  • OnResume - called when the application is resumed, after being sent to the background.

Note

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

To observe when these methods are called, implement a WriteLine call in each (as shown below) and test on each platform.

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

Important

On Android, the OnStart method will be called on rotation as well as when the application first starts, if the main activity lacks ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation in the [Activity()] attribute.

There are two events on the Application class that provide notification of pages appearing and disappearing:

  • PageAppearing - raised when a page is about to appear on the screen.
  • PageDisappearing - raised when a page is about to disappear from the screen.

These events can be used in scenarios where you want to track pages as they appear on screen.

Note

The PageAppearing and PageDisappearing events are raised from the Page base class immediately after the Page.Appearing and Page.Disappearing events, respectively.

There are four events on the Application class, each with their own event arguments, that let you respond to modal pages being shown and dismissed:

  • ModalPushing - raised when a page is modally pushed.
  • ModalPushed - raised after a page has been pushed modally.
  • ModalPopping - raised when a page is modally popped.
  • ModalPopped - raised after a page has been popped modally.

Note

The ModalPopping event arguments, of type ModalPoppingEventArgs, contain a Cancel property. When Cancel is set to true the modal pop is cancelled.