Android Activity-Lifecycle and Working | With Example

android_activity
Spread knowledge

 

What is an Android Activity

Activity is a primary component of an Android Application. This article will be explaining Android Activity lifecycle and its implementation.

According to Google Docs following is the definition for an Activity:

An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View).

Simple Explanation:

Android’s activity is one screen in the app’s user interface. Just like a window in java app or a webpage on any website. Android application is basically a combination of multiple activities which interact with each other.Every application has a single  Launcher Activity which is created as soon as the application is launched (This is the screen you see when the app starts). This launcher activity can now start other activities in response to user interaction(clicks)

Example : If you look at different screens shown below of the  Whatsapp android application, these two screens could be two activities inside the application which interact with each other and respond to clicks.

android_activity_example

Android Activity Lifecycle :

As I already told you activity is a single screen in the application which responds to user interaction, so suppose you start an application an Activity-A is created which is then visible to you. A click on any button on Activity-A could start a new Activity-B which is then visible to you and the old Activity-B is not seen anymore. Now you kill the application destroying both Activity A and Activity B

Basically Activity-A has gone through the following states

Created -> Visible-> Invisible ->Destroyed

Now inside the activity these states are represented by multiple callback methods which are invoked when ever the activity goes though the corresponding state in its lifecycle. An activity lifecycle starts from when its created to the time it is destroyed

activity_lifecycle

 onCreate()

  • This is the first callback an activity receives. This is invoked when the activity is first created.This is where we bind the UI of the activity.

onStart()

  • This callback indicates that the activity has entered into Started state.This callback is invoked when the activity is visible but not yet interactive.

onResume()

  • This callback indicates that the activity has entered into Resumed state. It basically means the activity is now in foreground and the user can now start interacting with the activity.

onPause()

  • This callback indicates that the activity has entered the Paused state.It basically is an indication that the user is now leaving the activity. This usually is invoked when something takes away the focus from the activity. This something could be a system dialog,device’s screen going off or even receiving a phone call.

onStop()

  • This callback indicates that the activity has entered in Stopped state. It indicates that the activity is no longer visible on the screen.

onDestroy()

  • This is a final callback an activity receives. This callback is invoked just before an activity is terminated.

Implementing all these callbacks inside an activity would lead to a very seamless user experience. API Documentation for Activity is available here .

Activity Example:

Step-1 :

The first step for creating any android component would be declaring it in the application AndroidManifest.xml. Just add the <activity> tag as shown in the snippet below

<application
 android:allowBackup="true"
 android:icon="@mipmap/ic_launcher"
 android:label="@string/app_name"
 android:roundIcon="@mipmap/ic_launcher_round"
 android:supportsRtl="true"
 android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

 

Step-2:

If you are using a Android studio creating a activity will be very simple. Just right click on your package and select New-> Activity->. Doing this your default activity class will be automatically created along with the layout file. But in this article we will create both the files manually.

  • Just right click on your package select New->Java Class. Create a class by the name MainActivity.java.  In the super class option enter AppCompatActivity. With this as the super class you can now implement all the lifecycle callbacks of an Activity.

new_activity_class

 

  • Right click on res/layout and then select new layout resource file.Create a file by the name activity_main.xml. This will be the UI for your activity. We will have a image and text in our UI for this example
  • Download the image from here to your res/drawable folder. Name it logo .This will be the resource of your image in UI
  • In the res/values open string.xml. Now add the following tag as shown in the snippet below[code lang=”java”]
    <string name=”activity_string”>Congrats on you first activity</string>
    [/code]Add the following code in the your layout file activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.krazybee.myapp.MainActivity">
        <ImageView
          android:id="@+id/my_image"
          android:layout_width="150dp"
          android:layout_height="150dp"
          android:layout_centerInParent="true"
          android:src="@drawable/logo" />
        <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_below="@+id/my_image"
          android:layout_centerHorizontal="true"
          android:padding="10dp"
          android:id="@+id/my_text"
          android:text="@string/activity_string"
          android:textStyle="bold" />
    </RelativeLayout>

     

    And this code to you MainActivity.java

    public class MainActivity extends AppCompatActivity {
    
        private static final String TAG = "APP_DEBUG";
    
        private ImageView logoImage;
    
        private TextView logoText;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            Log.d(TAG, "The onCreate() event");
            setContentView(R.layout.activity_main);
    
            logoImage = (ImageView) findViewById(R.id.my_image);
            logoText = (TextView) findViewById(R.id.my_text);
    
        }
    
        /** Called when the activity is about to become visible. */
        @Override
        protected void onStart() {
            super.onStart();
            Log.d(TAG, "The onStart() event");
        }
    
        /** Called when the activity has become visible. */
        @Override
        protected void onResume() {
            super.onResume();
            Log.d(TAG, "The onResume() event");
        }
    
        /** Called when another activity is taking focus. */
        @Override
        protected void onPause() {
            super.onPause();
            Log.d(TAG, "The onPause() event");
        }
    
        /** Called when the activity is no longer visible. */
        @Override
        protected void onStop() {
            super.onStop();
            Log.d(TAG, "The onStop() event");
        }
    
        /** Called just before the activity is destroyed. */
        @Override
        public void onDestroy() {
            super.onDestroy();
            Log.d(TAG, "The onDestroy() event");
        }
    }

     

    I have put up logs in every callback so that you can check how these are invoked when the app starts. If you check the logs  you will notice all the callbacks are invoked in the same sequence explained above. You can play around a little to see how these callbacks work..

    This is what your activity will look on the device

    android_activity_screenshot
    MainActivity

    Want to read about the other 3 Android Components?? Click here


Spread knowledge

4 Replies to “Android Activity-Lifecycle and Working | With Example”

Leave a Reply

Your email address will not be published. Required fields are marked *