Android Application Design Essentials
Anatomy of an Android Application
An Android application consists of several key components that work together to create a
functional mobile app. These components include Activities, Intents, Services, and Content
Providers.
1. Activities
An Activity represents a single screen in an Android application where users interact. It
serves as the UI layer of the app and handles user interactions. Every Android app must
have at least one activity, known as the Main Activity.
Key Features of Activities:
Each screen in an app is an Activity.
Activities must be declared in the AndroidManifest.xml file.
The onCreate() method initializes the activity when it is created.
Activities follow a lifecycle managed by Android, including:
● Created – Activity is first created.
● Started – Activity becomes visible.
● Resumed – Activity is in focus and interactive.
● Paused – Activity is partially visible (another activity is on top).
● Stopped – Activity is no longer visible.
● Destroyed – Activity is closed and removed from memory.
Activities can switch between each other using Intents.
Example:
In WhatsApp:
● The chat list screen is an Activity.
● Opening a chat window is another Activity.
● The calls screen is also a separate Activity.
When developing an Android app, you can either use the automatically created
MainActivity.java or create additional activities when needed.
Creating an Activity in Android Studio
When developing an Android app, we can either use the automatically created
MainActivity.java or create additional activities when needed.
1. Using MainActivity.java (Default Activity)
When we create a new Android project and choose Basic Activity, Android Studio
automatically creates:
● MainActivity.java (Main screen of the app)
● activity_main.xml (Layout file for the main screen)
Steps to Use MainActivity (Already Created)
1. Open Android Studio and create a new project.
2. Select Basic Activity (or Empty Activity).
3. MainActivity.java and activity_main.xml will be automatically generated.
4. we can design the UI in activity_main.xml and write logic in MainActivity.java.
5. Run the app to test screen.
If our app has only one screen, we do NOT need extra activities.
2. Creating a New Activity (When we Need More Screens)
If our app has multiple screens, we must create new activities.
Steps to Create a New Activity
1. Right-click on y package name (inside app > java > com.example.yourapp).
2. Click New > Activity > Empty Activity.
3. Enter the Activity Name (e.g., SecondActivity).
4. Click Finish—this creates:
o SecondActivity.java (Java file for the new screen).
o activity_second.xml (Layout file for the new screen).
5. Open AndroidManifest.xml and confirm that the new activity is automatically added
inside the <application> tag:
basic code for MainActivity.java, which is automatically created when selecting a Basic
Activity in Android Studio
Intent
An Intent is a messaging object used to communicate between different components of an
Android application. It is mainly used for navigating between activities, services, and
broadcast receivers.
Types of Intents
Intents are categorized into two types:
1. Explicit Intent
● Used when we know the target component (Activity, Service, etc.).
● Example: Navigating from one activity to another within the same app.
2. Implicit Intent
● Used when we do not specify the target component.
● The system decides which app or service can handle the request.
● Example: Opening a website, sharing an image, or making a phone call.
Uses of Intents in Android
Starting a new activity – Open a new screen in the app.
Passing data between activities – Send data from one activity to another.
Starting a service – Run a background task.
Broadcasting messages – Notify other apps or system events.
Services
A Service in Android is a background component that performs long-running operations
without a user interface. It runs even when the user switches to another app, making it
useful for tasks that don't require direct user interaction.
Types of Services in Android
1. Foreground Service
● Runs in the background but is visible to the user.
● Shows a notification (e.g., music player, ongoing call).
● Example: Playing music in Spotify while using other apps.
2. Background Service
● Runs in the background without user interaction.
● Used for tasks like downloading files, syncing data.
● Example: WhatsApp automatically syncing messages.
3. Bound Service
● Allows components (like activities) to bind to it.
● Stops when the component unbinds.
● Example: Google Assistant when interacting with voice commands.
Uses of Services
Playing music in the background
Fetching location updates
Uploading files to a server
Running scheduled tasks like notifications
Content Providers in Android
A Content Provider is a component in Android that manages shared access to an app's data.
It allows different applications to read, write, and modify data securely, even if they belong
to different apps.
Data Sharing → Enables apps to share data with other apps securely.
Data Abstraction → Hides direct database access and provides a structured interface.
Centralized Data Management → Useful for managing data across multiple apps.
Contacts App → Other apps can access contacts using the ContactsProvider.
Gallery App → Apps like Instagram or WhatsApp can fetch images from the gallery.
Messaging App → SMS apps can read messages using SmsProvider.
Uses of a Content Provider
When our app needs to share data with other apps.
When our app needs to manage structured data in an SQLite database.
When we need to access system data like contacts, messages, or media files.
Content Providers
A Content Provider is a component in Android that allows applications to share and manage
data securely. It provides controlled access to app data, enabling other apps to read, write,
and modify data without direct database access.
Features of Content Providers
1. Data Sharing → Enables apps to share data with other apps securely.
2. Data Abstraction → Hides direct database access and provides a structured
interface.
3. Centralized Data Management → Helps manage data across multiple apps
efficiently.
Examples of Content Providers in Android
Contacts App → Other apps can access contacts using the ContactsProvider.
Gallery App → Apps like Instagram or WhatsApp can fetch images from the gallery.
Messaging App → SMS apps can read messages using SmsProvider.
Uses of a Content Provider
1. When an app needs to share data with other apps.
2. When an app needs to store and manage structured data using an SQLite database.
3. When an app needs to access system data such as contacts, messages, or media
files.
Android Terminologies
Android development involves various key terminologies that are essential for
understanding how Android applications work. Below are some important Android
terminologies explained in detail:
1. Activity
An Activity represents a single screen in an Android application. It is responsible for user
interaction and UI display.
Each app has at least one activity (Main Activity).
Activities follow a lifecycle (Created, Started, Resumed, Paused, Stopped, Destroyed).
Switching between activities is done using Intents.
2. Intent
An Intent is a messaging object used to communicate between components (activities,
services, broadcast receivers, etc.).
Explicit Intent → Used to launch a specific activity within the same app.
Implicit Intent → Used to request actions from other apps (e.g., opening a web page or
sharing an image).
3. Services
A Service is a background component that runs without a user interface to perform long-
running tasks such as playing music, syncing data, or downloading files.
Foreground Service → Runs in the background but shows a notification (e.g., music player).
Background Service → Runs without user interaction (e.g., syncing data).
4. Content Provider
A Content Provider allows apps to share and access data in a structured way.
Used for accessing contacts, images, messages, and other system data.
Provides a standard API to read and write data securely.
5. Broadcast Receiver
A Broadcast Receiver listens for system-wide broadcast messages (e.g., battery low,
incoming call, network change).
Used for responding to system or app-specific events.
Example: Receiving an SMS notification.
6. SharedPreferences
SharedPreferences is a lightweight storage option for saving key-value pairs. It is used for
storing small amounts of persistent data like user settings.
Example: Saving a user’s login state or app preferences.
7. RecyclerView
A RecyclerView is an advanced, flexible UI component for displaying large lists or grids
efficiently.
Reuses list items instead of creating new ones, improving performance.
Supports multiple layouts like List, Grid, and Staggered Grid.
8. ViewModel
A ViewModel is a component of the MVVM (Model-View-ViewModel) architecture. It stores
and manages UI-related data in a lifecycle-aware way.
Prevents data loss when an activity is recreated due to configuration changes (e.g., screen
rotation).
9. WorkManager
WorkManager is a background task manager used for executing deferrable and guaranteed
tasks.
Used for scheduling tasks like file downloads, data syncing, and notifications.
10. AndroidManifest.xml
The AndroidManifest.xml file is a configuration file that defines the essential information
about the app.
Declares activities, permissions, services, broadcast receivers, and metadata.
Example: Declaring internet permissions for accessing the web.
11. Gradle
Gradle is a build automation tool used for compiling and managing dependencies in
Android projects.
It automates the build process and integrates external libraries easily.
12. APK (Android Package Kit)
An APK is the file format used to distribute and install Android applications.
Contains all app resources, code, and assets.
Example: app-release.apk is generated when the app is built for publishing.
Application Context
Context in Android refers to an interface that provides access to application-specific
resources and system services. It acts as a bridge between the application and the Android
operating system, enabling activities, services, and other components to interact with
system resources like databases, preferences, and system services.
Application Context
● It is tied to the entire application lifecycle.
● It remains active as long as the application is running.
● Used for accessing app-wide resources, shared preferences, and databases.
● Cannot be used for UI-related tasks like inflating layouts.
● Obtained using getApplicationContext().
Activity Context
● It is tied to the lifecycle of an activity.
● Used for UI-related operations like inflating layouts and launching activities.
● Can cause memory leaks if passed to long-lived objects.
● Obtained using this inside an activity.
Application Context refers to the global context of the application lifecycle. It is associated
with the application's environment and can be used when an object or component needs a
context that lasts as long as the application is running.
Key Characteristics of Application Context:
1. Global Scope: It remains alive throughout the entire lifecycle of the application.
2. Independent of Activities: Unlike Activity Context, it is not tied to a specific activity
and does not change when an activity is destroyed or recreated.
3. Memory Efficient: Since it lasts as long as the app, it avoids unnecessary memory
leaks compared to Activity Context.
Uses of Application Context:
1. Accessing Resources: Used to access app-wide resources such as strings, themes,
and layouts.
2. Launching Services: Required for starting or binding to services.
3. Accessing Shared Preferences and Databases: Used for storing and retrieving data in
SharedPreferences or SQLite databases.
4. Registering Broadcast Receivers: Useful for dynamically registering broadcast
receivers.
5. Handling Application Lifecycle Events: Helps in managing background tasks that
need to persist beyond an activity's lifecycle.
How to Get Application Context
From an Activity:
Context appContext = getApplicationContext();
From a Class without Context Reference:
You can pass the context from an activity or use a custom application class:
public class MyApp extends Application {
private static Context appContext;
@Override
public void onCreate() {
super.onCreate();
appContext = this;
public static Context getAppContext() {
return appContext;
Then, use MyApp.getAppContext() anywhere in the app.
Difference Between Application Context and Activity Context
Feature Application Context Activity Context
Scope Global (entire app) Tied to an activity
Exists only while the activity is
Lifecycle Lasts as long as the app
alive
Services, DB access, SharedPreferences, UI-related tasks like dialogs,
Use Case
Broadcast Receivers inflating layouts
Risk of Memory Higher if referenced
Lower
Leak incorrectly
Application Context is a powerful tool in Android that provides a global context for
resources, services, and background tasks. However, it should be used carefully, especially
when working with UI-related operations, as it does not have access to UI components.
Activities
An Activity in Android represents a single screen with a user interface (UI). It serves as an
entry point for user interactions with an app. Each application can have multiple activities,
and they work together to provide a seamless user experience.
An activity is a component of an Android app that provides a screen where users can
interact. It is a crucial part of the Android application lifecycle, managing the UI and
handling user inputs.
Each activity in an app is independent but can communicate with other activities to perform
different tasks.
Example:
● A login screen is one activity.
● A dashboard screen after login is another activity.
Activity Lifecycle
Each activity in Android follows a lifecycle that consists of several states:
Lifecycle Methods:
1. onCreate() – Called when the activity is first created. Used to initialize components.
2. onStart() – Called when the activity becomes visible to the user.
3. onResume() – Called when the user starts interacting with the activity.
4. onPause() – Called when the activity is partially visible but not in focus.
5. onStop() – Called when the activity is no longer visible.
6. onRestart() – Called when an activity is restarted after being stopped.
7. onDestroy() – Called before the activity is destroyed.
Creating an Activity in Android Studio
When developing an Android app, we can either use the automatically created
MainActivity.java or create additional activities when needed.
1. Using MainActivity.java (Default Activity)
When we create a new Android project and choose Basic Activity, Android Studio
automatically creates:
● MainActivity.java (Main screen of the app)
● activity_main.xml (Layout file for the main screen)
Steps to Use MainActivity (Already Created)
6. Open Android Studio and create a new project.
7. Select Basic Activity (or Empty Activity).
8. MainActivity.java and activity_main.xml will be automatically generated.
9. we can design the UI in activity_main.xml and write logic in MainActivity.java.
10. Run the app to test screen.
If our app has only one screen, we do NOT need extra activities.
2. Creating a New Activity (When we Need More Screens)
If our app has multiple screens, we must create new activities.
Steps to Create a New Activity
6. Right-click on y package name (inside app > java > com.example.yourapp).
7. Click New > Activity > Empty Activity.
8. Enter the Activity Name (e.g., SecondActivity).
9. Click Finish—this creates:
o SecondActivity.java (Java file for the new screen).
o activity_second.xml (Layout file for the new screen).
10. Open AndroidManifest.xml and confirm that the new activity is automatically added
inside the <application> tag:
basic code for MainActivity.java, which is automatically created when selecting a Basic
Activity in Android Studio:
MainActivity.java
package com.example.myapp;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the button in the layout
Button button = findViewById(R.id.button_next);
// Set a click listener for the button
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Navigate to SecondActivity when button is clicked
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
});
activity_main.xml (Layout File)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to Main Activity"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginBottom="20dp"/>
<Button
android:id="@+id/button_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to Second Activity"/>
</LinearLayout>
AndroidManifest.xml (Registering the Activity)
Android automatically adds MainActivity to the AndroidManifest.xml file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<application
android:allowBackup="true"
android:theme="@style/Theme.MyApp"
android:usesCleartextTraffic="true"
android:supportsRtl="true"
android:label="My App">
<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>
● MainActivity.java is the default entry point of the app.
● activity_main.xml defines the layout of the main screen.
● The Button navigates to SecondActivity using an Intent.
● The AndroidManifest.xml file ensures that MainActivity is the launch screen.
Service
In Android, Service is a crucial component that allows an application to perform background
tasks without a user interface. It runs in the background to handle tasks such as playing
music, downloading files, or syncing data.
Anatomy of Android Service
The Service component in Android follows a structured lifecycle and is divided into the
following parts:
1. Declaration in Manifest
Every service must be declared in the AndroidManifest.xml file using the
<service> tag.
Example: <service android:name=".MyService"/>
Creating a Service Class
o A service in Android is created by extending the Service class and overriding
necessary lifecycle methods.
Lifecycle of a Service
A service goes through different lifecycle stages:
Method Description
onCreate() Called when the service is first created.
onStartCommand() Called when a client starts the service.
onBind() Used when the service needs to interact with an activity.
onDestroy() Called when the service is destroyed.
Types of Services in Android
Android services are categorized into three types:
Foreground Service
▪ Runs in the foreground and shows a notification (e.g., music player).
▪ Example: Playing audio or tracking location.
Background Service
▪ Runs in the background without user interaction.
▪ Example: Syncing data, checking updates.
Bound Service
▪ Bound to a component (like an activity) and provides interaction.
▪ Example: Messenger service.
Starting and Stopping a Service
Start a service:
o Intent intent = new Intent(this, MyService.class);
o startService(intent);
Stop a service:
o stopService(intent);
Binding to a Service
o Bind a service (useful when interaction is needed between activity and
service):
o Intent intent = new Intent(this, MyService.class);
o bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
Example of a Simple Service
public class MyService extends Service {
@Override
public void onCreate() {
super.onCreate();
Log.d("MyService", "Service Created");
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService", "Service Started");
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyService", "Service Destroyed");
The Service component in Android is essential for running background tasks efficiently. By
managing its lifecycle properly, developers can ensure smooth operation without affecting
the app’s performance.
Intent
An Intent is a messaging object that allows communication between different components
of an application or even between applications. It is used to start activities, services, and
deliver broadcasts.
Types of Intents
There are two types of intents in Android:
1. Explicit Intent
● Used to start a specific component (Activity, Service, or BroadcastReceiver) within
the same application.
● Example: Starting a new activity.
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
2. Implicit Intent
● Used when the target component is not specified, allowing the system to determine
which application can handle the request.
● Example: Opening a web page.
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.google.com"));
startActivity(intent);
Components of an Intent
1. Action – Specifies the type of action to perform (e.g., Intent.ACTION_VIEW).
2. Data – URI data to act upon (e.g., Uri.parse("tel:1234567890")).
3. Category – Additional information about the type of component that should handle
the intent.
4. Extras – Key-value pairs to pass additional data.
5. Flags – Instructions on how the intent should be handled.
Common Intent Actions
Action Purpose
Intent.ACTION_VIEW Open a webpage or file
Intent.ACTION_DIAL Open the dialer with a phone number
Intent.ACTION_CALL Directly call a phone number (needs permission)
Intent.ACTION_SEND Share data like text, images, or files
Intent.ACTION_SENDTO Send an SMS or email
Example: Sending an Email
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "Hello, this is a test email.");
startActivity(Intent.createChooser(intent, "Send Email"));
Passing Data with Intent (Extras)
Sending Data
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("username", "JohnDoe");
startActivity(intent);
Receiving Data in Second Activity
String username = getIntent().getStringExtra("username");
Intent is a powerful mechanism in Android that enables navigation and data sharing
between components. Whether you use explicit or implicit intents depends on whether you
know the target component in advance.