0% found this document useful (0 votes)
39 views8 pages

Activity and Its Lifecycle

An Activity in Android is a component that represents a single screen in an application, with a lifecycle that includes states such as resumed, paused, and stopped. Activities can start other Activities using Intents and must be registered in the Manifest.xml file to function properly. The lifecycle of an Activity is managed by the Android runtime, with specific callback methods for each state, allowing for state preservation and restoration through the Bundle class.

Uploaded by

abhiramputta12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views8 pages

Activity and Its Lifecycle

An Activity in Android is a component that represents a single screen in an application, with a lifecycle that includes states such as resumed, paused, and stopped. Activities can start other Activities using Intents and must be registered in the Manifest.xml file to function properly. The lifecycle of an Activity is managed by the Android runtime, with specific callback methods for each state, allowing for state preservation and restoration through the Bundle class.

Uploaded by

abhiramputta12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Activity

An Activity is an application component that provides you an interface to perform the operations.
More simply, you can say that an Activity is a screen which is presented to the user by an
application. An Activity can be a dialler screen, Google Maps screen, etc. When you open your
application the very first screen that appear at front of you, is called a default Activity (or Main
Activity). There can be more than one loosely coupled Activities in your application. Generally,
as the complexity of your application increases, the need of number of Activities increases
proportionally.
An Activity can start another Activity to perform some actions. If it does so then system stops the
current Activity and preserves it in a stack (called Back Stack). When a new Activity starts, system
run it on to the top of the stack and takes the user’s focus. When a user taps on the back button,
then the current Activity pops out of the stack and relinquish the user’s focus and gets destroyed;
then previous Activity comes into the focus. You can understand this explanation with the help of
a diagram shown in Figure 4.1.

Figure 4.1: Implementation of Back Stack for multiple Activities of an app


(Source: http://developer.android.com/guide/components/tasks-and-back-stack.html)

Creating an Activity:
To understand this in detail consider the following example.
package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
MainActivity.java
Here, in the code, the very first line specifies the package name where your class MainActivity is
to be created. Next two lines are there to import the library classes, AppCompatActivity and
Bundle, in the program to use their functionality in your code. AppCompatActivity class is
included here to inherit its features in your MainActivity class. Using AppCompatActivity instead
of the base Activity class comes with several benefits. Using AppCompatActivity ensures that
your app is backward-compatible, has a consistent design, and can leverage modern Android
features more effectively than using the base Activity class. Your class must inherit the
AppCompatActivity class to use its methods in your defined class. The first method that is called
when your Activity does load into the memory, is onCreate() method. This is an overridden
method of AppCompatActivity class that takes an object of Bundle class to load the previous state
of the Activity. Notably, object of the Bundle class generally stores the state of the Activity.
The setContentView() method is a fundamental method in Android development that connects an
Activity with its corresponding layout, ensuring the UI is properly set up and displayed. It takes
the reference of the layout as an argument. In this example,
setContentView(R.layout.activity_main) tells the Activity to use the activity_main.xml file from
the res/layout directory as its layout.
Generally, you add the graphical components in an XML layout file. This will make it easy to
manage complex arrangement of graphical components in the Activity. Also, using an XML code
is an easy and structured task. If activity_main.xml is the name of the layout file, then it would be
included in the Java code using following code (shown in Bold):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
But, if you do not want to design the layout in XML, you can use java instead. But it requires a
complex java code to design the layout and add the graphical components. A simple example is
shown in the following box. But, still you need to write more code to make the design attractive,
whereas it designs can be made attractive using XML easily that we we will see in the upcoming
lectures/chapters.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a LinearLayout
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
// Create a Button
Button button = new Button(this);
button.setText("Click Me");
// Add the Button to the LinearLayout
linearLayout.addView(button);
// Set the LinearLayout as the content view
setContentView(linearLayout);
}

Remember that an Activity should be registered in the Manifest.xml file after its creation. To
register an Activity in the Manifest file, use the <activity> tag within <application> tag. The
<activity> tag consists of many attributes such as name, label, themes, and permissions, to add the
properties of the Activity. If you don’t specify the <activity> tag in your Manifest file then the
Activity will not display on the screen, and system will show a run time error when you run the
application. An <activity> tag contains an <intent-filter> tag to specify the Intents that can start
the Activity. Intents are described in detail the upcoming lectures. Example is given below.
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>

An Activity can start another Activity or application. An Activity can


accomplish this job with the help of a special feature of Android, called
Intent. Intent will be discussed in upcoming lectures.
Note it!

To have proper understanding of the working of an Activity you need to first know lifecycle of
the Activity.

Activity Lifecycle:
From its creation to its conclusion, an Activity goes through many stages of its life
such as create, start, pause, stop, etc. This journey of Activity to passing through
different stages of life called lifecycle of the Activity. Every stage of the Activity
lifecycle has a specific method associated to it, called call-back method. When an
Activity stops and another starts, it means a call-back method is called for each
Activity. The lifecycle of an Activity is managed by the Android run time system.
Generally, an Activity can remain in following three states:
1. Resumed: This state is also called running state. In this state an Activity remains
in the foreground of the screen and has the focus of the user.
2. Paused: When another Activity comes at the foreground of the Activity, then
Activity exists in paused state. In this state Activity remains alive and partially
visible but doesn’t have focus of the user. When an Activity remains alive, it
means the object of the Activity still holds in the memory and carries its
involvement with the window manager.
3. Stopped: When an Activity goes into the background due to another Activity
then it remains into the stopped state. In this state, while an Activity remains
alive, but it relinquishes the involvement with window manager. This means it
is no longer visible to the user in the foreground or background.
Figures 4.2.1 and Figure 4.2.2 is depicting the state diagrams to represent the
different stages of the Activity life cycle with different call-back methods:
Figure 4.2.1: A simplified illustration of Activity Lifecycle
(Source: http://developer.android.com/training/basics/activity-lifecycle/starting.html)
Figure 4.2.2: Activity Lifecycle
(Source: http://developer.android.com/guide/components/activities.html)
Following table is showing each lifecycle call-back method with details such as name of the
method, description of the method, what method is called after the specified method, method is
killable or not, etc.
Table 4.1: A summary of the activity lifecycle's call-back methods
(Source: http://developer.android.com/guide/components/activities.html)
Method Description Killable Next
after?
onCreate() Called when the activity is first created. In the onCreate() No onStart()
method, perform basic application startup logic that
happens only once for the entire life of the activity. This
is where you should do all your normal static set up such
as create views, bind data to lists, and so on.
onRestart() Called after the activity has been stopped, just prior to it
No onStart()
being started again.
onStart() When the activity enters the Started state, the system No onResume()
invokes onStart(). This call makes the activity visible to
the user as the app prepares for the activity to enter the
foreground and become interactive. For example, this
method is where the code that maintains the UI is
initialized.
onResume() When the activity enters the Resumed state, it comes to No onPause()
the foreground, and the system invokes the onResume()
callback. This is the state in which the app interacts with
the user. The app stays in this state until something
happens to take focus away from the app, such as the
device receiving a phone call, the user navigating to
another activity, or the device screen turning off.

onPause() The system calls this method as the first indication that onResume()
Yes
the user is leaving your activity, though it does not or
always mean the activity is being destroyed. It indicates onStop()
that the activity is no longer in the foreground, but it is
still visible if the user is in multi-window mode.
onStop() When your activity is no longer visible to the user, it Yes onRestart()
enters the Stopped state, and the system invokes the or
onStop() callback. This can occur when a newly onDestroy()
launched activity covers the entire screen. The system
also calls onStop() when the activity finishes running
and is about to be terminated.
From the Stopped state, the activity either comes back to
interact with the user, or the activity is finished running
and goes away. If the activity comes back, the system
invokes onRestart(). If the Activity is finished running,
the system calls onDestroy().
onDestroy() onDestroy() is called before the activity is destroyed. Yes Nothing
The system invokes this callback for one of two reasons:
1. The activity is finishing, due to the user
completely dismissing the activity or due to
finish() being called on the activity.
2. The system is temporarily destroying the activity
due to a configuration change, such as device
rotation or entering multi-window mode.

In the table column “Killable after?” shows that system can kill the Activity after execution of
specified method in the row. There are three call-back methods of an Activity’s lifecycle after that
an Activity can be killed: onPause(), onStop() and onDestroy(). In the shortage of memory, the
Android runtime system can kill the Activity in the paused state without calling the onStop() and
onDestroy() methods.
Following skeleton code is showing each basic call-back method of Activity:
package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(MainActivity.this, "onCreate() is called.", Toast.LENGTH_SHORT).show();
Log.i("Main Activity", "onCreate() is called.");
}
protected void onStart() {
super.onStart();
Toast.makeText(MainActivity.this, "onStart() is called.", Toast.LENGTH_SHORT).show();
Log.i("Main Activity", "onStart() is called.");
}
protected void onRestart() {
super.onRestart();
Toast.makeText(MainActivity.this, "onRestart() is called.", Toast.LENGTH_SHORT).show();
Log.i("Main Activity", "onRestart() is called.");
}
protected void onResume() {
super.onResume();
Toast.makeText(MainActivity.this, "onResume() is called.", Toast.LENGTH_SHORT).show();
Log.i("Main Activity", "onResume() is called.");
}
protected void onPause() {
super.onPause();
Toast.makeText(MainActivity.this, "onPause() is called.", Toast.LENGTH_SHORT).show();
Log.i("Main Activity", "onPause() is called.");
}
protected void onStop() {
super.onStop();
Toast.makeText(MainActivity.this, "onStop() is called.", Toast.LENGTH_SHORT).show();
Log.i("Main Activity", "onStop() is called.");
}
protected void onDestroy() {
super.onDestroy();
Toast.makeText(MainActivity.this, "onDestroy() is called.", Toast.LENGTH_SHORT).show();
Log.i("Main Activity", "onDestroy() is called.");
}
}
MainActivity.java
When you will run the above-mentioned code, a corresponding toast message will be displayed
on the screen whenever a call-back method will be called. By executing this code, you can make
an idea in your mind about the order of execution of the methods. For example, whenever you will
start the application, on the execution of call-back methods onCreate(), onStart() and onResume(),
three consecutive toast message will be showing on the screen respectively. And when you will
close the application when it is running, three consecutive toast message will be showing on the
screen respectively, on the execution of call-back methods onPause(), onStop() and onDestroy().
Type of the toast messages will be depending on your actions with the application.
Saving the state of the Activity: Whenever an Activity resumes after calling the onStop()
methods, the Activity retains its previous state. This is true but question is - how does it happen?
This happens as the object of the Activity pushed into the stack when onStop() method is called.
On the calling of onResume() method this object pops up from the stack and retains its position.
How can Android system save the state of the Activity if the Activity destroyed using onDetsroy()
method? This happens because Android can preserve the state of the Activity in an object of
Bundle class by calling the onSaveInstanceState() method before calling the onDestroy() method.
You can save the information of state in the Bundle class object as name-value pairs, using
methods like putInt() and putString(). After destroying the Activity by system if the user navigate
back the Activity, then the system get the information by calling the onCreate() method or
onRestoreInstanceState() method. These methods take the previously stored object of Bundle class
as an argument to recover the state information. In cases where Activity is created first time, the
Bundle class object has null value because there is no stored information about state. Figure 4.3 is
showing the whole mechanism of preserving and recovering the state information.

Figure 4.3: Saving the Activity state by using onSaveInstanceState() method


(Source: http://developer.android.com/guide/components/activities.html

You might also like