Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

unit-3mobile application development

Uploaded by

Lokesh Pck
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

unit-3mobile application development

Uploaded by

Lokesh Pck
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

UNIT III ANDROID APPLICATION DESIGN ESSENTIALS

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.

1) Anatomy of Android applica ons


Anatomy of an Android Applica on

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.

1. Project Structure Overview

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:

 app/: Contains the core parts of the app.

o src/: Holds the source code files (in Java or Kotlin).

 main/: Contains the primary source code, resources, and configura on files.

 test/: Contains unit tests for the app.

 androidTest/: Contains UI tests for the app.

o res/: Holds resources (layout, strings, images, etc.).

o build/: Stores generated files a er the build process.

o libs/: External libraries the app depends on.

o gradle/: Contains Gradle files, used to manage dependencies and build configura ons.

2. Key Files and Folders in an Android Applica on

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:

 The app's components (ac vi es, services, receivers, content providers).

 Permissions required by the app (e.g., internet access, loca on).

 The app's entry point (usually defined in the MainAc vity).

Example:

<manifest xmlns:android="h p://schemas.android.com/apk/res/android"

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">

<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>

</applica on>

</manifest>

2.2 Java or Kotlin Code (src/)

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:

 Ac vi es: Represent individual screens or UI components. Each ac vity is a subclass of Ac vity.

 Fragments: Smaller components of a screen (op onal, for managing UI modularly).

 Services: Handle background tasks that run without a user interface.

 Broadcast Receivers: Handle global system events (e.g., incoming messages, ba ery low).

 Content Providers: Manage and share data between different apps.

Example of MainAc vity (MainAc vity.java):

package com.example.myapp;

import android.os.Bundle;

import android.widget.TextView;

import androidx.appcompat.app.AppCompatAc vity;

public class MainAc vity extends AppCompatAc vity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.ac vity_main);

TextView textView = findViewById(R.id.textView);

textView.setText("Welcome to Android!");

2.3 Resources (res/)

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.

o Example: ac vity_main.xml defines the layout for the main screen.

 values/: Contains XML files defining resources like strings, colors, and dimensions.

o strings.xml: Stores strings that can be used throughout the app.

o colors.xml: Defines color resources.

o styles.xml: Contains app-wide styling informa on (e.g., themes, text sizes).

 drawable/: Contains image files (e.g., PNG, JPG) used in the app.

 mipmap/: Stores app launcher icons in different resolu ons.

Example of a Layout XML File (ac vity_main.xml):

<?xml version="1.0" encoding="u -8"?>

<Rela veLayout xmlns:android="h p://schemas.android.com/apk/res/android"

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>

2.4 Gradle Files (build.gradle)

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).

Example of build.gradle (App-level):

apply plugin: 'com.android.applica on'

android {

compileSdkVersion 30

defaultConfig {

applica onId "com.example.myapp"

minSdkVersion 16

targetSdkVersion 30

versionCode 1

versionName "1.0"

buildTypes {

release {

minifyEnabled false

proguardFiles getDefaultProguardFile('proguard-android-op mize.txt'), 'proguard-rules.pro'

dependencies {

implementa on 'androidx.appcompat:appcompat:1.2.0'

implementa on 'androidx.constraintlayout:constraintlayout:2.0.4'

testImplementa on 'junit:junit:4.13.1'

2.5 Assets Folder (assets/)

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:

AssetManager assetManager = getAssets();

InputStream inputStream = assetManager.open("myfile.txt");


2.6 Proguard Configura on (proguard-rules.pro)

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.

3. Core Android App Components

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.

 Unlike ac vi es, services don’t have a user interface.

3.3 Broadcast Receivers

 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.

3.4 Content Providers

 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.

4. App Execu on Flow

When an Android app starts:

1. The AndroidManifest.xml is read by the system to determine the app's structure and components.

2. The main ac vity is launched, and the onCreate() method is executed.

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.

 Gradle Configura on: Manages

dependencies, SDK versions, and build configura ons.

 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.

What is Context in Android?


In Android, Context is a base class for accessing system-level services and resources. It provides access to:
 System services like No fica onManager, Loca onManager, WifiManager, etc.
 Resources like strings, layouts, drawables, etc.
 Shared preferences for storing and retrieving persistent data.
Types of Context
1. Applica on Context
o Lifecycle: Tied to the en re applica on’s lifecycle. It remains alive as long as the applica on is running and is
destroyed when the applica on exits.
o Scope: It can be used from anywhere in the applica on because it is global, meaning you can call it from any
component of the app (ac vity, service, etc.).
o Usage: Best used when you need to access resources, services, or configura ons that are independent of UI
elements. It's a safer choice when working with background tasks and system services.
2. Ac vity Context
o Lifecycle: Tied to the lifecycle of an Ac vity. It exists only as long as the Ac vity is in the foreground and is destroyed
when the ac vity is destroyed.
o Scope: Limited to the ac vity that it is associated with.
o Usage: Best for UI opera ons and tasks that require direct interac on with the ac vity’s views or lifecycle.
3. Service Context
o Lifecycle: Tied to the lifecycle of a Service. It persists for the dura on of the service.
o Scope: Limited to the service that it is associated with, but like the applica on context, it can be used globally within
the service.
o Usage: Used for opera ons that run in the background, such as performing network opera ons or processing data.
Differences Between Applica on Context and Ac vity Context
Ac vity Context
Feature Applica on Context

Tied to the lifecycle of the en re Tied to the lifecycle of an ac vity.


Lifecycle
applica on.
Can cause memory leaks if used
Memory Less prone to memory leaks when improperly, especially in long-lived
Leaks used correctly. objects.

Available throughout the Only available within the ac vity.


Scope
applica on.
Best for UI interac ons and infla ng
Best for background tasks, services,
Usage views.
shared preferences, and resources.

Accessing system services or shared Accessing findViewById or interac ng


Example with ac vity views.
preferences.

Key Features and Use Cases for Applica on Context


1. Accessing System Services The Applica on Context provides access to many system services through the getSystemService()
method. These services are used for various purposes, such as interac ng with the hardware, managing data, or handling
system events. You can use the Applica on Context when you need a global reference to these services, which does not
depend on any par cular ac vity.
Example: Accessing System Services
Context context = getApplica onContext();
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
In this example, we access the WifiManager system service using the Applica on Context, which allows us to interact with
Wi-Fi hardware even when no ac vity is ac ve.
2. SharedPreferences SharedPreferences is o en used to store small amounts of data (such as user se ngs or preferences)
persistently. The Applica on Context is commonly used to access SharedPreferences since it doesn’t rely on the lifecycle of a
par cular ac vity.
Example: Using SharedPreferences
Context context = getApplica onContext();
SharedPreferences prefs = context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", "john_doe");
editor.apply();
In this case, the SharedPreferences is accessed using the Applica on Context to save user se ngs, ensuring that the
se ngs persist across ac vi es and when the app is reopened.
3. Database Access The Applica on Context is commonly used when interac ng with databases because database opera ons are
independent of the UI and should be available across the en re app. Using the Applica on Context avoids keeping the database
connec on ed to an Ac vity context, which could result in memory leaks if the ac vity is destroyed.
Example: Accessing SQLite Database
SQLiteDatabase db = context.openOrCreateDatabase("MyDatabase", Context.MODE_PRIVATE, null);
In this example, the Applica on Context is used to access the app's database, ensuring the connec on persists as long as
the app is running.
4. Star ng Services Services in Android run in the background, and the Applica on Context is o en used when star ng a service to
ensure that the service is not ed to the lifecycle of any par cular ac vity. Using the Applica on Context prevents a service
from being unexpectedly stopped if the ac vity that started the service is destroyed.
Example: Star ng a Service
Intent serviceIntent = new Intent(getApplica onContext(), MyBackgroundService.class);
startService(serviceIntent);
Here, the Applica on Context is used to start a service. This ensures that the service con nues to run even if the ac vity
that started it is no longer ac ve.
5. Broadcast Receivers Broadcasts are global system or applica on-wide events (e.g., device boot, network status change). You can
use the Applica on Context to register or send broadcasts that need to be observed globally.
Example: Sending a Broadcast
Intent intent = new Intent("com.example.MY_ACTION");
sendBroadcast(intent);
The Applica on Context is used to send broadcasts in this example, which allows other components of the app (or even
other apps) to receive and respond to the event.
6. Loading Resources You can use the Applica on Context to load resources such as strings, drawables, and other app assets that
are not dependent on the UI.
Example: Accessing Resources
String appName = getApplica onContext().getString(R.string.app_name);
This is useful when you need to access resources without relying on a specific ac vity’s lifecycle.
Cau on: Poten al Pi alls of Applica on Context
While the Applica on Context is generally safe for long-lived tasks like background services, it should not be used for UI-
related tasks (such as showing Toasts or star ng ac vi es), as it does not have access to the view hierarchy. For UI
opera ons, the Ac vity Context is recommended.
 Memory Leaks: If you hold a reference to the Applica on Context in an object that outlives the applica on's lifecycle (like in a
singleton), it can result in a memory leak if you are not careful. Similarly, Ac vity Context references should not be held in sta c
fields.
 UI Context: The Applica on Context does not have access to the ac vity's UI elements. For example, if you a empt to display a
Toast from the Applica on Context, it can lead to unexpected behavior or crashes because Toast requires a context ed to the
UI.
Example: Avoiding Memory Leaks
// This is incorrect usage of Applica onContext to avoid memory leaks
public class SomeClass {
private sta c Context appContext;

public sta c void init(Context context) {


appContext = context.getApplica onContext(); // Storing Applica onContext
}

public sta c void someMethod() {


// This will lead to a memory leak if appContext is not cleaned up
// because the context is held sta cally
SharedPreferences prefs = appContext.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
}
}
In the example above, the sta c reference to the Applica on Context might cause memory leaks if SomeClass is used for
long-lived tasks like storing user preferences because appContext won’t be cleared un l the app terminates.
Summary
 Applica on Context provides global access to applica on resources and system services, making it useful for background tasks,
system services, shared preferences, and database access.
 It is ed to the applica on's lifecycle and exists as long as the app is running.
 Avoid using Applica on Context for UI-related tasks (e.g., showing Toast, infla ng views, star ng ac vi es).
 Ac vity Context should be used for UI tasks as it is ed to the ac vity’s lifecycle.
 Proper management of context usage helps prevent memory leaks and ensures efficient use of system resources.

4) Ac vi es, Services, Intents


Key Android Components: Ac vi es, Services, and Intents
Android applica ons are built using fundamental building blocks that allow developers to create a variety of
func onali es. Three of the most essen al components are Ac vi es, Services, and Intents. Here's an in-depth overview
of each:

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>

Summary of Ac vi es, Services, and Intents:


Intents
Feature Ac vi es Services

Represent a Perform Facilitate


Purpose single screen background communica on
between components.
with a UI. tasks.

Depends on the ac on
Tied to the user Tied to the task
Lifecycle triggered.
interface. it performs.

Direct Used to navigate or


No user
Interac on interac on with pass data.
interface.
the user.

Login screen, Music playback, Naviga ng between


Example ac vi es or apps.
se ngs screen. data sync.

These three components form the backbone of Android app development, enabling developers to build feature-rich and
interac ve applica ons.

5)Android Manifest File and its common se ngs


Android Manifest File
The Android Manifest file (AndroidManifest.xml) is an essen al part of every Android app. It provides
informa on about the applica on to the Android system, such as its components, permissions, and
hardware requirements. It acts as a declara on for how the app interacts with the system and other apps.
The manifest file is located in the app/src/main/ directory of an Android project.

Structure of the Android Manifest File


Here’s a basic structure of an Android Manifest file:
<manifest xmlns:android="h p://schemas.android.com/apk/res/android"
package="com.example.myapp">
<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />

<!-- Minimum and target API levels -->


<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="33" />

<!-- Applica on Tag -->


<applica on
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">

<!-- 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>

<!-- Services -->


<service android:name=".MyService" />

<!-- Broadcast Receivers -->


<receiver android:name=".MyBroadcastReceiver" />

<!-- Content Providers -->


<provider
android:name=".MyContentProvider"
android:authori es="com.example.myapp.provider" />
</applica on>

</manifest>

Common Elements and Their Se ngs


1. <manifest>
o The root element of the file.
o Defines the applica on’s package name and contains all other elements.
o A ributes:
 package: The unique iden fier for the app (e.g., com.example.myapp).
2. <uses-permission>
o Declares the permissions required by the app to perform specific tasks (e.g., accessing the internet,
loca on, or camera).
o Example:
o <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
3. <uses-sdk>
o Specifies the app's compa bility with different versions of Android.
o A ributes:
 minSdkVersion: Minimum API level required to run the app.
 targetSdkVersion: API level the app is tested against.
 maxSdkVersion (op onal): Maximum API level the app supports.
o Example:
o <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="33" />
4. <applica on>
o Contains global se ngs for the app and declara ons of its components (ac vi es, services, etc.).
o Common a ributes:
 android:allowBackup: Enables or disables app data backup.
 android:icon: App icon resource.
 android:label: Display name of the app.
 android:theme: App’s default theme.
o Example:
o <applica on
o android:allowBackup="true"
o android:icon="@mipmap/ic_launcher"
o android:label="@string/app_name"
o android:theme="@style/AppTheme">
o </applica on>
5. <ac vity>
o Declares an Ac vity component and its behavior.
o A ributes:
 android:name: Fully qualified name or rela ve name of the Ac vity class.
 android:label: Title for the ac vity.
 android:theme: Specific theme for the ac vity.
 android:launchMode: Specifies how the ac vity should be launched (e.g., singleTask,
singleTop).
o Example:
o <ac vity android:name=".MainAc vity">
o <intent-filter>
o <ac on android:name="android.intent.ac on.MAIN" />
o <category android:name="android.intent.category.LAUNCHER" />
o </intent-filter>
o </ac vity>
6. <service>
o Declares a Service component.
o A ributes:
 android:name: Name of the service class.
 android:exported: Specifies whether the service can be used by other apps.
o Example:
o <service android:name=".MyService" android:exported="false" />
7. <receiver>
o Declares a BroadcastReceiver component.
o Example:
o <receiver android:name=".MyBroadcastReceiver" />
8. <provider>
o Declares a ContentProvider for data sharing.
o A ributes:
 android:authori es: Unique authority string.
o Example:
o <provider
o android:name=".MyContentProvider"
o android:authori es="com.example.myapp.provider" />
9. <intent-filter>
o Specifies the type of intents a component can respond to.
o Example for an ac vity to be launched at app startup:
o <intent-filter>
o <ac on android:name="android.intent.ac on.MAIN" />
o <category android:name="android.intent.category.LAUNCHER" />
o </intent-filter>
10. <meta-data>
o Allows you to pass custom data to your app or components.
o Example:
o <meta-data
o android:name="com.example.customKey"
o android:value="customValue" />
Common Manifest Configura ons
1. Permissions
o If your app requires access to specific features (e.g., camera, loca on), declare them here:
o <uses-permission android:name="android.permission.CAMERA" />
2. Hardware and So ware Features
o To declare app dependencies on hardware features:
o <uses-feature android:name="android.hardware.camera" android:required="true" />
3. Main Ac vity
o Define the entry point for the app using an intent filter with MAIN and LAUNCHER categories:
o <ac vity android:name=".MainAc vity">
o <intent-filter>
o <ac on android:name="android.intent.ac on.MAIN" />
o <category android:name="android.intent.category.LAUNCHER" />
o </intent-filter>
o </ac vity>
4. App Icon and Label
o Set the app’s display name and icon:
o <applica on
o android:icon="@mipmap/ic_launcher"
o android:label="@string/app_name" />
5. Applica on Metadata
o Pass configura on se ngs or API keys to your app:
o <applica on>
o <meta-data
o android:name="com.google.android.geo.API_KEY"
o android:value="YOUR_API_KEY" />
o </applica on>
6. Backup Configura on
o Enable or disable automa c backup:
o <applica on android:allowBackup="true" android:fullBackupContent="true" />

Tips for Working with the Manifest


1. Keep it Organized:
o Group related components together for be er readability.
2. Set Proper Permissions:
o Only request permissions your app truly needs to avoid unnecessary user concerns.
3. Follow Naming Conven ons:
o Use package and class names consistently to avoid run me errors.
4. Test on Different Devices:
o Use features like uses-sdk and uses-feature to ensure compa bility across devices.
5. Use Tools:
o Use Android Studio’s Manifest Editor for easier edi ng.

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.

6) Receiving and Broadcas ng Intents


Receiving and Broadcas ng Intents in 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.

Steps to Receive an Intent:

1. Define a BroadcastReceiver: Create a class that extends BroadcastReceiver and override the onReceive() method to handle the
intent.

2. public class MyBroadcastReceiver extends BroadcastReceiver {

3. @Override

4. public void onReceive(Context context, Intent intent) {

5. String ac on = intent.getAc on();

6. if (Intent.ACTION_BATTERY_LOW.equals(ac on)) {

7. // Handle the ba ery low event

8. Toast.makeText(context, "Ba ery is low!", Toast.LENGTH_SHORT).show();

9. }

10. }

11. }

12. Register the Receiver:

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 <ac on android:name="android.intent.ac on.BATTERY_LOW" />

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 IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_LOW);

o MyBroadcastReceiver receiver = new MyBroadcastReceiver();

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

15. public void onReceive(Context context, Intent intent) {

16. Bundle extras = intent.getExtras();

17. if (extras != null) {

18. String message = extras.getString("key");

19. Log.d("Receiver", "Received message: " + message);

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.

Steps to Broadcast an Intent:

1. Create and Send an Intent: Use the Intent class to define the broadcast and include any addi onal data.

2. Intent intent = new Intent("com.example.CUSTOM_INTENT");

3. intent.putExtra("key", "Hello, World!");

4. sendBroadcast(intent);

5. Receive the Broadcast: Other components can register to listen for this custom intent, similar to receiving system broadcasts.

o Register in the AndroidManifest.xml:

o <receiver android:name=".MyBroadcastReceiver">

o <intent-filter>

o <ac on android:name="com.example.CUSTOM_INTENT" />

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.

7. Intent intent = new Intent("com.example.ORDERED_INTENT");

8. sendOrderedBroadcast(intent, null);

o Set the priority in the manifest:

o <receiver android:name=".MyReceiverOne" android:priority="2" />

o <receiver android:name=".MyReceiverTwo" android:priority="1" />

9. Local Broadcasts: Use LocalBroadcastManager for broadcas ng intents within your app to improve performance and security.

o Send a local broadcast:

o LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(context);

o Intent localIntent = new Intent("com.example.LOCAL_INTENT");

o localIntent.putExtra("key", "Local Message");

o localBroadcastManager.sendBroadcast(localIntent);

o Register a local receiver:

o LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(context);

o IntentFilter localFilter = new IntentFilter("com.example.LOCAL_INTENT");

o localBroadcastManager.registerReceiver(new MyBroadcastReceiver(), localFilter);

System Broadcasts

Android provides many predefined system broadcast intents that apps can listen for. Some common examples include:

 android.intent.ac on.BATTERY_LOW: Triggered when the ba ery is low.

 android.intent.ac on.AIRPLANE_MODE_CHANGED: Triggered when airplane mode changes.


 android.net.conn.CONNECTIVITY_CHANGE: Triggered when network connec vity changes.

Example:

IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_LOW);

MyBroadcastReceiver receiver = new MyBroadcastReceiver();

context.registerReceiver(receiver, filter);

Advantages of Broadcast Receivers

1. Efficient way to handle global events.

2. Allows communica on between different components or apps.

3. Provides a mechanism for dynamic event handling.

Comparison of Sending Broadcasts

Method Use Case Scope Example

sendBroadcast() Standard broadcasts to all registered receivers. Global No fy all apps of a custom event.

sendOrderedBroadcast() Broadcasts with priority-based handling. Global No fy receivers in a defined order.

LocalBroadcastManager Broadcasts limited to your app. Local (within app) Pass data between app components.

Best Prac ces

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.

3. Clean Up Dynamic Receivers by unregistering them when no longer needed.

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.

You might also like