Introduction To Android Activity And Its LifeCycle

Android Activity is a single screen, like window, in which app draws it’s UI. This window typically fills the device’s screen, but may be small than the screen and float on top of other windows. Generally, one android activity implements one screen in an app.
Note – Activity is subclassed from ContextThemeWrapper class.

1. Android Activity Life Cycle

Below picture depicts the life cycle of an android activity in any android app. (image courtesy : android.com )

Tutorialwing Android Activity LifeCycle

Tutorialwing Android Activity LifeCycle

If you know about c, c++ or java programming, you know that every program starts from main() method. Very similar way, Android System starts an android program with in activity by calling onCreate() method. Then, Android program ends by calling onDestroy() method in activity. Between onCreate() and onDestroy() method, a series of methods are called.

Whenever we try to open an app, Activity serves as an entry point of the app.

Whenever an activity is is launched, onCreate() method is called. In this way, entire lifetime of activity starts with first call to onCreate() method. Activity does all setup of global state in onCreate() method. For example, layout is defined in this method by calling setContentView() method.

Then, onStart() method is called. It starts the visible lifetime of activity. It means you can see the activity on-screen, though it may not be in the foreground interacting with the user. During visible lifetime, we maintain the resources in the activity to be shown to the user. This method may be called multiple times.

Then, onResume() method is called. With call to this method, foreground lifetime of activity is started. So, activity is visible to the user and user is also interacting with activity.

If a new activity comes into the foreground, onPause() method of old activity is called. With call to onPause() method, foreground lifetime of activity ends. Thus, activity is not in front of all other activities and user can not interact with it now. onPause() and onResume() methods may be called many times. For example, When an activity result is delivered, when a new intent is delivered etc.

If another activity has been resumed and is covering old activity, old activity is not visible to the user. In this situation, onStop() method is called. This ends the visible lifetime of the activity.

Now, if the activity is finishing, onDestroy() method is called. With call to this method, entire lifetime of activity ends. So, we releases all the resources attached with this activity.

We are showing a table that displays a clear picture of which method does what in activity lifecycle.

Method Description Is Method Killable? Next
onCreate() First method to be called whenever activity is created. You should do static setup – create views, bind data to lists etc. No Always followed by onStart() method
onRestart() This method is called when activity has been stopped No Always followed by onStart() method
onStart() This method is called when activity is becoming visible to the user. No Followed by onResume() if activity comes to the foreground, or onStop() if activity becomes hidden
onResume() This method is called when activity starts interacting with the user. At this point, activity is at top of the activity stack. No Always followed by onPause()
onPause() This method is called when an activity is about to start resuming a previous activity. Here, you can save changes to persistent data, stop animations, or other things that are consuming CPU Pre-HONEYCOMB Followed by onResume() if activity returns back to the front, or onStop() if it becomes invisible to the user.
onStop() This method is called when activity is no longer visible to the user. Yes Followed by onRestart() if activity() is coming back to interact with the user, or onDestroy() if activity is being destroyed.
onDestroy() The final call before activity is destroyed. Yes No method is called after that.

Note – If you want to learn more about activity lifeycycle, you can goto official website of lifecycle of activity

2. How to use Android Activity?

Whenever you create an android application, an activity is created by default. Let’s create an android application to understand it clear.

Here, we have created an android application with name AndroidActivity. Now onwards, we will consider this application as a reference in this tutorial.

Note – You can create project in either kotlin or java. For the sake of completeness of this tutorial, we will discuss about both (Kotlin and Java) types of project.

Generally, you need to check at minimum three places for activity. They are –
  A. Code in Java file, Or in Kotlin file if it is a kotlin project. Basically, It is class file for activity.
  B. xml file in res/layout file.
  C. AndroidManifest file.

Note – If everything is OK in these three files, At least, you will see a screen with UI defined in xml file when you run the application.

Now, we are going to see the code related to activity in this application. Note that we have just created an android application AndroidActivity. We have done nothing after that.

Now, we will check code related to activity at those three places.

2.1 Code in class file

In application AndroidActivity, You will see a class file (MainActivity.java, or MainActivity.kt if it is kotlin project) under main/../com.tutorialwing.androidactivity package.

Code in MainActivity.java file –

public class MainActivity extends AppCompatActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
}
Code in MainActivity.kt file –
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

Here, we have extended the class MainActivity with AppCompatActivity. Then, we have defined onCreate() method where we have set the view for this activity using setContentView() method. Whatever UI we want to show to the user, we can define in the xml file (i.e. activity_main.xml) used in setContentView() method.

2.2 Code in xml file

In xml file, we define the user interface we want to show to the user. In this example, we are using activity_main.xml file for MainActivity and showing a button in it. So, code inside res/layout/activity_main.xml file is –

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:gravity="center">

	<!-- Place any widgets/layout here to build UI -->

	<Button
		android:id="@+id/showActivity"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Show Second Activity">
	</Button>

</LinearLayout>

2.3 Code in AndroidManifest.xml file

You must mention about your activity in AndroidManifest.xml file. This is the place where you actually tell the application Hey! There is activity with name MainActivity (or any other name) that we will be used when needed.

Code related to activity inside AndroidManifest.xml file is –

<activity android:name=".MainActivity">
	<intent-filter>
		<action android:name="android.intent.action.MAIN"/>

		<category android:name="android.intent.category.LAUNCHER"/>
	</intent-filter>
</activity>

Here, everything related to activity is inside < activity > tag. You must mention attribute name that contains name of the Activity. Note that there is an < intent-filter > tag within < activity > tag in Manifest file –

<intent-filter>
  <action android:name="android.intent.action.MAIN"/>

  <category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>

Here, android.intent.action.MAIN tell the android application that this activity is entry point of the application i.e. whenever application is started, this activity will be started and serve as an entry point of the application. If you do not want any application to serve as an entry point, do not mention android.intent.action.MAIN in < intent-filter > .

Did you know?
Only one activity can have < category android:name="android.intent.action.MAIN" /> in an android application.

android.intent.category.LAUNCHER is used to indicate that activity should appear in home screen’s launcher or anything else that consider itself to be a launcher.

3. How to Create a New Activity in Application.

If you want to add a new activity in existing android application. You can do it in two ways –
A. Manual Way
B. Using option in Android Studio IDE

3.1 Manual Way to Create New Activity

Basically, you need three things – class file, xml file and code inside manifest file that mention about this activity.
So, follow steps below to create a new activity.
1. Create an xml file (name it activity_second.xml) in res/layout folder and design the UI you want to show to the user. Here, we are showing only button to the user. So, code inside activity_second.xml file is –

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:gravity="center">

	<!-- Place any widgets/layout here to build UI -->

	<Button
		android:id="@+id/finishActivity"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Kill This Activity">
	</Button>

</LinearLayout>

2. Goto folder where java or kotlin file is stored (Here, it’s main/java/com.tutorialwing.androidactivity folder) . Then, create a java or kotlin file and name it (Here, we have named it SecondActivity.java, or SecondActivity.kt if it is kotlin project.)

3. Now, write below code in SecondActivity class.

Code inside SecondActivity.java –

package com.tutorialwing.androidactivity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class SecondActivity extends AppCompatActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_second);
	}
}

Code inside SecondActivity.kt –

package com.tutorialwing.androidactivity

import android.os.Bundle
import android.support.v7.app.AppCompatActivity

class SecondActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)
    }
}

Here, we have inherited SecondActivity class with AppCompatActivity class. Then, we have overridden onCreate method and set layout file that defines UI for this activity.

Did you know?
AppCompatActivity class is base class for activities that use support library action bar features.

4. Then, we need to mention this new activity (i.e. SecondActivity activity) in manifest file –

<activity android:name=".SecondActivity"
  android:label="Second Activity">
</activity>

5. If everything is OK, Finally, your project folders will look like below –

Tutorialwing Android Create Activity - Step 3

Tutorialwing Android Create Activity – Step 3

That’ it. You have successfully added a new activity by yourself.

3.2 Adding New Activity Using option in Android Studio IDE

Follow the steps below to create new activity using option provided in Android Studio IDE –
1. Goto File => New => Activity => Empty Activity and click on it. Below image clearly depicts the process.

Android Create New Activity , Introduction to Android Activity

Create New Activity – Step 1

2. You will get the below screen –

Create New Android Activity , Choose activity name while create new android activity

Create New Android Activity – Step 2

Enter the activity name, layout file name, and language in which you want to create this new file. Then, click on finish button. Now, your activity will be created. Note that you have nothing to do in AndroidManifest file in this scenario. Android Studio IDE will automatically add the related code in manifest file.

3. If everything is OK, finally, your project folders will look like below –

Tutorialwing Android Create Activity - Step 3

Tutorialwing Android Create Activity – Step 3

That’s it. You have successfully created android activity in your android application.

4. How to Start An Android Activity

You can start an activity as below –

Let’s assume we are starting a new activity (SecondActivity) from MainActivity class.

Code in MainActivity.java file –

startActivity(new Intent(MainActivity.this, SecondActivity.class));

You can similarly start a new activity from java file in any android project.

Code in MainActivity.kt file –

startActivity(Intent(this@MainActivity, SecondActivity::class.java))

You can similarly start a new activity from kotlin file in any android project.

5. How to Kill an Android Activity

You can kill any activity by calling finish() method.

finish()

6. onSaveInstanceState() and onRestoreInstanceState() method

Let’s take an example,

Suppose you are filling a form in an android application and you have already entered some data. While filling other data, you change mobile-screen orientation from portrait to landscape. Suddenly whole thing is gone i.e. all the entered data has been reset. Won’t it irritate you? 🙁

You would always like to restore the data, you have already entered, in landscape mode.

To deal with such scenarios, We save data in onSaveInstanceState() method. And restore it in onRestoreInstanceState() method. Let’s see how do we do it –

6.1 How to save data in onSaveInstanceState() method

You can put the data in Bundle, passed as parameter, in onSaveInstanceState method. This method is called to store data before pausing the activity.

Code to save data in onSaveInstanceState() method in java is –

@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
	super.onSaveInstanceState(savedInstanceState);

	// Save UI state changes to the savedInstanceState.
	savedInstanceState.putInt(KEY_INT, 10);
	savedInstanceState.putDouble(KEY_DOUBLE, 3.8);
	savedInstanceState.putBoolean(KEY_BOOLEAN, false);
        savedInstanceState.putString(KEY_STRING, "Android Tutorial by Tutorialwing");
}

Code to save data in onSaveInstanceState() method in kotlin is –

override fun onSaveInstanceState(savedInstanceState: Bundle) {
       super.onSaveInstanceState(savedInstanceState)

       // Save UI state changes to the savedInstanceState.
       savedInstanceState.putInt(KEY_INT, 10)
       savedInstanceState.putDouble(KEY_DOUBLE, 3.8)
       savedInstanceState.putBoolean(KEY_BOOLEAN, false)
       savedInstanceState.putString(KEY_STRING, "Android Tutorial by Tutorialwing")
}

6.2 How to retrieve data in onReStoreInstanceState method

You can get the data, stored in Bundle in onSaveInstanceState() method, back in onRestoreInstanceState() method. This onRestoreInstanceState() method is called after onStart() method when activity is being re-initialised from previously saved state.

Code to restore data in onReStoreInstanceState() method in java is –

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
	super.onRestoreInstanceState(savedInstanceState);

	// Retrieve the saved data in saveInstanceState method
	int myInt = savedInstanceState.getInt(KEY_INT);
	double myDouble = savedInstanceState.getDouble(KEY_DOUBLE);
	boolean myBoolean = savedInstanceState.getBoolean(KEY_BOOLEAN);
	String myString = savedInstanceState.getString(KEY_STRING);

	Toast.makeText(getApplicationContext(), "Retrieved String: " + myString, Toast.LENGTH_SHORT).show();
}

Code to restore data in onReStoreInstanceState() method in kotlin is –

override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)

        // Retrieve the saved data in saveInstanceState method
        val myInt = savedInstanceState.getInt(KEY_INT)
        val myDouble = savedInstanceState.getDouble(KEY_DOUBLE)
        val myBoolean = savedInstanceState.getBoolean(KEY_BOOLEAN)
        val myString = savedInstanceState.getString(KEY_STRING)

        Toast.makeText(applicationContext, "Retrieved String: " + myString!!, Toast.LENGTH_SHORT).show()
}

7. Different types of Android Activity

There are different types of android activity available that can be used depending upon the requirements of the application.

(1) Galley –
(2) Basic Activity
(3) Bottom Navigation Activity
(4) Empty Activity
(5) FullScreen Activity
(6) Login Activity
(7) Master / Detail Flow
(8) Navigation Drawer Activity
(9) Scrolling Activity
(10) Settings Activity
(11) Tabbed Activity

Leave a Reply