Android  Activity and its Lifecycle

Activity in Android is one of the most important components of Android. It is the Activity where we put the UI of our application. So, if you are new to Android development then you should learn what an Activity is in Android and what is the lifecycle of an Activity. In this blog, we will learn about Activity and its lifecycle. So, let's get started.

What is an Activity in Android?

Whenever you open an Android application, then you see some UI over your screen. That screen is called an Activity. It is the basic component of Android and whenever you are opening an application, then you are opening some activity.

For example, when you open your Gmail application, then you see your emails on your screen. Those emails are present in an Activity. If you open some particular email, then that email will be opened in some other Activity.

So, an Activity is a class that provides a window to draw the UI of your application. The first screen that is launched when you open an app is generally called MainActivity. You can call any Activity from any Activity.

When we all started with coding, we know about the main method from where the program begins execution. Similarly, in Android, Activity is the one from where the Android Application starts its process. Activity is one screen of the app's user interface. There is a series of methods which runs in an activity.

There is a lifecycle associated with every Activity and to make an error-free Android application, you have to understand the lifecycle of Activity and write the code accordingly.

Android Activity Lifecycle

An Android activity undergoes through a number of states during its whole lifecycle. The following diagram shows the whole Activity lifecycle:

Image Credit: Android Website

The Activity lifecycle consists of 7 methods:

  1. onCreate() : It is called when an activity is first created. When a user opens the app then some Activity is created. You have to implement this method in every activity because, inside this method, all the necessary components of your activity will be initialized. Here the initialization of your application's UI is done.
  2. onStart(): This method is called when an activity becomes visible to the user. When all the initialization is done by the onCreate() method, then this method is called.
  3. onResume(): It is called just before the user starts interacting with the application. Most of the core functionalities of the app are implemented in this method.
  4. onPause():  It is called when the activity is paused i.e. it is mostly called when you press the back or home button of your Android device. It is an indication that the user is leaving the activity and starting some other activity.
  5. onStop(): It is called when the activity is no longer visible to the user. If you are starting a new activity, or some existing activity is entering into onResume() state, then the current activity will not be visible to the user and is stopped.
  6. onRestart(): It is called when the activity in the stopped state is about to start again. By doing so, the state of the activity from the time it was stopped will be restored.
  7. onDestroy(): It is  called when the activity is totally destroyed i.e. when you clear the application stack then onDestroy() will be called and all the states of the activity will be destroyed.

So, these are the 7 methods that are associated with the lifecycle of an activity. Now, let's look at one practical example, but before that, you need to learn the basics of Intents in Android because we are going to use them in our example.

What are Intents?

Intents are the messaging body using which we can communicate between all the Android components. Intent also carries the information to pass between the components i.e. we can use intents to pass some message between some activities or in between some other Android components. Intents are of two types:

  1. Implicit : The implicit intent is used to specify some task and all the application that is capable of doing that task can perform the task. For example, while using an application, you can set an implicit intent that you want photos and the capable app will open and provide you with the required photos just like a gallery app.
  2. Explicit:  The explicit intent is used to open another activity from a particular activity within the same application, like opening settings screen in your app.

Practical Example

Now, we are done with the basics of Activity, Activity lifecycle and Intents. Let’s start with developing our application in Kotlin. We are going to develop an app which consists of three screens and on opening the app, we will see the first screen with two buttons clicking on which will open those other two screens. So, basically, we have one MainActivity and from that activity, we are launching the other two activities.

Follow the below steps to create a project in Android Studio:

  • Open Android Studio > Create New Project. If you already had a project open then create a new project by going to the File option in the top left menu and select New > New Project.
  • Add the application name, the application directory, and other required details and then select the "EmptyActivity" template. (Select the language as Kotlin)
  • By default, you will get a MainActivty.kt file in Java folder and activity_main.xml in res > layout folder. These both files i.e. the code file and the UI file together make one activity. Add two button in the layout file and these two buttons will be used to launch the other two activities from the MainActivity. The code for the activity_main.xml will be:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".MainActivity">

    <Button
        android:id="@+id/btnMindorks"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="MindOrks"
    app:layout_constraintBottom_toTopOf="@+id/btnGetmeanapp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnGetmeanapp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="GetMeAnApp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnMindorks" />

</android.support.constraint.ConstraintLayout>
  • Here, we have two buttons who says - "MindOrks" and "GetMeAnApp". Following is the UI of our MainActivity.
  • Now, we need to create the other two activities. To create an Activity in your project, go to File > New > Activity > EmptyActivity. Enter the name of the activity as MindorksActivity.
  • Similarly, create another activity and name it as GetmeanappActivity. For both the activities, two files will be created i.e. the Kotlin file and the layout file. Since you are creating an activity, so there is no need to connect these files because, these files are automatically connected. Following is the project structure of our application:
  • Inside the two newly created XML layout files you can put one TextView so that when you open them you can see different texts for different activities. Following is the code for the activity_getmeanapp.xml file:
activiy_getmeanapp.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    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">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="GetMeAnApp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
  • Following is the code for the activity_mindorks.xml file:
activity_mindorks.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    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">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="MindOrks"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
  • Now, the important part. We have to connect both these activity with the buttons present on the MainActivity page. On the click of the button, the other activities will be started. So, we need some kind of listener that will get triggered whenever we press a button. The listener responsible for this is called setOnClickListener(). This method will be called when a button is clicked and inside this method, we will write the code for opening the activity.
  • To open an activity, we have to use some intent. So, to open the MindorksActivity, we are using the mindorksIntent and to open the GetmeanappActivity, we are using the getmeanappIntent. Following is the code of our MainActivity.kt file:
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // opening MindorksActivity
        btnMindorks.setOnClickListener {
            var mindorksIntent = Intent(this, MindorksActivity::class.java)
            startActivity(mindorksIntent)
        }
        // opening GetmeanappActivity
        btnGetmeanapp.setOnClickListener {
            var getmeanappIntent = Intent(this, GetmeanappActivity::class.java)
            startActivity(getmeanappIntent)
        }
    }
}
  • Here, btnMindorks and btnGetmeanapp are the ids of the buttons which we had already set up in activity_main.xml where we created these buttons.

We had created an object from the Intent class and put two arguments in it.

  1. this: It is used to tell from which context it will open the new activity, so specify this as a reference to the MainActivity because, from MainActivity, you are opening some other activity.
  2. MindorksActivity::class.java / Getmeanapp::class.java: It shows the activity that we need to open i.e. our target activity.

startActivity() - passing the intent object in this method will launch the new activity.

  • Now, run your application in the mobile device or on Android Emulator. You can use the "Green Play" button present in Android Studio to run the application, or you can use Shift + F10 to run your application.
  • Press both the buttons present on the MainActivity and you will see different activities launching when you press the button.

Congratulations on your very first Android application :) Now, you are ready to dive deeper into some of the complex topics of Android.

That's it for this blog, see you in the next blog. Keep experimenting with your first Android application.

Happy Learning :)

Team Mindorks!