Xamrin forms lifecycle

  Xamarin.Form is a cross-platform mobile app development platform using XAML for the front-end and C# for the backend of the app. In Xamarin.Form, we can share all the code. Xamarin.Forms also provides 100% native API coverage for Android and iOS. So we can develop native apps for Android, iOS and Windows.


Xamarin.Forms Application Lifecycle:


When we create a Xamarin.Forms application, we see four projects:


Portable Project: This is the project where we will code 95% of our application code and this code is shared across all three platforms.

Android: This is the project where we will set the Android app icon and splash screen and all other code will come from the portable project.

iOS: In this project, we have set the iOS app architecture and icon.

Universal Windows: The Universal Windows Platform is an application platform for building both Windows Mobile applications and Windows desktop applications.


You can see the detail of the project where we have created a project for android and iOS.


Here you can see all projects contained in a single solution. In below image we've created two projects for android and iOS.






The Xamarin.Forms application lifecycle consists of three virtual methods that are overridden to handle the lifecycle method. These methods are available in App. Xaml. Cs class in a portable project.




The three methods are:

  • OnStart()
  • OnSleep()
  • OnResume()






These three methods are called when the application is in a running, sleeping, or resuming state. There is no method to exit the application. The application terminates with the OnSleep() method without further notice.


We can see all these files in App.Xaml.cs in our Xamarin.Forms (portable project).


OnStart() method.

Calling the OnStart() method when the application starts for the first time. When the application starts, it reads all the code written in the OnStart() method.


Syntax of OnStart() method:

    protected override void OnStart()

    {

                // Executes when your application starts

    }



OnResume() Method

OnResume() method is called when we come back to the application from sleep mode.

Syntax of OnResume() method :

protected override OnResume()

    {

            // Execute this code when app resumes execution

    }


OnSleep() Method

The OnSleep() method is called when the application is in sleep mode, i.e. when there is no work in the application. Call the sleep method when the user hides the application. In this form, our app is open in the background in a sleep state.

Syntax for OnSleep() method


protected override OnSleep()

{

        //Executes this code when application is in sleep mode

}


The code will look like below image




Previous Post Next Post