Mobile Application Development
Module 2
I Anatomy of an Android Application
In Android Studio, an Android application is organized into the following main parts:
1. Manifests Folder
Contains [Link]
Defines application package name
Declares activities, services, receivers
Specifies permissions and launcher activity
2. Java Folder
Contains Java/Kotlin source files
Each Activity represents one screen
Handles application logic and user interaction
Example:
[Link]
[Link]
3. Res (Resources) Folder
Stores all non-code resources.
a) Layout
XML files for user interface design
Example: activity_main.xml
b) Drawable
Images, icons, shapes
c) Values
[Link] – text values
[Link] – color values
[Link] – themes and styles
Mobile Application Development
4. Gradle Scripts
Used for build configuration
Defines SDK versions and dependencies
5. APK File
Final output of the application
Contains code, resources, and manifest
Installed on Android devices
Diagram
Android Application
├── [Link]
├── Java/Kotlin Files
├── Resource Files
└── APK
II Android Terminologies
1. Android
An open-source mobile operating system developed by Google.
2. Activity
A single screen in an Android application.
3. Service
A component that runs in the background without a user interface.
4. Intent
A messaging object used to communicate between Android components.
5. Broadcast Receiver
A component that listens for system-wide or application-wide messages.
6. Content Provider
A component used to share data between different applications.
7. Context
Provides access to application resources and system services.
8. APK (Android Package Kit)
The file format used to install Android applications.
Mobile Application Development
9. View
A basic user interface element such as Button or TextView.
10. ViewGroup
A container that holds and arranges views.
11. Fragment
A reusable portion of an activity’s user interface.
12. Resources
Non-code files such as layouts, images, strings, and colors.
13. [Link]
A configuration file that declares app components and permissions.
14. SDK (Software Development Kit)
A collection of tools used to develop Android applications.
15. Gradle
Build system used to compile and package Android apps.
III Application Context
Application Context is a context that is tied to the lifecycle of the entire application. It provides
access to application-level resources, system services, and global information and remains
available as long as the application is running.
It represents the global environment of the application
It is not destroyed when an activity is destroyed
It is mainly used for components that need a context beyond an activity
It should not be used for UI-related operations
How to Get Application Context?
Context appContext = getApplicationContext();
Mobile Application Development
Application Context(5 Main Uses )
[Link]
Purpose: Show messages to the user.
Example:
Context context = getApplicationContext();
[Link](context, "Hello, I am a Toast", Toast.LENGTH_SHORT).show();
2. Resources
Purpose: Access app resources like strings, colors, dimensions.
Example:
String appName = getApplicationContext().getString([Link].app_name);
3. SharedPreferences
Purpose: Store small data persistently across app sessions.
Example:
SharedPreferences sp = getApplicationContext().getSharedPreferences("MyPrefs",
MODE_PRIVATE);
[Link]().putString("key", "value").apply();
Mobile Application Development
4. System Services
Purpose: Access Android system services (Connectivity, Location, etc.)
Example:
ConnectivityManager cm = (ConnectivityManager)
getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
5. Starting a Service
Purpose: Start background tasks that run independently of UI.
Example:
Intent intent = new Intent(getApplicationContext(), [Link]);
startService(intent);
Example:
[Link]
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="[Link]
xmlns:tools="[Link]
<!-- Add this line for internet connectivity check -->
<uses-permission android:name="[Link].ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/[Link]">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
Mobile Application Development
</activity>
</application>
</manifest>
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
Button btnTest = findViewById([Link]);
[Link](v -> {
// 1️ ⃣ Toast
[Link](getApplicationContext(), "Hello App Context!",
Toast.LENGTH_SHORT).show();
// 2️⃣ Resources
String appName = getApplicationContext().getString([Link].app_name);
[Link](getApplicationContext(), "App Name: " + appName,
Toast.LENGTH_SHORT).show();
// 3️⃣ SharedPreferences
SharedPreferences sp = getApplicationContext()
.getSharedPreferences("MyPrefs", MODE_PRIVATE);
[Link]().putString("key", "Hello Students").apply();
String savedValue = [Link]("key", "Not found");
[Link](getApplicationContext(), "SharedPreferences: " + savedValue,
Toast.LENGTH_SHORT).show();
Mobile Application Development
// 4️⃣ System Services (Internet Check)
boolean connected = false;
ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
if ([Link].SDK_INT >= Build.VERSION_CODES.M) {
Network nw = [Link]();
if (nw != null) {
NetworkCapabilities nc = [Link](nw);
connected = nc != null &&
[Link](NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
[Link](NetworkCapabilities.NET_CAPABILITY_VALIDATED);
}
} else {
// For older versions
[Link] ni = [Link]();
connected = ni != null && [Link]();
}
}
[Link](getApplicationContext(),
connected ? "Internet Connected" : "No Internet",
Toast.LENGTH_SHORT).show();
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="16dp">
<Button
android:id="@+id/btnTest"
android:layout_width="wrap_content"
Mobile Application Development
android:layout_height="wrap_content"
android:text="Test App Context" />
</LinearLayout>
IV Activities
Definition
An Activity is one screen in an Android application.
Similar to a single window in desktop applications.
An Android app may have one or more activities (screens).
Activity Stack
Android manages activities in a stack (back stack).
New activity is placed on top of the stack.
Previous activity remains below it.
Four Stages of an Activity
Active / Running:
Activity is in the foreground. User is interacting with it.
Paused:
Activity lost focus but is still partially visible (e.g., a transparent activity on top). Still
alive, not destroyed.
Stopped / Hidden:
Activity is completely hidden by another activity. Retains data, but may be killed if
memory is needed.
Destroyed:
Activity is removed from memory. When reopened, it must be recreated and restored.
Mobile Application Development
Activity Lifecycle Methods
Android provides 7 methods to manage transitions between stages:
onCreate(): Activity is created. Used to initialize UI and load data.
onStart(): Activity becomes visible. Prepares UI to be displayed.
onResume(): Activity comes to the foreground. Starts interacting with the user.
onPause(): Activity loses focus. Save unsaved changes, pause animations.
onStop(): Activity is no longer visible. Release heavy resources.
onRestart(): Activity coming back from stopped. Prepare UI again.
onDestroy(): Activity is destroyed. Clean up resources.
Example Program
[Link]
Mobile Application Development
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main); // MUST match your XML file
[Link](this, "onCreate()", Toast.LENGTH_SHORT).show();
Button btnBack = findViewById([Link]);
[Link](v -> finish()); // Clicking will close activity
}
@Override
protected void onStart() {
[Link]();
[Link](this, "onStart()", Toast.LENGTH_SHORT).show();
}
@Override
protected void onResume() {
[Link]();
[Link](this, "onResume()", Toast.LENGTH_SHORT).show();
}
@Override
protected void onPause() {
[Link]();
[Link](this, "onPause()", Toast.LENGTH_SHORT).show();
}
@Override
protected void onStop() {
[Link]();
[Link](this, "onStop()", Toast.LENGTH_SHORT).show();
}
@Override
protected void onRestart() {
[Link]();
[Link](this, "onRestart()", Toast.LENGTH_SHORT).show();
}
Mobile Application Development
@Override
protected void onDestroy() {
[Link]();
[Link](this, "onDestroy()", Toast.LENGTH_SHORT).show();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="[Link]
android:orientation="vertical"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity Lifecycle Demo"
android:textSize="24sp"
android:layout_marginBottom="50dp"/>
<Button
android:id="@+id/btnBack"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Go Back"
android:textSize="18sp"/>
</LinearLayout>
V Services
Definition
A Service is a special component that allows an Android application to run in the
background.
It performs long-running operations without requiring user interaction.
A UI is not needed for Services.
Services can continue running even if the app is closed or the user switches to another
app.
Other components can bind to a Service for inter-process communication (IPC).
Mobile Application Development
Difference Between Service and Thread
Thread: OS feature that performs tasks in the background.
Service: Android component performing long-running tasks independently of UI.
A Service may use threads internally, but it is not the same as a thread.
Types of Android Services:
Foreground Services
Notify the user about ongoing operations.
Users can interact with the service via notifications.
Example: Downloading a file, music player—user can see progress or control the task.
Background Services
Run without user interaction.
Do not notify the user about ongoing tasks.
Example: Scheduled data sync, automatic backups, storing data in the background.
Mobile Application Development
Bound Services
Allow application components (like Activities) to bind to the service.
Service runs as long as any component is bound.
Multiple components can bind to the same service at the same time.
To bind a component to a service, use bindService() method.
VI Intents in Android
Definition:
An Intent is a messaging object used to request an action from another app component.
Main Uses of Intents
1. Starting an Activity
o Launch a new screen in the app.
o Use startActivity() to start an activity.
o Optionally, use startActivityForResult() to receive data back.
Example:
Intent intent = new Intent([Link], [Link]);
startActivity(intent);
2. Starting a Service
o Services perform background tasks without a UI.
o Use startService() for one-time tasks.
o Use bindService() for client-server style tasks.
Example:
Intent intent = new Intent(this, [Link]);
startService(intent);
3. Delivering a Broadcast
o Broadcasts are messages sent to any app.
o System broadcasts include device charging, boot completed, etc.
o Use sendBroadcast() to send your own broadcast.
Example:
Intent intent = new Intent("[Link].MY_BROADCAST");
sendBroadcast(intent);
Mobile Application Development
Types of Intents
1. Explicit Intent
o Specifies the exact component to start.
o Usually used within the same app.
Intent intent = new Intent(this, [Link]);
startActivity(intent);
2. Implicit Intent
o Specifies a general action, letting any app handle it.
o Example: opening a webpage, showing a location.
Intent intent = new Intent(Intent.ACTION_VIEW);
[Link]([Link]("[Link]
startActivity(intent);
Figure: Implicit Intent
Example:
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
Mobile Application Development
import [Link];
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
Button btnExplicit = findViewById([Link]);
Button btnImplicit = findViewById([Link]);
Button btnBroadcast = findViewById([Link]);
// 1️⃣ Explicit Intent: Start another activity
[Link](v -> {
Intent intent = new Intent([Link], [Link]);
startActivity(intent);
});
// 2️⃣ Implicit Intent: Open a webpage
[Link](v -> {
Intent intent = new Intent(Intent.ACTION_VIEW,
[Link]("[Link]
startActivity(intent);
});
// 3️⃣ Broadcast
[Link](v -> {
Intent intent = new Intent("[Link].MY_BROADCAST");
sendBroadcast(intent);
[Link](this, "Broadcast Sent", Toast.LENGTH_SHORT).show();
});
}
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
Mobile Application Development
[Link](savedInstanceState);
// Simple TextView as layout
TextView tv = new TextView(this);
[Link]("Welcome to Second Activity!");
[Link](24);
[Link](50, 50, 50, 50);
setContentView(tv); // Set TextView as content
}
}
[Link]
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="[Link]
xmlns:tools="[Link]
<!-- Permission for network state -->
<uses-permission android:name="[Link].ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/[Link]">
<!-- Main Activity -->
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>
<!-- Second Activity -->
<activity android:name=".SecondActivity"/>
</application>
</manifest>
Mobile Application Development
[Link]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp">
<Button
android:id="@+id/btnExplicit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start Second Activity" />
<Button
android:id="@+id/btnImplicit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Open Google"
android:layout_marginTop="20dp"/>
<Button
android:id="@+id/btnBroadcast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Broadcast"
android:layout_marginTop="20dp"/>
</LinearLayout>
VII Receiving and Broadcasting Intents
Receiving Intents
Used to get data sent from another activity.
Data is sent using putExtra() and received using getExtra().
Usually handled in the receiving activity’s onCreate() method.
Example:
// Sending Activity
Intent intent = new Intent([Link], [Link]);
Mobile Application Development
[Link]("message", "Hello!");
startActivity(intent);
// Receiving Activity
String message = getIntent().getStringExtra("message");
[Link](this, message, Toast.LENGTH_SHORT).show();
Output: Shows "Hello!" in SecondActivity
Broadcasting Intents
Broadcasts are messages sent to multiple app components or the system.
A BroadcastReceiver listens for these messages and reacts when received.
Two types of broadcasts:
1. System Broadcasts – sent by Android (e.g., battery low).
2. Custom Broadcasts – sent by your own app.
Example:
// BroadcastReceiver
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
[Link](context, "Broadcast received!", Toast.LENGTH_SHORT).show();
}
}
// Sending a Broadcast
Intent intent = new Intent("[Link].MY_BROADCAST");
sendBroadcast(intent);
Output: Shows "Broadcast received!"
Mobile Application Development
VIII. Android Manifest File and Common Settings
What is [Link]?
Every Android app must have it.
Describes app components and gives info to Android system.
Located at: app/src/main/[Link].
Main Purposes
Declare app components: Activities, Services, BroadcastReceivers,
ContentProviders
Set app permissions: e.g., Internet, Camera, Location
Specify features: Hardware/software requirements
Define app info: App name, icon, theme, version
Basic Structure
<manifest xmlns:android="[Link]
package="[Link]">
<uses-permission android:name="[Link]" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/[Link]">
<activity android:name=".MainActivity" android:exported="true">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>
</application>
</manifest>
Mobile Application Development
Common Settings
android:allowBackup → Allow backup of app data
android:icon → App icon
android:label → App name
android:theme → App theme
<intent-filter> → Marks launch activity
<uses-permission> → Requests permissions (Internet, Camera, etc.)
IX. Using Intent Filters and Permissions
Intent Filters
Intent Filters tell Android which intents your app component can respond to.
They are usually declared in [Link].
Used for:
o Starting activities from other apps (implicit intents)
o Receiving broadcasts
Types of actions in intent filters:
o [Link] → App entry point
o [Link] → Open data (e.g., URL, image)
Example: Open SecondActivity when app is launched
<activity android:name=".SecondActivity">
<intent-filter>
<action android:name="[Link]"/>
<category android:name="[Link]"/>
</intent-filter>
</activity>
Mobile Application Development
Example: Receive shared text from other apps
<activity android:name=".ReceiveTextActivity">
<intent-filter>
<action android:name="[Link]"/>
<category android:name="[Link]"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
Permissions
Permissions let the app access restricted features like internet, camera, location,
contacts, etc.
Declared in [Link] using <uses-permission> tag.
Examples:
<uses-permission android:name="[Link]"/>
<uses-permission android:name="[Link]"/>
<uses-permission android:name="[Link].ACCESS_FINE_LOCATION"/>
Some dangerous permissions (like Camera, Location) require runtime request in
code.
Normal permissions (like Internet) are granted automatically by Android.