0% found this document useful (0 votes)
18 views15 pages

Android Programming UNIT 2

The document outlines key components of Android applications, including Activities, Services, Content Providers, and Broadcast Receivers, detailing their roles and lifecycle methods. It explains the Activity lifecycle, emphasizing the importance of managing app resources and user interactions efficiently. Additionally, it covers Intents for communication between components, including explicit and implicit intents, and provides a guide for creating an application that switches between activities.

Uploaded by

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

Android Programming UNIT 2

The document outlines key components of Android applications, including Activities, Services, Content Providers, and Broadcast Receivers, detailing their roles and lifecycle methods. It explains the Activity lifecycle, emphasizing the importance of managing app resources and user interactions efficiently. Additionally, it covers Intents for communication between components, including explicit and implicit intents, and provides a guide for creating an application that switches between activities.

Uploaded by

Shaik Javeed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

CM-503 Android Programming

UNIT 2
COMPONENTS, ACTIVITY LIFE CYCLE, INTENTS

2.1 Android Application Components


Android apps are made up of four main components. Each plays a specific
role in how the app functions, interacts with users, or connects with the
system and other apps.
2.1.1 Activities (User Interface)
🔹 What is an Activity?
 An Activity is a single screen with a user interface.
 Every app must have at least one Activity.
 It’s like a window in a desktop application.
🔸 Life Cycle of an Activity:
Activities have a lifecycle managed by the Android system:
Method When it is called
onCreate(
When the activity is first created
)
onStart() When the activity becomes visible
onResum When the activity starts interacting
e() with user
When the activity goes into
onPause()
background partially
onStop() When the activity is no longer visible
onDestro
When the activity is destroyed
y()
Example Use Cases:
 LoginActivity: To take user credentials
 MainActivity: To show app content
 SettingsActivity: To change app preferences
Manifest Declaration:
<activity android:name=".MainActivity" />

2.1.2 Services (Background Work)


🔹 What is a Service?
 A Service performs background operations without providing a user
interface.
 Used when you want an operation to continue even if the app is closed.
🔸 Types of Services:

MJR COLLEGE OF ENGINEERING AND TECHNOLOGY BY SHAIK JAVEED


CM-503 Android Programming

Type Description
Started Starts using startService() and runs in
Service background
Bound Binds with other components and
Service provides data
Foreground Shows notification and keeps running
Service actively
🧩 Example Use Cases:
 Music player running in background
 Uploading images in background
 Location tracking app
Manifest Declaration:
<service android:name=".MyService" />

✅ 2.1.3 Content Providers (Data Sharing)


🔹 What is a Content Provider?
 Allows data sharing between different applications.
 Provides read/write access to private app data.
🔸 Use of Content URIs:
URIs identify the data to operate on.
Example:
Uri uri = [Link].CONTENT_URI;
🔸 Important Methods:
Metho
Purpose
d
query(
Read data
)
insert() Add data
update Modify existing
() data
delete(
Remove data
)
🧩 Example Use Cases:
 Reading phone contacts
 Accessing image gallery
 Syncing data across apps
Manifest Declaration:
<provider
android:name=".MyContentProvider"
android:authorities="[Link]"
android:exported="true" />

MJR COLLEGE OF ENGINEERING AND TECHNOLOGY BY SHAIK JAVEED


CM-503 Android Programming

2.1.4 Broadcast Receivers (System Message Listener)


🔹 What is a BroadcastReceiver?
 It responds to system-wide broadcast events.
 Acts like a listener waiting for system or app events.
🔸 Two Types:
Type Registered In When Used
AndroidManifest. For system events
Static
xml (boot)
Dynam Java code at For app-specific
ic runtime events
🧩 Example Use Cases:
 Low battery alert
 Alarm or notification trigger
 Airplane mode ON/OFF detection
Manifest Declaration:
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="[Link].BOOT_COMPLETED"/>
</intent-filter>
</receiver>

✅ Summary of Android Application Components


User
Component Description Used For
Interface
Represents app
Activity ✅ UI logic and interaction
screen
Performs background
Service ❌ Audio playback, downloads
tasks
ContentProvi Shares app data Contacts, gallery, file

der securely sharing
Listens to
BroadcastRec Battery, boot, SMS received,
system/app ❌
eiver airplane mode
messages

Android Activity Lifecycle


Activity Lifecycle in Android
What is an Activity?
 An Activity is a single screen in an Android app that allows the user to
interact with the app.
 It is the entry point for user interaction.

MJR COLLEGE OF ENGINEERING AND TECHNOLOGY BY SHAIK JAVEED


CM-503 Android Programming

 Example: Login screen, Home screen, Settings screen—all are


activities.

What is the Activity Lifecycle?


 The Activity Lifecycle is the set of states an activity goes through
from creation to destruction.
 The Android system calls specific lifecycle methods at each stage
to manage the activity's behavior.

Lifecycle Methods and Their Purpose


Method Description
onCreate( Called when the activity is first created. Used to set up UI and
) initialize variables.
onStart() Called when the activity becomes visible to the user.
onResum
Called when the activity is ready for user interaction.
e()
Called when the activity is partially hidden (e.g., another
onPause()
activity pops up).
onStop() Called when the activity is completely hidden.
onRestart Called if the activity is coming back to the foreground after
() being stopped.
onDestro Called before the activity is destroyed, either by the user or
y() system.

Example Usage of Each Method:


Method Use Case Example
onCreate( Load UI from XML layout, initialize
) views
Start animations, connect to data
onStart()
sources
onResum Resume paused tasks, restart
e() music/video
Pause ongoing tasks, save
onPause()
unsaved data
Release heavy resources,
onStop()
disconnect APIs
onRestart Re-initialize components before
() resuming
onDestro Final clean-up before activity is
y() closed

MJR COLLEGE OF ENGINEERING AND TECHNOLOGY BY SHAIK JAVEED


CM-503 Android Programming

🎯 Importance of Activity Lifecycle:


 Helps manage app resources efficiently.
 Prevents memory leaks and crashes.
 Ensures better performance and user experience.
 Essential for handling interruptions like incoming calls, app switching,
etc.

Activity Lifecycle in Android – Flow Explanation (Image-Based)

MJR COLLEGE OF ENGINEERING AND TECHNOLOGY BY SHAIK JAVEED


CM-503 Android Programming

This flowchart shows how an Activity behaves from launch to shutdown with
all lifecycle methods and possible transitions based on system/user actions.

1. Activity Launched
 When a user opens an app or navigates to a new screen (activity), the
lifecycle begins.
 Three methods are called in sequence:
onCreate()
 Called first when the activity is created.
 Used for:
o Initializing components
o Loading the UI (via setContentView())
o Setting up variables and listeners.
onStart()
 Called after onCreate().
 The activity is now visible to the user but not interactive.
onResume()
 Called after onStart().
 Now the activity is interactive and in the foreground.
 This is where animations, video/audio playback, and user input begin.
At this stage, the activity is in the “Running” state.

2. User Interaction and System Events


onPause()
 Called when:
o A new activity partially covers the current one.
o The system needs to temporarily shift focus.
 The activity is still partially visible, but not focused.
 Save minimal state (e.g., pause video).

onStop()
 Called when:
o The activity is completely hidden (not visible).
o The user navigates away or starts another full-screen activity.
 Stop resource-heavy operations like animations, sensors, etc.

3. Returning to the Activity


onRestart()
 Called if the user returns to the activity after onStop().
 Followed by onStart() and then onResume() again.
 The activity is revived and brought to the foreground.

4. Activity is Destroyed

MJR COLLEGE OF ENGINEERING AND TECHNOLOGY BY SHAIK JAVEED


CM-503 Android Programming

onDestroy()
 Called when:
o The user closes the activity.
o The system destroys the activity to free up memory.
 Final clean-up is done here (like closing DB, stopping threads).

5. App Process Killed


 If memory is very low, the system may kill the app process.
 Next time user navigates back, onCreate() will be called again from
scratch.

Summary of Flow Transitions:


Event/Action Lifecycle Callback
Launch activity onCreate() → onStart() → onResume()
New activity opens on top onPause()
Activity completely hidden onStop()
User returns to activity onRestart() → onStart() → onResume()
User or system closes
onPause() → onStop() → onDestroy()
activity
System kills process (low App is destroyed without calling
memory) lifecycle methods

Demo Android App to Demonstrate Activity Lifecycle in Android

import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
Toast toast = [Link](getApplicationContext(), "onCreate
Called", Toast.LENGTH_LONG).show();
}

protected void onStart() {


[Link]();
Toast toast = [Link](getApplicationContext(), "onStart
Called", Toast.LENGTH_LONG).show();
}

MJR COLLEGE OF ENGINEERING AND TECHNOLOGY BY SHAIK JAVEED


CM-503 Android Programming

@Override
protected void onRestart() {
[Link]();
Toast toast = [Link](getApplicationContext(), "onRestart
Called", Toast.LENGTH_LONG).show();
}

protected void onPause() {


[Link]();
Toast toast = [Link](getApplicationContext(), "onPause
Called", Toast.LENGTH_LONG).show();
}

protected void onResume() {


[Link]();
Toast toast = [Link](getApplicationContext(), "onResume
Called", Toast.LENGTH_LONG).show();
}

protected void onStop() {


[Link]();
Toast toast = [Link](getApplicationContext(), "onStop Called",
Toast.LENGTH_LONG).show();
}

protected void onDestroy() {


[Link]();
Toast toast = [Link](getApplicationContext(), "onDestroy
Called", Toast.LENGTH_LONG).show();
}
}

2.3 & 2.4 INTENTS in Android


2.3 Define Intents
An Intent is a fundamental building block in Android for communication
between components. Definition:
An Intent is an abstract description of an operation to be performed. It
allows an app to request an action from another app component (e.g.,
launching an activity, sending data, opening a web page, etc.).

MJR COLLEGE OF ENGINEERING AND TECHNOLOGY BY SHAIK JAVEED


CM-503 Android Programming

Key Characteristics of Intents:


 Enables component communication within and across apps.
 Can carry data from one component to another.
 Intents are used with:
o Activities (to start/stop or switch screens)
o Services (to start background operations)
o Broadcast receivers (to deliver system-wide messages)

2.4 INTENTS
Role of Intents in Android:
Intents act as messengers in the Android system. They help connect
components like:
 Activity to Activity
 Activity to Service
 App to external app (like Camera, Contacts, Browser)
 Broadcasting messages to the system or apps

2.4.1 Exploring Intent Objects (with fields)


The Intent class is a Java object that contains:

Field Purpose Example

Intent.ACTION_VIEW,
Action Defines what to do
ACTION_SEND

Data URI data to act upon "content://contacts/1"

Extras Key-value data to send putExtra("key", "value")

Compon The target activity or


[Link]
ent service

Categor Info about the kind of


Intent.CATEGORY_LAUNCHER
y component

Flags Controls how activity is FLAG_ACTIVITY_NEW_TASK

MJR COLLEGE OF ENGINEERING AND TECHNOLOGY BY SHAIK JAVEED


CM-503 Android Programming

Field Purpose Example

launched

Constructor Example:
Intent intent = new Intent(context, [Link]);
[Link]("Name", "Javeed");

2.4.2 Types of Intents


1. Explicit Intents
 Target is known (you specify the class name).
 Used within the same app.
Intent i = new Intent(this, [Link]);
startActivity(i);
2. Implicit Intents
 No specific class is mentioned.
 Android searches apps/components that can handle the request.
Intent i = new Intent(Intent.ACTION_VIEW);
[Link]([Link]("[Link]
startActivity(i);

Intent
When to Use Example
Type

Start another screen in same Intent(this,


Explicit
app [Link])

Ask system to choose Open camera, share text,


Implicit
appropriate app view URL

2.4.3 Linking Activities Using Intents


Why link activities?
 To move from one screen to another (like Login → Dashboard).
 To pass data from one activity to another.

MJR COLLEGE OF ENGINEERING AND TECHNOLOGY BY SHAIK JAVEED


CM-503 Android Programming

Example 1: Simple Activity Switch


In [Link]
Intent intent = new Intent([Link], [Link]);
startActivity(intent);
In [Link]
<activity android:name=".SecondActivity"/>

Example 2: Passing Data Between Activities


🔹 Sending:
Intent intent = new Intent(this, [Link]);
[Link]("username", "Javeed");
startActivity(intent);
🔹 Receiving:
Intent intent = getIntent();
String name = [Link]("username");
[Link]("Welcome, " + name);

Example 3: Calling System Apps with Implicit Intents

Purpos
Intent
e

Dialer Intent(Intent.ACTION_DIAL, [Link]("[Link]

Intent(Intent.ACTION_SENDTO,
SMS
[Link]("smsto:123456789"))

Intent(Intent.ACTION_SENDTO,
Email
[Link]("[Link]

Web Intent(Intent.ACTION_VIEW,
Page [Link]("[Link]

Summary Table:

MJR COLLEGE OF ENGINEERING AND TECHNOLOGY BY SHAIK JAVEED


CM-503 Android Programming

Intent
Details
Feature

Used for Starting Activities, Services, Broadcasts

Types Explicit & Implicit

Contains Action, Data, Extras, Component

Real Use Moving between screens, Sending emails,


Cases Opening camera

2.5 Creation of Android Application That Switches


Between Activities
This topic demonstrates how to navigate between two screens
(Activities) using Explicit Intents in Android. It’s one of the fundamental
features every Android app uses for screen-to-screen communication.

Objective:
Create an Android application with two activities, where the user can
move from the MainActivity to SecondActivity, and optionally return.
Steps to Create the Application
🔹 Step 1: Create a New Project
1. Open Android Studio
2. Click "New Project"
3. Choose Empty Activity
4. Name it SwitchActivityApp
5. Finish
Android Studio automatically creates [Link] or [Link] with
activity_main.xml.
🔹 Step 2: Add SecondActivity
1. Right-click on java > [Link]
2. Select: New > Activity > Empty Activity

MJR COLLEGE OF ENGINEERING AND TECHNOLOGY BY SHAIK JAVEED


CM-503 Android Programming

3. Name it: SecondActivity


4. Click Finish
This adds:
 [Link] (or .kt)
 activity_second.xml
 Registers it in [Link]
🔹 Step 3: Design Layout for Both Activities
activity_main.xml
<LinearLayout xmlns:android="[Link]
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:gravity="center">

<Button
android:id="@+id/buttonSwitch"
android:text="Go to Second Activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
activity_second.xml
<LinearLayout xmlns:android="[Link]
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:gravity="center">

<TextView
android:text="Welcome to Second Activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>

MJR COLLEGE OF ENGINEERING AND TECHNOLOGY BY SHAIK JAVEED


CM-503 Android Programming

🔹 Step 4: Code in [Link]


public class MainActivity extends AppCompatActivity {

Button buttonSwitch;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

buttonSwitch = findViewById([Link]);

[Link](new [Link]() {
@Override
public void onClick(View view) {
Intent intent = new Intent([Link], [Link]);
startActivity(intent);
}
});
}
}

🔹 Step 5: [Link] (Auto-added but verify)


<activity android:name=".SecondActivity" />

🔹 Step 6: Run the App


 Click Run ▶️in Android Studio

MJR COLLEGE OF ENGINEERING AND TECHNOLOGY BY SHAIK JAVEED


CM-503 Android Programming

 App opens with a button: "Go to Second Activity"


 Click it → Navigates to the SecondActivity

Optional: Add "Back to MainActivity" in SecondActivity


activity_second.xml (Add button):
<Button
android:id="@+id/buttonBack"
android:text="Go Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
[Link]
Button buttonBack = findViewById([Link]);
[Link](v -> finish()); // Closes current activity

Summary

Concept Description

Used to start another


Intent
Activity

Explicit Specifies the class to be


Intent opened

Activity Each screen in Android

Manifest Declares all components

MJR COLLEGE OF ENGINEERING AND TECHNOLOGY BY SHAIK JAVEED

You might also like