0% found this document useful (0 votes)
58 views21 pages

Anatomy of Android App Components

I need answers to score good marks in semister

Uploaded by

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

Anatomy of Android App Components

I need answers to score good marks in semister

Uploaded by

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

Anatomy of an Android Application:

An Android Application is a collection of interconnected components that work together to deliver a


smooth and interactive mobile experience. Each component has its own specific role, and the
Android system manages their life cycles efficiently.
An Android app typically includes Activities, Services, Broadcast Receivers, Content Providers, and
Intents. Let’s understand each in detail:
1. Activities

An Activity is one of the most important components of an Android application. It represents a single
screen with a user interface that allows the user to interact with the app. Each activity is like an
individual page in the app, and an application can have one or more activities working together.
When an app is opened, Android launches the main activity, which serves as the entry point for user
interaction. Activities handle user actions such as clicking buttons, typing text, or selecting items, and
they can also navigate to other activities. Every activity has a layout file (XML) that defines how the
screen looks, and the Java/Kotlin code behind it defines how it behaves.
Example: In a mobile banking app, the Login Screen is one activity where the user enters credentials,
and the Dashboard Screen showing account details is another activity.
2. Services

A Service is a component used to perform background operations that do not need any user
interface. It runs even when the user is not interacting directly with the app. Services are useful for
long-running tasks like playing music, downloading files, syncing data, or fetching information from
the internet. Unlike activities, services do not show anything on the screen, but they keep the app
functioning smoothly in the background. Android provides different types of services such as
Foreground Services (which show notifications), Background Services (for hidden background tasks),
and Bound Services (which allow interaction between apps).
Example: When you listen to music on your phone and switch to another app, the music continues to
play — this happens because a background service is running the music player.

3. Broadcast Receivers
A Broadcast Receiver is a component that allows an application to respond to broadcast messages
sent by the Android system or by other applications. It acts like a listener that waits for specific
events to happen and then reacts accordingly. Broadcasts can be system-generated (like low battery,
incoming calls, Wi-Fi connectivity changes) or app-generated (custom messages). When a broadcast
is received, the receiver automatically performs an action like showing a message, starting a service,
or updating the UI. This helps apps stay responsive to important system changes.
Example: When your phone’s battery becomes low, the Android system sends a “battery low”
broadcast, and apps that have a Broadcast Receiver can detect it and alert the user to charge the
phone.
4. Content Providers

A Content Provider is used to manage and share data between different applications in a structured
and secure way. It works as a bridge that allows apps to access data stored by other apps without
directly accessing their files. The data may be stored in an SQLite database, file system, or even on
the internet. Each content provider uses a unique URI (Uniform Resource Identifier) to identify the
data it provides. This component ensures that sensitive data like contacts or messages are shared
safely with proper permissions.

Example: The Contacts App on Android uses a content provider to store all contact details. Other
apps, like WhatsApp or Telegram, use this provider to access your contact list when showing who is
available to chat.
5. Intents

An Intent is a messaging object that allows different Android components to communicate with each
other. It is used to start activities, launch services, or deliver broadcasts. Intents can also carry data
between components using extras. There are two main types of intents: Explicit Intents (which
directly specify the target component) and Implicit Intents (which specify the action to be
performed, letting the system decide which app can handle it). Intents are one of the most powerful
features in Android because they enable inter-app communication and task automation.
Example: When you click the Share button in a photo gallery app, an implicit intent is used to open
another app like WhatsApp, Gmail, or Instagram to share that photo.
Android Terminologies:
Below are the important terms and their meanings used in Android Development:

1. Android
 Android is an open-source mobile operating system developed by Google.

 It is based on the Linux kernel and mainly used for smartphones, tablets, and wearable
devices.

2. Activity

 An Activity represents a single screen in an Android app (like a page in a website).


 Example: Login screen, Home screen.

 File type: [Link] or [Link].


3. Intent

 An Intent is used to start another activity or communicate between components.

 Example: Opening a new screen or sending data to another app.

4. Fragment

 A Fragment is a reusable portion of a user interface that can be combined within an Activity.

 Helps in building flexible and responsive UIs.


5. View

 A View is the basic building block of the UI.


 Examples: Button, TextView, EditText, ImageView.

6. Layout

 Layout defines how UI elements are arranged on the screen.

 Examples: LinearLayout, RelativeLayout, ConstraintLayout.

7. Manifest File ([Link])

 This file contains essential information about the app:

o App name, version, permissions (like internet, camera)

o Declares all activities, services, receivers.


8. Resources (res folder)

 Contains non-code files like images, strings, colors, and layouts.

o res/layout → XML UI files

o res/drawable → Images

o res/values → Strings, colors, styles


9. Gradle

 Gradle is the build automation tool used in Android Studio.

 It manages dependencies, compiles code, and builds APKs.

10. SDK (Software Development Kit)

 A collection of tools, libraries, and APIs needed to develop Android apps.


 Includes emulator, debugger, and Android platform tools.

11. AVD (Android Virtual Device)


 A virtual emulator used to test apps on different Android devices without needing a real
phone.

12. ADB (Android Debug Bridge)


 A command-line tool that lets you communicate with an Android device (for debugging and
testing).

13. APK (Android Package Kit)

 The file format of Android apps.

 It contains all resources, code, and manifest to install the app.

14. Dalvik / ART (Android Runtime)


 Android apps run inside the Android Runtime (ART).

 Earlier versions used Dalvik Virtual Machine.

 It converts app code into machine code for execution.


15. Services

 Background components that perform tasks without a user interface.

 Example: Playing music, downloading files.

16. Broadcast Receiver

 Used to listen for system-wide messages or events.

 Example: Battery low alert, incoming call.

17. Content Provider

 Manages and shares data between apps.

 Example: Contacts app data accessed by other apps.

18. Permissions

 Apps must request permissions to access certain features.

 Example: Camera, Location, Storage.


19. RecyclerView

 Advanced and efficient list view for displaying large sets of data in scrollable form.
Creating User Interfaces with Basic Views:
In Android, the User Interface (UI) is designed using a hierarchy of Views and ViewGroups. Together,
they define how the user interacts with the app — how buttons appear, how text is displayed, and
how different elements are arranged on the screen. Every visible component in an Android
application, such as a button, image, or text field, is built upon these fundamental concepts.

1. View:
A View in Android represents the basic building block of the user interface. It is an object that
occupies a rectangular area on the screen and is responsible for drawing content and handling user
interactions such as touch, click, and keyboard input. Views are the visual elements the user can see
and interact with. Examples include TextView, Button, ImageView, EditText, and CheckBox.

Each View can be customized by changing its attributes such as width, height, color, padding, and
text. Developers can also define behaviors such as what happens when the user clicks or long-
presses the view.

Example:
A TextView displays static text, a Button performs an action when clicked, and an ImageView shows
an image or icon on the screen.

Common Types of Views

a) TextView

A TextView is used to display text to the user. It is one of the simplest and most commonly used
views in Android. You can set its text, size, color, and style through XML or programmatically in
Java/Kotlin.
Example: A label showing “Welcome to MyApp” on the screen.

b) EditText

An EditText allows users to enter and edit text. It is an editable version of TextView that is often used
in forms, login screens, or search bars.
Example: A text box where users enter their username or password.

c) Button

A Button represents a clickable element that performs an action when pressed. It is one of the main
interactive components in Android applications.
Example: A "Submit" or "Login" button that triggers an event when tapped.

d) ImageView

An ImageView is used to display an image resource, such as icons or photos, on the screen. You can
set the image source, adjust its size, and scale it within the layout.
Example: Showing a company logo or profile picture.

e) CheckBox

A CheckBox allows users to select one or more options from a set. It can be either checked or
unchecked, and its state can be read in the program to perform specific actions.
Example: A list of options like “Subscribe to newsletter” or “Accept Terms & Conditions.”
2. ViewGroup:
A ViewGroup is a special type of View that can contain other Views (or even other ViewGroups). It
acts as a container that organizes the layout structure of the UI. ViewGroups are responsible for
positioning, measuring, and managing the child Views they contain. The way Views are arranged
within a ViewGroup depends on the type of layout being used.

In other words, a ViewGroup defines how multiple UI elements are displayed on the screen —
whether they appear side by side, stacked vertically, centered, or positioned relative to one another.
Examples of ViewGroups:
LinearLayout, RelativeLayout, ConstraintLayout, FrameLayout, and TableLayout.

Common Types of ViewGroups (Layouts)


a) LinearLayout

A LinearLayout arranges its child views either vertically (one below another) or horizontally (side by
side). The order of arrangement depends on the orientation attribute.
It’s simple and useful for creating structured lists or form-like interfaces.
Example: A vertical layout containing a TextView, EditText, and Button stacked top to bottom.

b) RelativeLayout

A RelativeLayout arranges its child views relative to each other or relative to the parent container.
You can position one element to the left, right, above, or below another element.
This layout provides flexibility for complex UI designs without deeply nested layouts.
Example: Placing a Button below an EditText and aligning both in the center of the screen.

c) ConstraintLayout
A ConstraintLayout is an advanced layout that allows you to create flexible, flat, and responsive
designs without nesting multiple ViewGroups. You can define constraints between different views —
for example, aligning one view to another’s edge or centering elements both vertically and
horizontally.
Example: Designing a modern login screen with a logo at the top and text fields perfectly aligned
below it.

d) FrameLayout
A FrameLayout is designed to hold a single child view, though it can technically contain multiple
children stacked on top of each other. It is often used to display one element at a time, such as when
switching between fragments.
Example: Displaying a video or image in the center of the screen, where other elements may overlap.

e) TableLayout

A TableLayout organizes its children into rows and columns, similar to an HTML table. It’s suitable for
displaying structured data in a grid-like manner.
Example: A layout that shows student marks in tabular format with rows for subjects and columns
for marks.
Application Components:
Android applications are built using four major components, which define how an app behaves,
interacts with the system, and communicates with other apps. Each component plays a unique and
important role in the Android ecosystem.

a. Context:
In Android, Context is an abstract class that provides access to system resources, application-level
operations, and services. It is like a “bridge” between the Android system and your application.

Purpose:

Context is used to:


 Access system services (e.g., ConnectivityManager, LocationManager).

 Retrieve app resources such as strings, layouts, and drawables.


 Start new activities or services.

 Access files, databases, and shared preferences.


Types of Context:

1. Application Context – Used for global operations, remains alive as long as the application is
running.
Example: getApplicationContext()

2. Activity Context – Tied to the lifecycle of an activity, should be used for UI-related tasks.
Example: this or [Link]
Common Uses:

 To start an activity:

 Intent i = new Intent(getApplicationContext(), [Link]);

 startActivity(i);

 To access SharedPreferences:

 SharedPreferences sp = getSharedPreferences("MyPrefs", MODE_PRIVATE);


 To access a system service:

 ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
b. Activity:
An Activity is a single screen in an Android application that provides a user interface (UI). It acts as
the main entry point for user interaction.

Each activity represents one task that a user can perform in the app.

Purpose:

 To provide a user interface to interact with users.


 To manage the app’s UI lifecycle.

 To control navigation between screens.

Activity Lifecycle:

Android manages activity states using lifecycle methods:


1. onCreate() – Called when the activity is first created. Initialize UI components here.

2. onStart() – Called when the activity becomes visible.

3. onResume() – Activity is in the foreground and ready for user interaction.

4. onPause() – Activity is partially hidden (e.g., another app is on top).

5. onStop() – Activity is no longer visible.


6. onDestroy() – Activity is about to be destroyed (final cleanup).

Example:

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);
setContentView([Link].activity_main);

@Override
protected void onStart() {

[Link]();

[Link](this, "Activity Started", Toast.LENGTH_SHORT).show();

Notes:

 Every Android app must have at least one activity (main activity).

 Activities are declared in the [Link] file.


c. Service:
A Service is a component that runs in the background to perform long-running operations without a
user interface. It continues to run even if the user switches to another app.

Purpose:

Used for background operations such as:

 Playing music while using another app.


 Downloading or uploading files in the background.

 Syncing data with a server.

 Tracking user location.

Types of Services:
1. Foreground Service:

o Always visible to the user through a notification.

o Used for tasks the user is actively aware of.


Example: Music player, step counter.

2. Background Service:

o Runs in the background without user awareness.

o Used for less critical background operations.

3. Bound Service:

o Allows other components (activities or apps) to bind and interact with it.
o Useful for client-server communication within the same app.

Lifecycle Methods:
 onCreate() – Called when the service is created.

 onStartCommand() – Called when the service starts.

 onBind() – Called when another component binds to the service.

 onDestroy() – Called before the service is destroyed.


Example:

public class MyService extends Service {

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

[Link](this, "Service Started", Toast.LENGTH_SHORT).show();


// Perform background operation

return START_STICKY;
}

@Override

public void onDestroy() {

[Link](this, "Service Stopped", Toast.LENGTH_SHORT).show();

@Override

public IBinder onBind(Intent intent) {

return null;
}
}

Starting a Service:
Intent i = new Intent(this, [Link]);

startService(i);

Stopping a Service:

stopService(i);
Intents in Android:
In Android, an Intent is a messaging object that allows different components of an application, such
as activities, services, or broadcast receivers, to communicate with each other. Intents act like
requests or instructions, telling the Android system that a specific action should be performed. They
can also carry additional information, such as user input or data from one activity to another, making
them very powerful for component interaction. Intents form the backbone of Android’s component-
based architecture, as without them, different parts of an app would not be able to work together
effectively. Simply put, an intent is a tool that helps one part of an app talk to another part or even
request services from other apps installed on the device.

Types of Intents
Android provides two main types of intents, which are explicit intents and implicit intents, each
serving different purposes and use cases.

1. Explicit Intents:
An explicit intent is used when you want to start a specific component of your application, such as a
particular activity or service. The developer must specify the exact class name of the target
component in the intent, which means there is no ambiguity about which component will handle the
request. This type of intent is mostly used for internal navigation within an app, for example, moving
from a login screen to a dashboard or opening a profile page from a list. Explicit intents can also carry
data to the target component using methods like putExtra(), which allows passing strings, numbers,
or even objects. Because explicit intents are directed and controlled, they are very predictable, easy
to debug, and secure, as they cannot trigger components from other apps without explicit
permission.

Example: Navigating from one activity to another

Intent intent = new Intent(this, [Link]);

startActivity(intent);

Example with Data Transfer:

Intent intent = new Intent(this, [Link]);

[Link]("username", "John");

[Link]("age", 25);

startActivity(intent);

Advantages:

 Simple and predictable

 Directly opens the required activity

 Secure, as only known components can be invoked


2. Implicit Intents:
An implicit intent is used when you do not specify the exact component to handle the request.
Instead, you describe the action you want to perform, such as viewing a webpage, sending a
message, or opening a map. The Android system then searches for all components or apps installed
on the device that can handle that action and lets the user choose or automatically selects the best
match. Implicit intents are especially useful for cross-app functionality, enabling your app to interact
with other apps without directly integrating their code. They can also carry data, such as URLs or
text, to be used by the receiving app, and the receiving app must declare an intent filter in its
manifest to respond to such requests.

Example: Open a website

Intent intent = new Intent(Intent.ACTION_VIEW, [Link]("[Link]

startActivity(intent);

Example: Share text


Intent shareIntent = new Intent(Intent.ACTION_SEND);

[Link]("text/plain");
[Link](Intent.EXTRA_TEXT, "Hello, check this out!");

startActivity([Link](shareIntent, "Share via"));


Advantages:

 Flexible and not tied to a single component

 Enables cross-app communication

 Makes apps interoperable


Receiving and Broadcasting Intents in Android:
In Android, broadcasting intents is a way for apps or the system to send messages to multiple
components at once. These messages are called broadcasts, and they can inform apps about system
events (like battery low, device boot completed) or app-specific events (like new data available). A
BroadcastReceiver is a component that listens for these broadcasts and reacts when a relevant
message is received. Broadcast receivers are useful for performing actions without keeping an
activity running, enabling efficient, event-driven behavior in apps.
Creating a Broadcast Receiver

A BroadcastReceiver is a special Android component that receives and handles broadcast intents. To
create one, you extend the BroadcastReceiver class and implement the onReceive() method, which is
automatically called when the broadcast is received. Inside onReceive(), you can perform actions
such as showing a notification, starting a service, or updating the UI.

Registering Broadcast Receivers


Broadcast receivers can be registered in two ways:

1. Statically in the manifest:


o When registered in the manifest file, the receiver is always ready to receive
broadcasts, even if the app is not running.

o The <intent-filter> defines which actions the receiver will listen for.
o Example: Listening for the device boot completion event.

<receiver android:name=".MyReceiver">
<intent-filter>

<action android:name="[Link].BOOT_COMPLETED" />

</intent-filter>

</receiver>

2. Dynamically in code:

o Dynamic registration allows receivers to be active only while the activity or service is
running, conserving system resources.

o Receivers must be unregistered when not needed to prevent memory leaks.

IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_LOW);

MyReceiver receiver = new MyReceiver();

registerReceiver(receiver, filter);

Dynamic receivers are ideal for temporary events like monitoring network connectivity or responding
to user interactions.
Types of Broadcasts

Broadcasts can be classified into three types, each with its own behavior and use cases:

1. Normal Broadcasts:

o Sent using sendBroadcast() and delivered asynchronously to all receivers.

o The order of delivery is not guaranteed, and all receivers receive it roughly at the
same time.

o Example: A weather app broadcasting updated temperature information to multiple


components.
2. Ordered Broadcasts:

o Sent using sendOrderedBroadcast() and delivered one receiver at a time based on


priority.
o Higher-priority receivers can abort the broadcast to prevent it from reaching lower-
priority receivers.

o Example: Security-related events or notifications where certain apps must handle the
event before others.

3. Local Broadcasts:

o Sent using LocalBroadcastManager and confined within the same app, making them
more secure and efficient.

o These broadcasts do not leave the app, reducing risk of exposing sensitive data.

o Example: Notifying an activity that new data has been downloaded by a service.
Use Cases of Broadcast Receivers

Broadcast receivers are widely used in Android applications to handle system and app-specific
events:

1. System Events:

o Detect when the device boots, battery is low, Wi-Fi or network connectivity changes,
or when an incoming call or SMS is received.

2. App-specific Events:

o Notify activities when a download or upload is complete, when new messages arrive,
or when background data updates occur.

3. Scheduling Tasks:

o Broadcasts can trigger Alarms via the AlarmManager to run periodic tasks at specific
times, even when the app is not active.

4. Security and Monitoring:

o Detect unauthorized access or changes in device settings, allowing apps to respond


proactively.
Android Manifest File:
The Android Manifest File is a central configuration file for every Android application. Named
[Link], it serves as a bridge between the Android system and your app, providing
essential information about your app’s components, permissions, and overall behavior. Without this
file, the system would not know what activities, services, broadcast receivers, or content providers
exist in the app, making it impossible to run. Essentially, it acts as a blueprint for the Android
operating system, describing what the app contains and what it is allowed to do.
Purpose of [Link]

1. Declares App Components:


o The manifest lists all components of the app, including activities, services, broadcast
receivers, and content providers.

o It tells the system which activity should be the launcher activity and which services
can run in the background.

o Example: Declaring the main activity ensures the system knows which screen to start
when the app launches.
2. Requests Permissions:

o Many Android features, like accessing the camera, internet, or storage, require
explicit permissions.
o The manifest is where you declare these permissions, allowing the system to prompt
the user for access.

o Example: To access the internet, you declare <uses-permission


android:name="[Link]"/>.

3. Defines App Configuration:

o The manifest can define app metadata, such as app name, icon, theme, version, and
supported screen sizes or device features.

o It can also declare hardware or software requirements, ensuring the app runs only
on compatible devices.

o Example: Specifying that the app requires a camera ensures it won’t install on
devices without one.

Basic Structure of [Link]

A typical manifest file contains the following main elements:

1. <manifest> Tag

The <manifest> tag is the root element of the Android manifest file. It defines the package name of
your application, which acts as a unique identifier for the app on the device and in the Google Play
Store. Inside the manifest tag, you can declare permissions, components, and application-level
metadata. The manifest also specifies the minimum and target SDK versions, which ensure that your
app runs on compatible devices. Without this root element, the system would not be able to parse
the configuration, making it impossible for the app to run correctly.
Example:

<manifest xmlns:android="[Link]

package="[Link]"

android:versionCode="1"

android:versionName="1.0">
</manifest>

2. <uses-permission> Tag
The <uses-permission> tag is used to request access to protected system features. Many Android
APIs, like accessing the camera, internet, or storage, require permissions to ensure user privacy and
security. Permissions are divided into normal (automatically granted) and dangerous (require explicit
user approval). Declaring permissions in the manifest ensures that the system prompts the user
appropriately when the app tries to access restricted features. Failing to declare necessary
permissions will cause the app to crash or malfunction.

Example:
<uses-permission android:name="[Link]" />

<uses-permission android:name="[Link]" />

3. <application> Tag

The <application> tag acts as a container for all app components like activities, services, broadcast
receivers, and content providers. It also allows you to define global attributes for the app, such as the
app icon (android:icon), app name (android:label), theme (android:theme), and backup options. You
can also specify metadata, like API keys for third-party services, inside the application tag. Essentially,
it provides a centralized configuration for your app’s behavior and appearance.

Example:

<application

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme">

</application>

4. <activity> Tag

The <activity> tag declares a single screen (activity) of your app. Activities are the building blocks of
an Android UI, and each activity must be registered in the manifest to function correctly. The main
activity, which launches when the app starts, is specified with an intent filter using MAIN action and
LAUNCHER category. Additional attributes like android:launchMode or android:screenOrientation can
control how the activity behaves. Properly defining activities in the manifest ensures that the system
can manage them in the task stack efficiently.
Example:

<activity android:name=".MainActivity">

<intent-filter>

<action android:name="[Link]"/>

<category android:name="[Link]"/>
</intent-filter>

</activity>

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

5. <service> Tag

The <service> tag is used to declare background services that perform long-running tasks without a
user interface. Services can run even when the app is not visible, making them ideal for operations
like music playback, downloading files, or syncing data. Attributes such as android:enabled and
android:exported determine whether the service can be started by other apps. Without declaring a
service in the manifest, the system will not recognize or start it, which can result in unexpected
failures.

Example:

<service android:name=".MyBackgroundService"

android:enabled="true"

android:exported="false"/>
6. <receiver> Tag

The <receiver> tag declares a broadcast receiver, which is a component that listens for system or
app-specific messages called broadcast intents. Broadcast receivers can react to events such as
device boot, battery changes, network connectivity, or custom app events. You define which
broadcasts the receiver listens for using an intent filter. Broadcast receivers are lightweight, often
running only briefly to respond to an event, and are essential for event-driven programming in
Android.

Example:

<receiver android:name=".MyReceiver">

<intent-filter>

<action android:name="[Link].BOOT_COMPLETED"/>
</intent-filter>

</receiver>
7. <provider> Tag

The <provider> tag declares a content provider, which allows your app to share data with other apps
securely. Content providers manage access to structured data stored in databases, files, or over the
network. Attributes like android:authorities and android:exported define how other apps can access
the data. Without declaring a content provider in the manifest, the system cannot make it available
to other apps or components, limiting data-sharing capabilities.

Example:
<provider

android:name=".MyContentProvider"
android:authorities="[Link]"

android:exported="true"/>
8. <intent-filter> Tag

The <intent-filter> tag specifies what kinds of intents a component can respond to. Activities,
services, and broadcast receivers use intent filters to declare which actions, categories, or data types
they can handle. For example, the main activity uses an intent filter to respond to the MAIN action
and LAUNCHER category, allowing it to start when the app icon is tapped. Intent filters allow your
app to interact with other apps and respond to system-level events safely.
Using Intent Filters in Android:
An Intent Filter in Android is a declaration in the manifest or code that tells the system which intents
a component can respond to. It acts as a gateway, allowing activities, services, or broadcast receivers
to selectively handle external or internal requests. Without an intent filter, a component can only be
invoked explicitly by its class name. Intent filters enable flexible communication between apps and
components, letting your app respond to system events, user actions, or shared data from other
apps. Essentially, they define the capabilities and responsibilities of a component within the Android
ecosystem.

Purpose of Intent Filters

Intent filters serve multiple critical purposes in Android:


1. Component Discovery:

o The Android system uses intent filters to determine which components can handle a
particular intent.

o For example, when a user taps on a web URL, the system looks for activities with
intent filters that support the VIEW action with a matching data scheme.
o This allows users to choose from multiple apps capable of handling the request.

2. Enabling Cross-App Communication:

o Intent filters allow components to receive requests from other apps, not just within
the same app.

o For instance, a file-sharing app can declare an intent filter to receive SEND actions for
images or documents.

o This makes your app integrated and interactive within the larger Android ecosystem.

3. Event Handling:

o Components can respond to system-wide or app-specific events through intent


filters.

o Broadcast receivers use intent filters to filter out irrelevant broadcasts, ensuring only
important events trigger the component.

o This approach supports event-driven programming, improving efficiency and


responsiveness.

Structure of Intent Filters

An intent filter is declared within a component in [Link] and typically consists of three
main elements:

1. Action: Defines the type of operation the component can handle (e.g., VIEW, SEND, MAIN).

2. Category: Provides additional information about the role or context of the component (e.g.,
LAUNCHER, DEFAULT, BROWSABLE).

3. Data: Specifies the type of data or URI the component can handle (e.g., http, mailto, or
image/*).
Permissions in Android:
In Android, permissions are a security mechanism that protects user privacy and sensitive device
data. They restrict apps from accessing resources such as the camera, location, contacts, or internet
unless the user explicitly grants access. Permissions ensure that apps cannot perform malicious or
unauthorized operations on the device. Android uses a combination of manifest-declared
permissions and runtime permissions (for newer Android versions) to enforce this security. Without
proper permissions, many app features cannot function.
Purpose of Permissions

1. Protect User Privacy:


o Permissions prevent apps from accessing sensitive data, like contacts, messages, or
location, without consent.

o This ensures that personal information is not exposed to other apps or external
entities.

2. Control Device Access:

o Some system features, such as the camera, microphone, or storage, require explicit
permissions to prevent unauthorized usage.

o Permissions provide a controlled environment where apps can access only what they
need.
3. Enhance App Security:

o By restricting access to sensitive APIs, permissions reduce the risk of malware or data
leaks.

o Android enforces these checks at both install-time and runtime, depending on the
permission type.

Declaring Permissions in Manifest

Before accessing sensitive resources, apps must declare the required permissions in
[Link].

Example:

<uses-permission android:name="[Link]" />

<uses-permission android:name="[Link].ACCESS_FINE_LOCATION" />

<uses-permission android:name="[Link]" />


 INTERNET: Allows the app to access network resources.

 ACCESS_FINE_LOCATION: Provides access to precise location data.

 CAMERA: Enables the app to use the device camera.

Manifest declarations tell the system what the app intends to use, prompting the user during
installation (for older Android versions) or at runtime (for Android 6.0+).
Runtime Permissions (Android 6.0 and above)

Starting from Android 6.0 (Marshmallow), permissions are divided into:

1. Normal Permissions: Automatically granted at install-time; do not require explicit approval.

o Example: Access to the internet.

2. Dangerous Permissions: Require explicit approval from the user at runtime, because they
grant access to sensitive resources.

o Example: CAMERA, LOCATION, MICROPHONE.

Example: Requesting Camera Permission at Runtime


if (checkSelfPermission([Link])

!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{[Link]}, 1);

 checkSelfPermission(): Checks if the permission is already granted.

 requestPermissions(): Prompts the user to grant the permission.

 1: Request code used to identify the permission request in the callback.

You might also like