unit-3mobile application development
unit-3mobile application development
Anatomy of Android applica ons, Android terminologies, Applica on Context, Ac vi es, Services,
Intents, Receiving and Broadcas ng Intents, Android Manifest File and its common se ngs, Using
Intent Filter, Permissions.
An Android applica on is built using a combina on of various components that work together to define its behavior,
appearance, and interac on with users and the system. The anatomy of an Android applica on can be broken down
into key sec ons: the Manifest, Code, Resources, and Build Configura on. Here's a detailed look at the various parts
that make up an Android applica on.
When you create an Android applica on in Android Studio, the project is organized into several folders and files.
Here's a basic overview of the Android project structure:
Top-Level Folders:
main/: Contains the primary source code, resources, and configura on files.
o gradle/: Contains Gradle files, used to manage dependencies and build configura ons.
2.1 AndroidManifest.xml
The AndroidManifest.xml is a crucial file that contains the essen al informa on about your app to the Android
system, such as:
Example:
package="com.example.myapp">
<applica on
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.Light">
<intent-filter>
</intent-filter>
</ac vity>
</applica on>
</manifest>
The src/ folder contains the source code of your applica on, typically wri en in Java or Kotlin (Kotlin is the preferred
language for Android development).
Key Classes:
Broadcast Receivers: Handle global system events (e.g., incoming messages, ba ery low).
package com.example.myapp;
import android.os.Bundle;
import android.widget.TextView;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.ac vity_main);
textView.setText("Welcome to Android!");
The res/ folder contains all the resources used in the app, including layout files, strings, images, and styles. Resources
are stored in specific subdirectories based on their type.
layout/: Contains XML files defining the UI of each ac vity and fragment.
values/: Contains XML files defining resources like strings, colors, and dimensions.
drawable/: Contains image files (e.g., PNG, JPG) used in the app.
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, Android!"
android:textSize="24sp"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"/>
</Rela veLayout>
Android Studio uses Gradle as the build system. The build.gradle files define the app’s dependencies, compile SDK
versions, and other configura ons.
build.gradle (Project-level): Configures global se ngs such as repositories and Gradle version.
build.gradle (App-level): Defines dependencies (e.g., libraries), SDK versions, and build types (e.g., debug,
release).
android {
compileSdkVersion 30
defaultConfig {
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
buildTypes {
release {
minifyEnabled false
dependencies {
implementa on 'androidx.appcompat:appcompat:1.2.0'
implementa on 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementa on 'junit:junit:4.13.1'
The assets/ folder contains raw files (e.g., fonts, text files, audio files) that are bundled with the app but not pre-
processed by Android. You can use the AssetManager class to read files from the assets/ folder.
Example:
ProGuard is a tool that op mizes and obfuscates the code to make it more difficult to reverse-engineer. The proguard-
rules.pro file defines rules for ProGuard, such as which classes or methods to keep or discard during the build process.
Android applica ons are based on a set of core components. Each of these components is defined in the
AndroidManifest.xml file and has a specific role in the app's behavior.
3.1 Ac vi es
Ac vity is the most commonly used component. It represents a single screen in the app.
An app can have mul ple ac vi es, each handling different parts of the app’s UI.
3.2 Services
A Service is a component that runs in the background, performing tasks like downloading files, playing music, or
handling long-running processes.
A Broadcast Receiver listens for and handles system-wide or app-specific broadcast messages, like when the
device's ba ery is low, or when Wi-Fi becomes available.
Broadcast receivers can respond to events such as network changes or SMS messages.
A Content Provider is used to manage access to shared data between applica ons, such as contacts, media files,
or calendar events.
Content providers act as intermediaries to access data from databases, files, or other apps.
1. The AndroidManifest.xml is read by the system to determine the app's structure and components.
3. The setContentView() method is used to inflate the layout, and user interac on begins.
4. The app responds to user input, system events, and performs tasks as needed (e.g., network opera ons,
background services).
Conclusion
The anatomy of an Android applica on is composed of several essen al components, each playing a vital role:
AndroidManifest.xml: Declares essen al details about the app, its components, and permissions.
Source Code: Contains Java/Kotlin code that defines the logic and behavior of the app.
Resources: Includes XML files, images, and other assets that define the app's user interface and func onality.
Core Components: Ac vi es, services, broadcast receivers, and content providers that define how the app
func ons.
Understanding the anatomy of Android applica ons helps in organizing and building efficient, modular, and scalable
apps.
2)Android terminologies
Key Android Terminologies
Here are some essen al Android terminologies that are crucial for understanding how Android applica ons are developed,
structured, and func on:
1. Ac vity
An Ac vity is a single screen with a user interface in an Android app. It acts as the entry point for user interac ons and
controls the app’s UI. An app can have mul ple ac vi es, each represen ng different screens or func onali es.
Example: MainAc vity is o en the first screen users see when they launch the app.
2. Intent
An Intent is a messaging object used to request an ac on from another app component (such as star ng an ac vity or
sending data between ac vi es). Intents can be either explicit (targe ng a specific component) or implicit (indica ng an
ac on to be performed without specifying the component).
Example: Naviga ng from one ac vity to another is done through an Intent.
3. Fragment
A Fragment is a reusable por on of the user interface that can be combined with other fragments to create a complete UI
in an ac vity. Fragments can be added, replaced, or removed dynamically within an ac vity.
Example: A ListFragment displaying a list of items in a part of the screen.
4. View
A View represents a UI element in Android. Views are the building blocks for crea ng the user interface in Android
applica ons. Examples of views include bu ons, text fields, and image views.
Example: TextView, Bu on, EditText are all types of views.
5. Layout
A Layout defines the structure of the UI elements in an ac vity or fragment. It is a container that arranges child views in a
specific way. There are various types of layouts, such as LinearLayout, Rela veLayout, ConstraintLayout, etc.
Example: ac vity_main.xml defines the layout of the main ac vity.
6. Service
A Service is a component that runs in the background and performs long-running opera ons without a user interface.
Services are used for tasks like playing music, downloading files, or handling network requests.
Example: A DownloadService that manages downloading large files in the background.
7. Broadcast Receiver
A Broadcast Receiver listens for and handles system-wide or applica on-specific broadcast messages, such as when the
device’s ba ery is low, or when a new SMS message is received. It allows apps to respond to global events.
Example: An app might use a BroadcastReceiver to listen for network connec vity changes.
8. Content Provider
A Content Provider is a component that manages and shares data between different apps. It provides a standardized
interface for accessing and modifying data from databases, files, or other sources.
Example: The ContactsProvider allows an app to access contact data stored on the device.
9. Manifest File
The AndroidManifest.xml file is an essen al configura on file that provides cri cal informa on about the app to the
Android system. It declares components like ac vi es, services, content providers, and broadcast receivers, and also
requests necessary permissions.
Example: The AndroidManifest.xml declares the app’s main ac vity and permissions for accessing the internet.
10. Permissions
Permissions are used to restrict access to certain resources or capabili es of the device, such as the internet, camera, or
loca on services. These permissions must be declared in the AndroidManifest.xml file, and some permissions need to be
requested at run me as well.
Example: android.permission.INTERNET allows the app to access the internet.
11. SDK (So ware Development Kit)
The Android SDK is a collec on of tools and libraries used to develop Android apps. It includes compilers, debuggers,
device emulators, and the necessary APIs for building Android applica ons.
Example: Android Studio is the official IDE that includes the Android SDK.
12. Gradle
Gradle is the build automa on system used by Android Studio to compile, package, and manage dependencies for Android
applica ons. It uses a domain-specific language (DSL) to define the build configura on.
Example: The build.gradle file contains dependencies and se ngs related to the app’s build process.
13. Build Variants
A Build Variant refers to a version of the app that can be built in Android Studio. Variants are typically created to
dis nguish between different versions of the app (e.g., debug vs. release, or free vs. paid versions).
Example: You may have a debug build variant for tes ng and a release variant for produc on.
14. Manifest Placeholders
Manifest Placeholders are placeholders used in the AndroidManifest.xml file to replace specific values during the build
process. They allow you to configure values dynamically depending on the build type or environment.
Example: @string/app_name can be replaced with different values based on the build configura on.
15. RecyclerView
A RecyclerView is a flexible and efficient view for displaying large sets of data in a scrollable list or grid. It is more efficient
than ListView and allows for easier handling of complex layouts and anima ons.
Example: A RecyclerView could display a list of contacts or messages in an Android app.
16. Ac vity Lifecycle
The Ac vity Lifecycle refers to the series of states that an ac vity goes through during its life. It starts from being created
(onCreate()), becomes visible to the user (onStart()), interacts with the user (onResume()), and may be paused, stopped,
or destroyed as the user interacts with the app.
Example: The onCreate() method is called when an ac vity is first created, and onDestroy() is called when the ac vity is
destroyed.
17. Dependency Injec on
Dependency Injec on (DI) is a design pa ern used to implement Inversion of Control, allowing dependencies (objects) to
be passed to classes rather than being created inside them. DI is commonly used in Android development to manage
objects and their dependencies.
Example: Dagger is a popular DI framework used in Android apps.
18. Handler and Looper
A Handler allows communica on between threads in Android. It is typically used to send messages from a background
thread to the main UI thread (main thread). A Looper is a message loop used by the main thread to handle tasks.
Example: A Handler can post messages from a worker thread to update the UI thread.
19. ANR (Applica on Not Responding)
ANR is an error that occurs when an app becomes unresponsive for a prolonged period. The Android system will display an
ANR dialog if an app’s main thread is blocked for too long, typically more than 5 seconds.
Example: If an app performs a long-running opera on on the main thread, it may trigger an ANR.
20. APK (Android Package)
An APK is the file format used for distribu ng and installing Android applica ons. It contains all the app’s code, resources,
assets, and manifest file. When you build an app, Android Studio generates an APK file.
Example: The APK is installed on an Android device to run the applica on.
21. App Bundle
An App Bundle is a more efficient packaging format for distribu ng Android apps. It allows Android to generate op mized
APKs for each device configura on, reducing the app size and improving performance.
Example: Android App Bundles are the recommended format for publishing apps on Google Play.
22. Jetpack
Jetpack is a set of Android libraries, tools, and architectural guidance to help developers build robust, maintainable, and
testable apps. It includes components like LiveData, Room, Naviga on, and WorkManager.
Example: Naviga on component simplifies naviga on between different screens in an app.
Conclusion
These terminologies form the founda on of Android development. Understanding these terms is essen al for developing,
debugging, and op mizing Android applica ons.
3) Applica on Context
Detailed Informa on on Applica on Context in Android
The Applica on Context in Android is an instance of the Context class, which serves as a handle to the system’s global
state, providing access to the applica on's resources, database, shared preferences, and system services. This context is
linked to the lifecycle of the applica on and is available throughout the en re app's existence, unlike the Ac vity Context,
which is ed to a specific Ac vity or UI screen.
Let’s go into further detail regarding how and when to use the Applica on Context, and how it differs from other types of
context, such as Ac vity Context.
1. Ac vi es
An Ac vity represents a single screen in an Android app, with a user interface (UI) for user interac on. It acts as the entry
point for the user to interact with the app.
Key Features:
Ac vi es control the UI and user interac on.
Each ac vity is typically ed to a layout file (defined in XML).
An app can have mul ple ac vi es, each represen ng a specific part of the app’s func onality.
Lifecycle of an Ac vity:
An ac vity goes through several lifecycle states managed by callback methods:
1. onCreate(): Ini alizes the ac vity, inflates the UI, and prepares resources.
2. onStart(): The ac vity becomes visible to the user.
3. onResume(): The ac vity enters the foreground and interacts with the user.
4. onPause(): The ac vity goes into the background but remains par ally visible (e.g., when a dialog appears).
5. onStop(): The ac vity is no longer visible.
6. onDestroy(): The ac vity is destroyed and cleaned up from memory.
7. onRestart(): Invoked if the ac vity is restarted a er being stopped.
Example of an Ac vity:
public class MainAc vity extends AppCompatAc vity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac vity_main); // Connects the layout to the ac vity
}
}
2. Services
A Service is a component used for performing long-running tasks in the background, without a user interface. Services are
ideal for opera ons that need to con nue even when the user is not ac vely interac ng with the app.
Types of Services:
1. Foreground Services:
o Display a persistent no fica on.
o Commonly used for tasks like music playback or loca on tracking.
2. Background Services:
o Run in the background without user interac on.
o Example: Syncing data or downloading files.
3. Bound Services:
o Allow other components (ac vi es, fragments) to bind to the service to interact with it.
o Example: Communica on between a client and server.
Lifecycle of a Service:
1. onCreate(): Called when the service is created.
2. onStartCommand(): Executes when the service is started using startService().
3. onBind(): Executes when another component binds to the service.
4. onUnbind(): Executes when the service is unbound from all clients.
5. onDestroy(): Cleans up the service.
Example of a Service:
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Perform background work here
return START_STICKY; // Ensures the service restarts if killed
}
@Override
public IBinder onBind(Intent intent) {
return null; // Return null for an unbound service
}
@Override
public void onDestroy() {
super.onDestroy();
// Clean up resources
}
}
To start the service:
Intent serviceIntent = new Intent(this, MyService.class);
startService(serviceIntent);
3. Intents
An Intent is a messaging object used to request an ac on from another app component. It serves as a bridge between
different components, enabling communica on and interac on.
Types of Intents:
1. Explicit Intent:
o Used to launch a specific component (ac vity, service, etc.).
o Example: Naviga ng between ac vi es within the same app.
2. Intent intent = new Intent(this, SecondAc vity.class);
3. startAc vity(intent);
4. Implicit Intent:
o Used to request an ac on that can be handled by any app that supports it (e.g., sharing content, opening a URL).
o Example: Opening a web page in the browser.
5. Intent intent = new Intent(Intent.ACTION_VIEW);
6. intent.setData(Uri.parse("h ps://www.example.com"));
7. startAc vity(intent);
Intent Extras:
You can pass addi onal data with an Intent using extras:
Intent intent = new Intent(this, SecondAc vity.class);
intent.putExtra("key", "value");
startAc vity(intent);
To retrieve the data in the target ac vity:
String value = getIntent().getStringExtra("key");
Intent Filters:
Intent filters are used in the AndroidManifest.xml to specify which intents a component can handle.
Example: Declaring an ac vity to handle the "VIEW" ac on for a specific URL scheme.
<ac vity android:name=".MyAc vity">
<intent-filter>
<ac on android:name="android.intent.ac on.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="h ps" android:host="www.example.com" />
</intent-filter>
</ac vity>
Depends on the ac on
Tied to the user Tied to the task
Lifecycle triggered.
interface. it performs.
These three components form the backbone of Android app development, enabling developers to build feature-rich and
interac ve applica ons.
<!-- Ac vi es -->
<ac vity android:name=".MainAc vity">
<intent-filter>
<ac on android:name="android.intent.ac on.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</ac vity>
</manifest>
The Android Manifest file plays a central role in defining your app’s configura on and func onality. Properly
se ng it up ensures a seamless experience across different devices and versions of Android.
Intents in Android are powerful messaging objects that allow communica on between components within the same app or across
different apps. They can be used to receive and broadcast messages for various system or app events.
Receiving Intents
An Intent can be received by components such as Ac vi es, Services, or Broadcast Receivers. Broadcast Receivers are the most common
way to listen for system-wide or app-specific broadcast events.
1. Define a BroadcastReceiver: Create a class that extends BroadcastReceiver and override the onReceive() method to handle the
intent.
3. @Override
6. if (Intent.ACTION_BATTERY_LOW.equals(ac on)) {
9. }
10. }
11. }
o Sta c Registra on (via AndroidManifest.xml): The receiver is always ac ve and listens for intents even when the
app is not running.
o <receiver android:name=".MyBroadcastReceiver">
o <intent-filter>
o </intent-filter>
o </receiver>
o Dynamic Registra on (via code): The receiver is registered at run me and is ac ve only while the app or specific
component is running.
o registerReceiver(receiver, filter);
13. Handle the Received Intent: In the onReceive() method, you can extract data from the Intent and perform ac ons based on
the received broadcast.
14. @Override
20. }
21. }
Broadcas ng Intents
An app can broadcast its own custom intents to communicate with other apps or components. Broadcas ng is done using the
sendBroadcast(), sendOrderedBroadcast(), or LocalBroadcastManager methods.
1. Create and Send an Intent: Use the Intent class to define the broadcast and include any addi onal data.
4. sendBroadcast(intent);
5. Receive the Broadcast: Other components can register to listen for this custom intent, similar to receiving system broadcasts.
o <receiver android:name=".MyBroadcastReceiver">
o <intent-filter>
o </intent-filter>
o </receiver>
6. Ordered Broadcasts: Use sendOrderedBroadcast() to send a broadcast where mul ple receivers handle the intent in a defined
priority order.
8. sendOrderedBroadcast(intent, null);
9. Local Broadcasts: Use LocalBroadcastManager for broadcas ng intents within your app to improve performance and security.
o localBroadcastManager.sendBroadcast(localIntent);
System Broadcasts
Android provides many predefined system broadcast intents that apps can listen for. Some common examples include:
Example:
context.registerReceiver(receiver, filter);
sendBroadcast() Standard broadcasts to all registered receivers. Global No fy all apps of a custom event.
LocalBroadcastManager Broadcasts limited to your app. Local (within app) Pass data between app components.
1. Use LocalBroadcastManager for internal app communica on to avoid unnecessary system-wide broadcasts.
2. Minimize Sta c Broadcast Receivers as they consume resources even when the app is not ac ve.
4. Avoid Excessive Broadcas ng to reduce app overhead and system resource consump on.
By effec vely receiving and broadcas ng intents, Android apps can achieve efficient communica on and dynamic event handling
between components and other applica ons.