Close
Topic : Activity Lifecycle - OnCreate() | OnStart() | OnResume() | OnPause() | OnStop() | OnDestroy() | OnRestart()

Activity Lifecycle:

Activities are the fundamental building block of Android Application and they can exist in a number of different states. Activity Lifecycle begins with instantiation and ends with destruction including many states in between. When an activity changes state, the appropriate lifecycle event method is called, to Notify the activity of the impending state change and allowing it to execute code to adapt to that change.

In Order to handle Android Activity Lifecycle, the Activity Class provide a collection of methods. These methods allow developers to implement the functionality that is necessary to satisfy the state and resource management requirements of their applications. The following Diagram Illustrates the states an Activity can go through during its lifetime.


Activity Lifecycle: infobrother

These methods are provided by Android SDK and Xamarin.Android Framework to manage the state of activities within an application. When the Activity state change, The Operating System notify and call the specific method to handle that activity.

All methods are predefined by Android SDK and Xamarin.Android Framework, but we can override these methods within an activity to handle state changes. Let's Examine each of these lifecycle methods by writing this simple and useful example.




  • Step 1 - Create Project:

    » Open Visual Studio, and create new Android Project using Black Android template.
    » Open Resources » Layout » Main.axml file, Drag & Drop button in Designer Window.
    » Switch back to source Window, and the make some changes as shown below.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minWidth="25px"
    android:minHeight="25px">
    <Button
        android:text="@string/buttontext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button1" />
</LinearLayout>




  • Step 2 - Edit Strings.xml File:

    » Open Resources » Values » String.xml file, and Assign the values to button.

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="app_name">ActivityLifeCycle</string>
  <string name="buttontext">Start Next Activity</string>
</resources>



Step 3 - Edit MainActivity.cs file:

Now it's time to Use Lifecycle Methods to Handle Activities changes. These Methods are called on the User Interface thread and can block the Operating system to perform any other work such as hiding the current activity, displaying new activity etc. So, make sure, The Code to override the methods should be enough brief as possible to make an application feel well performing and able to perform others operations, like, any long-running tasks should be executed on a background, user can hide the activity and start another activity, etc.

Let's examine each of these lifecycle methods and learn, how we will use it in our Application.



Namespace:

In Order to Use The all lifecycle Methods, we need to include following Namespace in our Application.


using Android.App;


OnCreate():

Whenever the Activity is created, OnCreate() is the first method to be called by OS. This method is Always overridden to perform some start up Functions that may require by an Activity such as, Creating Views, Initializing Variables etc.


protected override void OnCreate(Bundle bundle)
{
   base.OnCreate(bundle);
}

Oncreate() Method take one parameter, which is a dictionary for storing and passing state Information and Objects between activities.

User Launch the app, Oncreate() Method has been called by OS to perform some start-up operation. The Layout and views has been created and the Variable has been initialized by the method - let's move onward to Start the Application -


OnStart():

The Activity has been created and onCreate() method is finished, now it's time to call OnStart() method to perform some specific tasks right before an activity becomes visible such as refreshing current views within the activity.


protected override void OnStart()
{
   base.OnStart();
}

After OnCreate(), The OS call OnStart() method to refresh the Application contents. The app is loading now - let's move onward to Use the Application -


OnResume():

OnStart() Method has finished its work, and the application is ready to start interacting with the user. The OS Call OnResume() method immediately to perform tasks such as: Start Animation, Display any Relevant alerts and dialogs box, play a sound (if any) etc.


protected override void OnResume()
{
   base.OnResume();
}

OnCreate() Loaded the application completely, now the application is ready to interact with user. Animation as been started to welcome user, Dialogs box has been pop up to ask for update application.

OnResume() method is important, because any operation that is Pause by calling OnPause() method should be Resume by calling OnResume(). It's the only lifecycle method that is guaranteed to execute after Onpause() when bringing the activity back to life.



OnPause():

The system can put the activity into the background by calling OnPause() method. Activities should override this method if they need to -
» Commit unsaved Changes to persistent data.
» Destroy or Clear up Other Objects consuming resources.
» Ramp down frame rates and pausing animations.
» Unregister external event handlers or Notification handlers.


protected override void OnPause()
{
   base.OnPause();
}

There are two Possible Lifecycle methods that will be called after OnPause():
» OnResume() Will be called, if the Activity is to be returned to the foreground.
» OnStop() will be called, if the Activity is being placed in the Background.


OnResume() Method allow a user to play with the app, suddenly, the user needs to open another application, the System call OnPause() method to pause the application, put in the background, and allow the user to use another application.


OnStop():

The System will call OnStop() method, when The Activity is no longer visible to user. This happens when one of the following occurs.
» New Activity is being started by system and is covering up this activity.
» An Existing Activity is being brought to the foreground.
» The Activity is being Destroyed.

OnStop() Method may be called in Low-Memory Situations, such as When Android is Starved for Resources and can't properly background the activity. Before Calling OnDestroy() method to destroy the Activity, The OnStop() Method prepare the Activity for Destruction. The System can Call onRestart() Method, if the Activity is coming back to interact with the user.


protected override void OnStop()
{
   base.OnStop();
}

User Using an App, He switches to another App, System call OnPause() Method to pause the Activity. But the Android is Starved for Resources and can't properly background the Activity. In This situation, the System will Call OnStop() Method to stop the Application. Now, the User needs to Destroy the application or Restart the Application.


OnDestroy():

To Destroyed the Activity, System will call OnDestroy() Method. Most of the time, Android kill the application process that is hosting the activity, which will result in OnDestroy() method not being invoked. Most of the Activities will not implement this method, because most clean up and shut down process done by OnPause() and OnStop() Methods. OnDestroy() Method is typically overridden to clean Up long running Resources that might leak resources.


protected override void OnDestroy()
{
   base.OnDestroy();
}

There will be no lifecycle Methods called after the Activity has been destroyed.


The application has been stopped due the low-memory or any other problem. Most of the time, application show an Error - "Application stop working". In this situation, user need to kill the process and Close the application.


OnRestart():

When the Activity has been stopped by calling OnStop() Method, To start the Activity again, The system will call OnRestart() Method. User Open an Activity-A, and then Open another activity-B. In this way, the system Invoked OnPause() and OnStop() Method to pause and stop the Activity-A. The Activity-A is moved to the Background but is not Destroyed. Now User want to use Activity-A again, User will restore Activity-A by Using Task Manager and System will call the OnRestart() Method of the Activity to start the activity again. and After OnRestart(), system will call OnStart(), then OnResume() and so on...


protected override void OnRestart()
{
   base.OnRestart();
}

The user was using an application, then he press Home button to do some other task, after finishing his task, he opens that application.


We Write the above Lifecycle methods in our MainActivity.cs file our first activity has been created, now its time to create another activity. follow the Given Steps to create second activity.



Adding Another Activity: infobrother
  • Step 4 - Add Another Activity:

    » Right Click on your Project and add new Item.
    » Choose Activity from list.
    » Add it in Your Project.




In Second Activity, we will write same lifecycle Methods as we wrote in MainActivity.cs file.




Launch the Emulator: infobrother
  • Final Step - Build & Run:

    Our Project has been ready, now its time to build and run the program. This project has two Activities to Demonstrate the Activity lifecycle, and how the various lifecycle methods are called.
    » Run Emulator




Viewing State Transitions:

Each Method in this Example writes to the IDE application output window to Indicate Activity state. To Open the Output Window in Visual studio, Type CTRL + ALT + O. When We start the app, the Output Window displays the state Changes of First Activity as shown -


[ActivityLifecycle.MainActivity] First Activity -OnCreate 
[ActivityLifecycle.MainActivity] First Activity - OnStart
[ActivityLifecycle.MainActivity] First Activity - OnResume

When we click the Button Start Next Activity, we can see in Output Window, First Activity Pause and stop while Second Activity goes through its state changes.


[ActivityLifecycle.MainActivity] First Activity - OnPause
[ActivityLifecycle.SecondActivity] Second Activity - OnCreate
[ActivityLifecycle.SecondActivity] Second Activity - OnStart
[ActivityLifecycle.SecondActivity] Second Activity - OnResume
[ActivityLifecycle.MainActivity] First Activity - OnStop


In this way, Second Activity is started and Displayed in place of first Activity. When we click the Back button, The Second Activity will destroyed and First Activity will Resumed.


[ActivityLifecycle.SecondActivity] Second Activity - OnPause
[ActivityLifecycle.MainActivity] First Activity - OnRestart
[ActivityLifecycle.MainActivity] First Activity - OnStart
[ActivityLifecycle.MainActivity] First Activity - OnResume
[ActivityLifecycle.SecondActivity] Second Activity - OnStop
[ActivityLifecycle.SecondActivity] Second Activity - OnDestroy


Back Vs. Home:

Back Vs Home

Many Android Devices have two distinct buttons, Back and Home. There is subtle difference between the two buttons, even through they appear to have the same effect of putting an application in the background. when user clicks the Back button, they are telling android that they are done with the activity. Android will call OnDestroy() Method to destroy the Activity. In other side, when the user clicks the Home button the Android will call OnPause() method and activity is merely placed into the background and android will not kill the activity.





using Android.App;
using Android.Widget;
using Android.OS;
using Android.Content;
using Android.Util;

namespace ActivityLifeCycle
{
    [Activity(Label = "First Activity", MainLauncher = true)]
    public class MainActivity : Activity
    {
        int count = 0;

        protected override void OnCreate(Bundle bundle)
        {
            Log.Debug(GetType().FullName, "First Activity - onCreate");
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            FindViewById<Button>(Resource.Id.button1).Click += (sender, args) =>
            {
                var intent = new Intent(this, typeof(SecondActivity));
                StartActivity(intent);
            };

            if(bundle != null)
            {
                count = bundle.GetInt("clickCount", 0);
                Log.Debug(GetType().FullName, "First Activity - Recovered Instance State");
            }
        }


        protected override void OnSaveInstanceState(Bundle outState)
        {
            outState.PutInt("clickCount", count);
            Log.Debug(GetType().FullName, "First Activity - saving Instance state");
            base.OnSaveInstanceState(outState);
        }
        protected override void OnDestroy()
        {
            Log.Debug(GetType().FullName, "First Activity - On Destroy");
            base.OnDestroy();
        }

        protected override void OnPause()
        {
            Log.Debug(GetType().FullName, "First Activity - On Pause");
            base.OnPause();
        }

        protected override void OnRestart()
        {
            Log.Debug(GetType().FullName, "First Activity - On Restart");
            base.OnRestart();
        }

        protected override void OnResume()
        {
            Log.Debug(GetType().FullName, "First Activity - On Resume");
            base.OnResume();
        }

        protected override void OnStart()
        {
            Log.Debug(GetType().FullName, "First Activity - On Start");
            base.OnStart();
        }

        protected override void OnStop()
        {
            Log.Debug(GetType().FullName, "First Activity - On stop");
            base.OnStop();
        }
    }
}
using Android.App;
using Android.OS;
using Android.Util;



namespace ActivityLifeCycle
{
    [Activity(Label = "Second Activity")]
    public class SecondActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            Log.Debug(GetType().FullName, "Second Activity - OnCreate");
            base.OnCreate(bundle);
        }

        protected override void OnRestart()
        {
            Log.Debug(GetType().FullName, "Second Activity - OnRestart");
            base.OnRestart();
        }

        protected override void OnStart()
        {
            Log.Debug(GetType().FullName, "Second Activity - OnStart");
            base.OnStart();
        }

        protected override void OnResume()
        {
            Log.Debug(GetType().FullName, "Second Activity - OnResume");
            base.OnResume();
        }

        protected override void OnPause()
        {
            Log.Debug(GetType().FullName, "Second Activity - Onpause");
            base.OnPause();
        }

        protected override void OnStop()
        {
            Log.Debug(GetType().FullName, "Second Activity - Onstop");
            base.OnStop();
        }

        protected override void OnDestroy()
        {
            Log.Debug(GetType().FullName, "Second Activity - ondestroy");
            base.OnDestroy();
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minWidth="25px"
    android:minHeight="25px">
    <Button
        android:text="@string/buttontext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button1" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="app_name">ActivityLifeCycle</string>
  <string name="buttontext">Start Next Activity</string>
</resources>
















I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement