Topic 5: Android Building Blocks -I : Activity
📖 10 min read · 🎯 beginner · 🧭 Prerequisites: operators-in-java, abstraction-in-java
Why this matters
Every Android app you've ever used — WhatsApp, YouTube, your bank app — opens with a screen. You tap the icon, something appears, you interact with it, you move to another screen. Each one of those screens is what Android calls an Activity. Before you can build notifications, databases, or background services, you need to understand this fundamental piece — the room your user walks into first. If you skip this, nothing else makes sense. So let's start here, at the front door of every Android app you'll ever build.
What You'll Learn
- What an Activity is and how it fits into an Android application
- The complete Activity lifecycle and when each callback fires
- How to create an Activity with a layout, a Java class, and a Manifest entry
- How to navigate between two Activities using
Intent - How to pass data from one Activity to another via Intent extras
The Analogy
Think of an Android app as a multi-room museum. Each room is an Activity — it has its own décor (layout XML), its own staff (the Java class handling logic), and its own entrance on the museum map (the Manifest declaration). A visitor (the user) walks through an entrance, explores the room, and can follow a sign (an Intent) that leads them to the next room. The museum's security system (the Android OS) tracks which rooms are open, which are temporarily closed for cleaning (paused), and which have been shut down entirely (destroyed) — and that tracking system is the Activity lifecycle.
Chapter 1: Overview of Activities
An Activity represents a single screen with a user interface. Android applications are typically composed of multiple activities that work together to deliver a cohesive user experience. Each Activity is independent and interacts with the user to perform specific tasks.
Three foundational concepts underpin every Activity:
- Lifecycle — Activities move through well-defined states: created, started, resumed, paused, stopped, and destroyed. Each transition triggers a callback method you can override.
- Intents — Activities are started via
Intentobjects, the messaging mechanism that lets different components of an application communicate and pass data to one another. - Layouts — Activities define their UI using XML layout files stored in
res/layout/. These files describe the arrangement and properties of every UI element on screen.
flowchart LR
A[Intent fired] --> B[Activity Created]
B --> C[Activity Started]
C --> D[Activity Resumed\n— user sees it]
D --> E[Activity Paused\n— partial cover]
E --> F[Activity Stopped\n— not visible]
F --> G[Activity Destroyed]
F --> H[Activity Restarted]
H --> C
Chapter 2: Activity Lifecycle
Understanding the Activity lifecycle is crucial for managing resources and delivering a smooth user experience. The Android OS calls these lifecycle methods automatically as the Activity's state changes:
| Method | When it fires |
|---|---|
onCreate() | First creation — initialize the activity here (inflate layout, bind views, set listeners) |
onStart() | Activity becomes visible to the user |
onResume() | Activity starts interacting with the user (foreground, has focus) |
onPause() | Activity is partially obscured by another activity (loses focus but may still be visible) |
onStop() | Activity is no longer visible to the user |
onDestroy() | Called just before the activity is destroyed (cleanup resources) |
onRestart() | Called after the activity has been stopped and is about to start again |
Each method is a hook. You override only the ones your Activity needs — but onCreate() is required on every Activity because that is where you call setContentView() to attach a layout.
Chapter 3: Creating a Simple Activity
Building an Activity requires three coordinated files: the layout XML, the Java class, and the Manifest entry. Let's build one that displays a message when a button is tapped.
Step 1: Define the Activity Layout
res/layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textSize="24sp" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
</LinearLayout>
Step 2: Create the Activity Class
MainActivity.java
package com.example.myapp;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textView.setText("Button Clicked!");
}
});
}
}
setContentView(R.layout.activity_main) inflates the XML layout and attaches it to this Activity. findViewById() looks up a view by the android:id you defined in XML and returns a typed reference you can interact with in Java.
Step 3: Register the Activity in the Manifest
Every Activity must be declared in AndroidManifest.xml. The <intent-filter> below marks MainActivity as the app's launch entry point.
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<application
android:allowBackup="true"
android:label="@string/app_name"
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>
</manifest>
Chapter 4: Starting Another Activity
You start a new Activity by creating an Intent that names the destination class and passing it to startActivity(). Let's add a second screen to our app.
Step 1: Create the Second Activity Layout
res/layout/activity_second.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to the Second Activity!"
android:textSize="24sp" />
</LinearLayout>
Step 2: Create the Second Activity Class
SecondActivity.java
package com.example.myapp;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
}
Step 3: Register the Second Activity in the Manifest
<application
...>
...
<activity android:name=".SecondActivity"></activity>
</application>
Step 4: Add Navigation from MainActivity
Update the layout to include a second button, then wire up the Intent in the Java class.
Updated res/layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textSize="24sp" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
<Button
android:id="@+id/navigate_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to Second Activity" />
</LinearLayout>
Updated MainActivity.java
package com.example.myapp;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private Button button;
private Button navigateButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
button = findViewById(R.id.button);
navigateButton = findViewById(R.id.navigate_button);
button.setOnClickListener(v -> textView.setText("Button Clicked!"));
navigateButton.setOnClickListener(v -> {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
});
}
}
new Intent(MainActivity.this, SecondActivity.class) is an explicit Intent — you name the exact destination class. The OS creates that Activity and pushes it onto the back stack.
Chapter 5: Passing Data Between Activities
Intents can carry data through extras — key-value pairs attached with putExtra() and retrieved with the matching get*Extra() method on the receiving end.
Step 1: Send Data from MainActivity
MainActivity.java — only the relevant listener changes:
navigateButton.setOnClickListener(v -> {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("EXTRA_MESSAGE", "Hello from MainActivity!");
startActivity(intent);
});
"EXTRA_MESSAGE" is the key — a plain String constant you and the receiving Activity agree on. The value can be a String, primitive, Parcelable, Serializable, or Bundle.
Step 2: Receive Data in SecondActivity
Updated SecondActivity.java
package com.example.myapp;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
TextView textView = findViewById(R.id.textView);
String message = getIntent().getStringExtra("EXTRA_MESSAGE");
textView.setText(message);
}
}
getIntent() returns the Intent that launched this Activity. getStringExtra("EXTRA_MESSAGE") retrieves the value by the same key used in putExtra. If the key is absent, getStringExtra returns null, so guard against that in production code.
Make sure the activity_second.xml layout gives textView an id so SecondActivity can find it:
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to the Second Activity!"
android:textSize="24sp" />
🧪 Try It Yourself
Task: Build a two-screen app where the user types their name into an EditText on the first screen, taps "Greet Me", and the second screen displays "Hello, [name]! Welcome to Vizag."
Success criterion: Tapping the button navigates to the second screen and shows the personalized greeting using the name the user typed.
Starter snippet — add to activity_main.xml before the Button:
<EditText
android:id="@+id/nameInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your name"
android:inputType="textPersonName" />
Then in MainActivity.java, read the input with:
String name = nameInput.getText().toString();
intent.putExtra("EXTRA_NAME", name);
And in SecondActivity.java, build the greeting:
String name = getIntent().getStringExtra("EXTRA_NAME");
textView.setText("Hello, " + name + "! Welcome to Vizag.");
🔍 Checkpoint Quiz
Q1. What is the correct order of lifecycle methods called when a user opens an Activity for the first time?
A) onResume() → onStart() → onCreate()
B) onCreate() → onStart() → onResume()
C) onCreate() → onResume() → onStart()
D) onStart() → onCreate() → onResume()
Q2. What does this code do?
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("EXTRA_MESSAGE", "Hello!");
startActivity(intent);
A) Sends an SMS message to SecondActivity
B) Navigates to SecondActivity and passes the String "Hello!" under the key "EXTRA_MESSAGE"
C) Broadcasts "Hello!" to all activities in the app
D) Creates SecondActivity but does not start it until finish() is called
Q3. Given this snippet in SecondActivity.onCreate(), what will textView display if no extra was passed?
String message = getIntent().getStringExtra("EXTRA_MESSAGE");
textView.setText(message);
A) An empty string ""
B) The string "null"
C) A blank screen (the app crashes)
D) null is passed to setText(), which may throw a NullPointerException depending on the view implementation
Q4. You are building an Activity that plays a video. In which lifecycle method should you pause the video playback so it stops when another app comes to the foreground?
A) onStop()
B) onDestroy()
C) onPause()
D) onCreate()
A1. B — Android always calls onCreate() first (initialization), then onStart() (visible), then onResume() (interactive).
A2. B — new Intent(src, dst) is an explicit Intent pointing to SecondActivity; putExtra attaches the key-value pair; startActivity fires the navigation.
A3. D — getStringExtra() returns null when the key is absent. Passing null to TextView.setText() throws a NullPointerException. Always null-check or provide a default value.
A4. C — onPause() is the earliest callback guaranteed to fire before the activity loses focus, making it the right place to pause playback so the user doesn't hear audio from a hidden screen.
🪞 Recap
- An Activity is a single screen with a user interface, and every Android app is built from one or more Activities.
- The Activity lifecycle (
onCreate→onStart→onResume→onPause→onStop→onDestroy) gives you precise hooks to manage resources as the OS suspends or destroys your screen. - Every Activity needs three things: an XML layout in
res/layout/, a Java class extendingAppCompatActivity, and a<activity>declaration inAndroidManifest.xml. - Navigation between Activities is done with an explicit
Intentpointing to the destination class, fired viastartActivity(). - Data travels between Activities as Intent extras: attach with
putExtra(key, value)on the sender; retrieve withget*Extra(key)on the receiver.
📚 Further Reading
- Android Activity documentation — the source of truth on Activity concepts and lifecycle
- Android Activity Lifecycle deep-dive — detailed per-state guidance with diagrams
- Intents and Intent Filters — everything about explicit vs. implicit Intents and passing data
- ⬅️ Previous: Abstraction in Java
- ➡️ Next: Android Building Blocks II: Services