BCA & BSc[IT] SEM-6 ANDROID
BCA & BSc[IT&CA] SEM -6
CS-35 MOBILE APPLICATION
DEVELOPMENT IN ANDROID
USING KOTLIN UNIT-2
RIDDHI N. SIDDHPURA
Page | 1
BCA & BSc[IT] SEM-6 ANDROID
Q. Introduction of Android.
Android is an open source and Linux-based Operating System for mobile
devices such as smartphones and tablet computers. Android was developed by
the Open Handset Alliance, led by Google, and other companies.
Android offers a unified approach to application development for mobile
devices which means developers need to develop only for Android, and their
applications should be able to run on different devices powered by Android.
The first beta version of the Android Software Development Kit (SDK) was
released by Google in 2007, whereas the first commercial version, Android 1.0,
was released in September 2008.
On June 27, 2012, at the Google I/O conference, Google announced the next
Android version, 4.1 Jelly Bean. Jelly Bean is an incremental update, with the
primary aim of improving the user interface, both in terms of functionality and
performance.
The source code for Android is available under free and open source software
licenses. Google publishes most of the code under the Apache License version
2.0 and the rest, Linux kernel changes, under the GNU General Public License
version 2.
Features of Android
Android is a powerful operating system competing with Apple 4GS and support
great features. Few of them are listed below:
# Feature Description
Android OS basic screen provides a beautiful and
1 Beautiful UI
intuitive user interface.
Android provides facility to connect mobile to mobile,
2 Connectivity
mobile to network using Bluetooth and Wi-Fi.
SQLite, a lightweight relational database, is used for
3 Storage
data storage purposes.
Page | 2
BCA & BSc[IT] SEM-6 ANDROID
# Feature Description
Media
4 Supports MIDI, WAV, JPEG, PNG, GIF, and BMP.
support
5 Messaging Supports SMS and MMS.
Based on the open-source WebKit layout engine,
6 Web browser coupled with Chrome's V8 JavaScript engine
supporting HTML5 and CSS3.
Android has native support for multi-touch which was
7 Multi-touch initially made available in handsets such as the HTC
Hero.
User can jump from one task to another and same
8 Multi-tasking
time various applications can run simultaneously.
Resizable Widgets are resizable, so users can expand them to
9
widgets show more content or shrink them to save space.
Multi-
10 Support single direction and bi-directional text.
Language
Google Cloud Messaging (GCM) is a service that let
developers send short message data to their users on
11 GCM
Android devices, without needing a proprietary sync
solution.
A technology that let apps discover and pair directly,
12 Wi-Fi Direct
over a high bandwidth peer-to-peer connection.
A popular NFC-based technology that let users
Android
13 instantly share, just by touching two NFC-enabled
Beam
phones together.
Android Applications
• Android applications are usually developed in the Java language using
the Android Software Development Kit.
• Once developed, Android applications can be packaged easily and sold
out either through a store such as Google Play or the Amazon Appstore.
• Android powers hundreds of millions of mobile devices in more than 190
countries around the world. It's the largest installed base of any mobile
Page | 3
BCA & BSc[IT] SEM-6 ANDROID
platform and is growing fast. Every day more than 1 million new Android
devices are activated worldwide.
Q. The open handset alliance
The Open Handset Alliance (OHA) is a business alliance of 84 technology
companies, led by Google, that was formed in 2007 to develop open standards
for mobile devices. Its primary achievement is the development and promotion
of the Android mobile operating system. The OHA includes members from
various sectors, such as handset manufacturers (e.g., HTC, Samsung),
semiconductor companies (e.g., Qualcomm, Intel), and mobile network
operators (e.g., T-Mobile).
Purpose and goals
• Accelerate mobile innovation: By combining the resources of its
member companies, the OHA aims to speed up innovation in the mobile
industry.
• Develop open standards: The alliance works to create and promote
open standards for mobile devices, with a focus on the Android
platform.
• Improve the consumer experience: The ultimate goal is to offer
consumers a better, less expensive, and richer mobile experience.
• Promote Android: The group is committed to commercially deploying
handsets, developing applications, and supporting the expansion of the
Android platform.
Key members
The OHA is a diverse group of companies that came together to support the
Android platform. Key members include:
• Google: The alliance leader and creator of Android
• HTC: A prominent handset manufacturer
Page | 4
BCA & BSc[IT] SEM-6 ANDROID
• Samsung: Another major player in the mobile industry
• Intel: A semiconductor company
• Motorola: A mobile phone manufacturer
• Qualcomm: A key provider of mobile chips and technology
• T-Mobile: A major mobile network operator
Q. Android Architecture
Android operating system is a stack of software components which is roughly
divided into five sections and four main layers as shown below in the
architecture diagram.
Page | 5
BCA & BSc[IT] SEM-6 ANDROID
Linux kernel
At the bottom of the layers is Linux - Linux 2.6 with approximately 115 patches.
This provides basic system functionality like process management, memory
management, device management like camera, keypad, display etc. Also, the
kernel handles all the things that Linux is really good at, such as networking
and a vast array of device drivers, which take the pain out of interfacing to
peripheral hardware.
Libraries
On top of Linux kernel there is a set of libraries including open-source Web
browser engine WebKit, well known library libc, SQLite database which is a
useful repository for storage and sharing of application data, libraries to play
and record audio and video, SSL libraries responsible for Internet security etc.
Android Runtime
This is the third section of the architecture and available on the second layer
from the bottom. This section provides a key component called Dalvik Virtual
Machine which is a kind of Java Virtual Machine specially designed and
optimized for Android.
The Dalvik VM makes use of Linux core features like memory management and
multithreading, which is intrinsic in the Java language. The Dalvik VM enables
every Android application to run in its own process, with its own instance of
the Dalvik virtual machine.
The Android runtime also provides a set of core libraries which enable Android
application developers to write Android applications using standard Java
programming language.
Application Framework
The Application Framework layer provides many higher-level services to
applications in the form of Java classes. Application developers are allowed to
make use of these services in their applications.
Page | 6
BCA & BSc[IT] SEM-6 ANDROID
Applications
You will find all the Android application at the top layer. You will write your
application to be installed on this layer only. Examples of such applications are
Contacts Books, Browser, Games, etc.
Q. The android platform
Google first publicly announced Android in November 2007 but was released
on 23 SEPTEMBER 2008 to be exact.
The first device to bring Android into the market was the HTC Dream with the
version Android 1.0. Since then, Google released a lot of android versions
such as Apple Pie, Banana Bread, Cupcake, Donut, Éclair, Froyo, Gingerbread,
Jellybeans, Kitkat, Lollipop, marshmallow, Nougat, Oreo, etc. with extra
functionalities and new features.
API
Code Name Version level Release date
September 23,
- Android 1.0 1
2008
- Android 1.1 2 February 9, 2009
Cupcake Android 1.5 3 April 30, 2009
September 15,
Donut Android 1.6 4
2009
Eclair Android 2.0 - 2.1 5-7 October 26, 2009
Froyo Android 2.2 - 2.2.3 8 May 20, 2010
Gingerbread Android 2.3 - 2.3.4 9-10 December 6, 2010
Page | 7
BCA & BSc[IT] SEM-6 ANDROID
API
Code Name Version level Release date
Android 3.0.x -
Honeycomb 11 - 13 February 22, 2011
3.2.x
Ice Cream
Android 4.0 - 4.0.4 14 - 15 October 18, 2011
Sandwich
Jelly Bean Android 4.1 - 4.1.2 16 - 18 July 9, 2012
Kitkat Android 4.4 - 4.4.4 19 July 9, 2012
Lollipop Android 5.0 - 5.1 21 - 22 October 17, 2014
Marshmallow Android 6.0 - 6.0.1 23 October 5, 2015
Nougat Android 7.0 - 7.1 24 - 25 August 22, 2016
Oreo Android 8.0 26 August 21, 2017
Pie Android 9.0 27 August 6, 2018
Android Q Android 10.0 29 September 3, 2019
Android 11 Android 11.0 30 September 8, 2020
Snow Cone Android 12.0 - 12.1 31-32 October 4, 2021
Tiramisu Android 13 33 August 15, 2022
Upside Down Cake Android 14 34 October 4, 2023
Vanilla Ice Cream Android 15 35 May 15, 2024
Page | 8
BCA & BSc[IT] SEM-6 ANDROID
Q. Programming Languages used in Developing Android
Applications.
1. Java
2. Kotlin
Developing the Android Application using Kotlin is preferred by Google, as
Kotlin is made an official language for Android Development, which is
developed and maintained by JetBrains.
Previously before Java is considered the official language for Android
Development. Kotlin is made official for Android Development in Google I/O
2017.
Advantages of Android Development
• The Android is an open-source Operating system and hence
possesses a vast community for support.
• The design of the Android Application has guidelines from Google,
which becomes easier for developers to produce more intuitive user
applications.
• Fragmentation gives more power to Android Applications. This
means the application can run two activities on a single screen.
• Releasing the Android application in the Google play store is easier
when it is compared to other platforms.
Disadvantages of Android Development
• Fragmentation provides a very intuitive approach to user experience
but it has some drawbacks, where the development team needs
time to adjust to the various screen sizes of mobile smartphones
that are now available in the market and invoke the particular
features in the application.
• The Android devices might vary broadly. So the testing of the
application becomes more difficult.
• As the development and testing consume more time, the cost of the
application may increase, depending on the application's complexity
and features.
Page | 9
BCA & BSc[IT] SEM-6 ANDROID
Q. Android SDK
Android SDK stands for Android Software Development Kit which is
developed by Google for Android Platform. With the help of Android SDK, we
can create android Apps easily.
Android SDK is a collection of libraries and Software Development tools that
are essential for Developing Android Applications. Whenever Google releases
a new version or update of Android Software, a corresponding SDK also
releases with it.
Components of Android SDK
Android SDK Components play a major role in the Development of Android
applications. Below are the important components:
1. Android SDK Tools
Android SDK tool is an important component of Android SDK. It consists of a
complete set of development and debugging tools. Below are the SDK
developer tools:
• Android SDK Build tool.
• Android Emulator.
• Android SDK Platform-tools.
• Android SDK Tools.
2. Android SDK Build-Tools
Android SDK build tools are used for building actual binaries of Android App.
The main functions of Android SDK Build tools are built, debug, run and test
Android applications. The latest version of the Android SDK Build tool
is 30.0.3. While downloading or updating Android in our System, one must
ensure that its latest version is download in SDK Components.
3. Android Emulator
An Android Emulator is a device that simulates an Android device on your
system. Suppose we want to run our android application that we code. One
option is that we will run this on our Android Mobile by Enabling USB
Debugging on our mobile. Another option is using Android Emulator. In
Android Emulator the virtual android device is shown on our system on which
we run the Android application that we code.
Page | 10
BCA & BSc[IT] SEM-6 ANDROID
In Android Virtual Emulator all functions that are feasible on real Android
mobile is works on virtual Device like:
• phone calls, text messages.
• stimulate different network speeds.
• specify the location of a device
4. Android SDK Platform-tools
Android SDK Platform-tools is helpful when we are working on Project and
they will show the error messages at the same time. It is specifically used for
testing. It includes:
• Android Debug Bridge (ADB), is a command-line tool that helps to
communicate with the device. It allows us to perform an action such
as Installing App and Debugging App etc.
5. Android SDK Tools
Android SDK tool is a component of SDK tool. It consists of a set of tools
which and other Utilities which are crucial for the development of Android
Application. It contains the complete set of Debugging and Development
tools for android.
Q. Building a sample android application
1. Set up Android Studio:
• Download and install Android Studio from the official Android
Developers website. This IDE is essential for Android development.
2. Create a New Project:
• Open Android Studio.
• On the Welcome screen, select "New Project."
• Choose a project template, such as "Empty Activity," and click "Next."
• Configure your project:
o Name: Give your application a name (e.g., "MyFirstApp").
o Package name: This is usually automatically generated based on
your name.
o Save location: Choose where to save your project.
o Language: Select "Kotlin."
Page | 11
BCA & BSc[IT] SEM-6 ANDROID
o Minimum SDK: Choose the lowest Android version your app will
support.
• Click "Finish." Android Studio will set up your project.
3. Explore Project Files:
• [Link]:
This is your main Kotlin file where you'll write the logic for your app's
main screen.
• activity_main.xml:
This XML file defines the layout of your app's main screen (the user
interface).
• [Link]:
This file contains essential information about your app, like permissions
and components.
4. Modify the Layout (activity_main.xml):
• Open activity_main.xml.
• You'll likely see a TextView with "Hello World!" already present.
• You can customize this text or add other UI elements like buttons or
images using the Design view or by directly editing the XML
5. Run Your App:
• Connect an Android device to your computer with USB debugging
enabled, or use an Android Virtual Device (AVD) created in Android
Studio.
• Click the "Run" button (green play icon) in the toolbar.
• Select your connected device or AVD and click "OK."
Android Studio will build and install your app, and you should see your
"Welcome to my first app!" message on the device or emulator.
Page | 12
BCA & BSc[IT] SEM-6 ANDROID
Q. Anatomy of an android application
1) [Link]:
Every project in Android includes a manifest file, which
is [Link], stored in the root directory of its project hierarchy.
The manifest file is an important part of our app because it defines the
structure and metadata of our application, its components, and its
requirements.
This file includes nodes for each of the Activities, Services, Content Providers
and Broadcast Receiver that make the application and using Intent Filters and
Permissions, determines how they co-ordinate with each other and other
applications.
2) Kotlin+Java:
The Java folder contains the Java source code files. These files are used as a
controller for controlled UI (Layout file). It gets the data from the Layout file
Page | 13
BCA & BSc[IT] SEM-6 ANDROID
and after processing that data output will be shown in the UI layout. It works
on the backend of an Android application.
3) drawable:
A Drawable folder contains resource type file (something that can be drawn).
Drawables may take a variety of file like Bitmap (PNG, JPEG), Nine Patch,
Vector (XML), Shape, Layers, States, Levels, and Scale.
4) layout:
A layout defines the visual structure for a user interface, such as the UI for an
Android application. This folder stores Layout files that are written in XML
language. You can add additional layout objects or widgets as child elements
to gradually build a View hierarchy that defines your layout file.
5) mipmap:
Mipmap folder contains the Image Asset file that can be used in Android
Studio application. You can generate the following icon types like Launcher
icons, Action bar and tab icons, and Notification icons.
6) [Link]:
located inside [Link] file contains color resources of the Android
application. Different color values are identified by a unique name that can
be used in the Android application program.
7) [Link](Module: app): This defines the module-specific build
configurations. Here you can add dependencies what you need in your
Android application.
Q. Android terminologies
Core Android Concepts:
• Android OS: The Linux-based operating system developed by Google for
mobile devices.
• APK (Android Package Kit): The file format used to distribute and install
Android applications.
• Android Runtime (ART): The application runtime environment
responsible for compiling and executing app code.
Page | 14
BCA & BSc[IT] SEM-6 ANDROID
• SDK (Software Development Kit): A collection of tools, libraries,
documentation, and samples necessary for developing Android
applications.
• API (Application Programming Interface): A set of protocols, routines,
and tools for building software applications, defining how software
components should interact.
• Activity: A single screen in an Android application with a user interface.
• Service: A component that runs in the background to perform long-
running operations without a user interface.
• Content Provider: Manages access to a structured set of data, enabling
data sharing between applications.
• Broadcast Receiver: A component that responds to system-wide
broadcast announcements (e.g., battery low, SMS received).
• Intent: An abstract description of an operation to be performed, used
for inter-component communication.
• Manifest File ([Link]): An XML file that describes the
essential characteristics of an app and defines its components.
Development Tools and Technologies:
• Android Studio:
The official Integrated Development Environment (IDE) for Android
application development.
• Gradle:
A build automation system used to manage dependencies and build
Android projects.
• Kotlin:
A modern, statically typed programming language officially supported by
Google for Android development.
• Java:
A widely used programming language historically used for Android
development.
• XML (Extensible Markup Language):
Page | 15
BCA & BSc[IT] SEM-6 ANDROID
Used for defining user interface layouts and other structured data in
Android.
• ADB (Android Debug Bridge):
A command-line tool for communicating with an Android device or
emulator.
• AVD (Android Virtual Device) / Emulator:
A software-based virtual device that runs on your computer, simulating
an Android device.
• Logcat:
A logging utility in Android Studio used to view system messages and
app-specific logs.
User Interface Elements:
• Widget: Small, interactive application components that can be
embedded in other application components (e.g., home screen widgets).
• Notification: Alerts that draw the user's attention to an app event
without interrupting their current activity.
• Layout: The structure of the user interface in an Android activity or
fragment.
Android Enterprise Terminologies:
• BYOD (Bring Your Own Device):
Personally owned devices used for work, typically with a work profile.
• Work Profile:
A separate, secure profile on a device that isolates work apps and data
from personal data.
• Fully Managed Device:
A corporate-owned device fully controlled by the organization for work
purposes.
• Dedicated Device:
A fully managed device configured for a specific, limited set of tasks
(e.g., kiosk mode).
Page | 16
BCA & BSc[IT] SEM-6 ANDROID
• Application context, Activities, Services, Intents
Q. What is Context in Android?
Android Applications are popular for a long time and it is evolving to a greater
level as users' expectations are that they need to view the data that they
want in an easier smoother view.
Hence, the android developers must know the important terminologies
before developing the app. In Android Programming we generally come
across the word Context.
Looking at this definition we come across two things:
• The Context tells us about the surrounding information.
• It is very important to understand the environment which we want
to understand.
Similarly when we talk about Android Programming Context can be understood
as something which gives us the Context of the current state of our
application. We can break the Context and its use into three major points:
• It allows us to access resources.
• It allows us to interact with other Android components by sending
messages.
• It gives you information about your app environment.
Types of Context in Android
There are mainly two types of Context that are available in Android.
1. Application Context
2. Activity Context
"Application" context is tied to the application itself and remains alive as long
as the application is running. This means that it can be used across multiple
activities, and is useful for accessing global resources and classes that are not
tied to any specific activity, such as shared preferences or database helpers.
Functionalities Provided by Application Context
• Resource Access ? It provides access to application resources such as
layouts, dimensions, strings through Resource class.
Page | 17
BCA & BSc[IT] SEM-6 ANDROID
• Application level - information access ? It provides information related to
the application such as package name, application name, application
version through Package Manager class.
• Application-level-Broadcasts ? It is used to send and receive application-
level broadcasts using registerReceiver() and sendBroadCast() methods.
• Resource Caching ? It uses resources such as layouts and drawables to
improve the application performance.
When you use any "Activity" context, it is tied to the activity that you are
currently in. This means that if the activity is destroyed, the context will also be
destroyed.
An activity context should be used when you need access to resources or
classes that are tied to a specific activity, such as views or resources that are
specific to that activity.
Functionalities Provided by Activity Context
• Launching Intent ? It is used to start a new activity or services using
startActivity() or startActivityForResult() method.
• Resource Access ? It provides access to resources such as strings, layouts
and images through getResources() method.
• View Inflation ? Activity Context is used to inflate views with the help of
LayoutInflator.
• Dialog Creation ? It is used to create Alert Dialog Box and Progress Dialog
Box.
• Action Bar ? It is used to manage Action Bar such as setting title, icons and
navigation.
Activity Context Application Context
Activity Context has a shorter life
Application Context is created when the
cycle than Application Context. It is
application starts and remains till the
created and destroyed with the
application gets terminated.
Activity.
Page | 18
BCA & BSc[IT] SEM-6 ANDROID
Application Context has a longer life
Activity Context has a shorter life
cycle and remains in the memory
cycle and can be destroyed with the
throughout the lifetime of an
activity.
application.
Application Context is available to the
Activity Context is limited to current
entire application including all activities
Activity such as Fragments and Views.
and their components.
Q. Android activity life cycle
An Activity is the fundamental building block of an Android app, representing a
single screen with which users can interact. To manage the various states an
Activity can be in, Android provides a lifecycle that consists of several callback
methods. These methods are invoked at different points in the Activity’s life,
allowing you to perform specific actions based on the current state.
Lifecycle Methods
There are seven key lifecycle methods that you can override in your Activity
class: key lifecycle methods are -
1. onCreate()
This method is called when the activity is first created. It is responsible for
initializing the activity’s UI, such as inflating the layout and finding the views.
2. onStart()
This method is called when the activity becomes visible to the user. It is a good
place to start animations and other visual changes.
Page | 19
BCA & BSc[IT] SEM-6 ANDROID
3. onResume()
This method is called when the activity becomes the foreground activity. It is
the state in which the user can interact with the activity. This is where you
should register any listeners or start any services that need to be running while
the activity is in the foreground.
Page | 20
BCA & BSc[IT] SEM-6 ANDROID
4. onPause()
This method is called when the activity is no longer the foreground activity. It is
a good place to unregister listeners, save any data that needs to be saved, and
stop any services that don’t need to be running in the background.
5. onStop()
This method is called when the activity is no longer visible to the user. It is a
good place to stop animations and other visual changes.
6. onDestroy()
This method is called when the activity is about to be destroyed. It is a good
place to release any resources and clean up any remaining data.
It’s important to note that an activity can also be in a “stopped” state if it is
temporarily obscured by another activity, but it will still retain its state and not
be destroyed.
In this case, the onStop() method will be called, but not onDestroy(). The
onRestart() method will be called when the activity becomes visible again.
Q. Services in Android
• Services in Android are a special component that facilitates an
application to run in the background in order to perform long-running
operation tasks.
• The prime aim of a service is to ensure that the application remains
active in the background so that the user can operate multiple
applications at the same time.
Page | 21
BCA & BSc[IT] SEM-6 ANDROID
• A user-interface is not desirable for android services as it is designed
to operate long-running processes without any user intervention. A
service can run continuously in the background even if the application
is closed or the user switches to another application.
• Further, application components can bind itself to service to carry
out inter-process communication(IPC) . There is a major difference
between android services and threads, one must not be confused
between the two.
• Thread is a feature provided by the Operating system to allow the
user to perform operations in the background. While service is
an android component that performs a long-running operation about
which the user might not be aware of as it does not have UI.
Types of Android Services
1. Foreground Services:
• Services that notify the user about its ongoing operations are termed
as Foreground Services.
• Users can interact with the service by the notifications provided about
the ongoing task. Such as in downloading a file, the user can keep track
of the progress in downloading and can also pause and resume the
process.
Page | 22
BCA & BSc[IT] SEM-6 ANDROID
2. Background Services:
• Background services do not require any user intervention. These
services do not notify the user about ongoing background tasks and
users also cannot access them.
• The process like schedule syncing of data or storing of data fall under
this service.
3. Bound Services:
• This type of android service allows the components of the application
like activity to bound themselves with it.
• Bound services perform their task as long as any application
component is bound to it.
More than one component is allowed to bind themselves with a service at a
time. In order to bind an application component with a
service bindService() method is used.
The Life Cycle of Android Services :
• In android, services have 2 possible paths to complete its life cycle
namely Started and Bounded.
1. Started Service (Unbounded Service):
• By following this path, a service will initiate when an application
component calls the startService() method.
• Once initiated, the service can run continuously in the background even
if the component is destroyed which was responsible for the start of
the service. Two option are available to stop the execution of service:
1. By calling stopService() method,
2. The service can stop itself by using stopSelf() method.
2. Bounded Service:
• It can be treated as a server in a client-server interface. By following
this path, android application components can send requests to the
service and can fetch results.
• A service is termed as bounded when an application component binds
itself with a service by calling bindService() method.
Page | 23
BCA & BSc[IT] SEM-6 ANDROID
To stop the execution of this service, all the components must unbind
themselves from the service by using unbindService() method.
• To carry out a downloading task in the background, the startService()
method will be called. Whereas to get information regarding the
download progress and to pause or resume the process while the
application is still in the background, the service must be bounded with
a component which can perform these tasks.
Fundamentals of Android Services
A user-defined service can be created through a normal class which is
extending the class Service .
Further, to carry out the operations of service on applications, there are
certain callback methods which are needed to be overridden .
The following are some of the important methods of Android Services:
Methods Description
onStartCommand() The Android service calls this method when a
component(eg: activity)
Page | 24
BCA & BSc[IT] SEM-6 ANDROID
Methods Description
requests to start a service using startService(). Once
the service is started,
it can be stopped explicitly using stopService() or
stopSelf() methods.
This method is mandatory to implement in android
service and is invoked
whenever an application component calls the
bindService() method in order to
onBind() bind itself with a service. User-interface is also
provided to communicate
with the service effectively by returning an IBinder
object.
If the binding of service is not required then the
method must return null.
The Android system invokes this method when all the
onUnbind() clients
get disconnected from a particular service interface.
Once all clients are disconnected from the particular
onRebind() interface of service and
there is a need to connect the service with new
clients, the system calls this method.
Whenever a service is created either using
onStartCommand() or onBind(),
onCreate() the android system calls this method. This method is
necessary to perform
a one-time-set-up.
When a service is no longer in use, the system
onDestroy() invokes this method
just before the service destroys as a final clean up
call. Services must
Page | 25
BCA & BSc[IT] SEM-6 ANDROID
Methods Description
implement this method in order to clean up
resources like registered listeners,
threads, receivers, etc.
Q. Android Intents
• In Android, it is quite usual for users to witness a jump from one
application to another as a part of the whole process.
• for example, searching for a location on the browser and witnessing a
direct jump into Google Maps or receiving payment links in Messages
Application (SMS) and on clicking jumping to PayPal or GPay (Google
Pay).
• This process of taking users from one application to another is achieved
by passing the Intent to the system.
• Intents , in general, are used for navigating among various activities
within the same application, but note, is not limited to one single
application.
• i.e., they can be utilized from moving from one application to another
as well.
Intents could be Implicit, for instance, calling intended actions, and explicit as
well, such as opening another activity after some operations like onClick or
anything else. Below are some applications of Intents:
1. Sending the User to Another App
2. Getting a Result from an Activity
3. Allowing Other Apps to Start Your Activity
Important Method of Intent and their Description
Page | 26
BCA & BSc[IT] SEM-6 ANDROID
Methods Description
This is to launch a new activity or get an
[Link]()
existing activity to be action.
This is to start a new service or deliver
[Link]()
instructions for an existing service.
This is to deliver the message to broadcast
[Link]()
receivers.
Types of Android Intents
There are two types of intents in android
1. Implicit
2. Explicit
Implicit Intent
• Implicit Intent doesn't specify the component. In such a case, intent
provides information on available components provided by the system
that is to be invoked.
• For example, you may write the following code to view the webpage.
Syntax:
Intent intent=new Intent(Intent.ACTION_VIEW);
[Link]([Link]("[Link]
startActivity(intent);
Explicit Intent
• Explicit Intent specifies the component. In such a case, intent provides
the external class to be invoked.
Syntax:
Intent i = new Intent(getApplicationContext(), [Link]);
startActivity(i);
Page | 27
BCA & BSc[IT] SEM-6 ANDROID
Q. Receiving and Broadcasting Intents
• Broadcast in android is the system-wide events that can occur when the
device starts, when a message is received on the device or when
incoming calls are received, or when a device goes to airplane mode.
• etc. Broadcast Receivers are used to respond to these system-wide
events. Broadcast Receivers allow us to register for the system and
application events, and when that event happens, then the register
receivers get notified. There are mainly two types of Broadcast
Receivers:
1. Static Broadcast Receivers: These types of Receivers are declared in
the manifest file and works even if the app is closed.
2. Dynamic Broadcast Receivers: These types of receivers work only if the
app is active or minimized.
• Since from API Level 26, most of the broadcast can only be caught by the
dynamic receiver, so we have implemented dynamic receivers in our
sample project given below.
• There are some static fields defined in the Intent class which can be used
to broadcast different events. We have taken a change of airplane mode
as a broadcast event, but there are many events for which broadcast
register can be used.
• Following are some of the important system-wide generated intents:-
Description Of
Intent Event
Indicates low
[Link].BATTERY_LOW : battery condition
on the device.
This is broadcast
once after the
[Link].BOOT_COMPLETED
system has finished
booting
Page | 28
BCA & BSc[IT] SEM-6 ANDROID
Description Of
Intent Event
To perform a call to
[Link] someone specified
by the data
Indicates that the
[Link].DATE_CHANGED
date has changed
Indicates that the
[Link] device has been a
reboot
The mobile
network or wifi
[Link].CONNECTIVITY_CHANGE
connection is
changed(or reset)
This indicates that
airplane mode has
[Link].ACTION_AIRPLANE_MODE_CHANGED
been switched on
or off.
The two main things that we have to do in order to use the broadcast receiver
in our application are:
Creating the Broadcast Receiver:
class AirplaneModeChangeReceiver:BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
// logic of the code needs to be written here
}
}
Page | 29
BCA & BSc[IT] SEM-6 ANDROID
Registering a BroadcastReceiver:
IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {
// receiver is the broadcast receiver that we have registered
// and it is the intent filter that we have created
registerReceiver(receiver,it)
}
Q. Android Manifest File and its common settings
• The [Link] file is a critical XML file located at the root of
every Android project that describes essential information about the app
to the Android operating system and Google Play.
• It acts as a blueprint, defining the app's structure, components,
permissions, and hardware/software requirements.
Key Purposes
The manifest file serves several vital functions:
• App Identification: It provides a unique package name
(e.g., [Link] ), version code, and version name to manage
and identify the app.
• Component Declaration: All app components (activities, services,
broadcast receivers, and content providers) must be declared here for
the system to run them.
• Permission Specification: It outlines the permissions the app needs to
access sensitive user data or protected system features (e.g., Internet
access, camera, contacts).
• Device Compatibility: It declares the hardware and software features
required by the app (e.g., a camera, specific API levels), which helps
Google Play filter the app for compatible devices.
Page | 30
BCA & BSc[IT] SEM-6 ANDROID
• Intent Handling: It uses intent filters to specify which types of intents a
component can respond to, enabling interaction with other apps and the
system.
• Metadata and Configuration: It specifies metadata such as the app's
icon, label, and theme.
1. manifest
• The main component of the [Link] file is known as
manifest. Additionally, the packaging field describes the activity class's
package name.
• It must contain an <application> element with the xmlns:android and
package attribute specified.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="[Link]
xmlns:tools="[Link]
package="[Link]">
<!-- manifest nodes -->
<application>
</application>
</manifest>
2. uses-sdk
• It is used to define a minimum and maximum SDK version by means of
an API Level integer that must be available on a device so that our
application functions properly, and the target SDK for which it has been
designed using a combination of minSdkVersion, maxSdkVersion, and
targetSdkVersion attributes, respectively. It is contained within the
<manifest> element.
<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="27" />
Page | 31
BCA & BSc[IT] SEM-6 ANDROID
3. uses-permission
• It outlines a system permission that must be granted by the user for the
app to function properly and is contained within the <manifest>
element.
• When an application is installed (on Android 5.1 and lower devices or
Android 6.0 and higher), the user must grant the application
permissions.
<uses-permission
android:name="[Link]"
android:maxSdkVersion="18" />
4. application
• A manifest can contain only one application node. It uses attributes to
specify the metadata for your application (including its title, icon, and
theme).
• During development, we should include a debuggable attribute set to
true to enable debugging, then be sure to disable it for your release
builds.
• The application node also acts as a container for the Activity, Service,
Content Provider, and Broadcast Receiver nodes that specify the
application components.
• The name of our custom application class can be specified using the
android:name attribute.
<application
android:name=".GeeksForGeeks"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@drawable/gfgIcon"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@android:style/[Link]"
android:debuggable="true"
tools:targetApi="31">
<!-- application nodes -->
Page | 32
BCA & BSc[IT] SEM-6 ANDROID
</application>
5. uses-library
• It defines a shared library against which the application must be linked.
This element instructs the system to add the library's code to the
package's class loader.
• It is contained within the <application> element.
<uses-library
android:name="[Link]"
android:required="true" />
6. activity
• The Activity sub-element of an application refers to an activity that
needs to be specified in the [Link] file.
• It has various characteristics, like label, name, theme, launchMode, and
others.
• In the manifest file, all elements must be represented by <activity>. Any
activity that is not declared there won't run and won't be visible to the
system.
• It is contained within the <application> element.
<activity
android:name=".MainActivity"
android:exported="true">
</activity>
7. intent-filter
• It is the sub-element of activity that specifies the type of intent to which
the activity, service, or broadcast receiver can send a response.
• It allows the component to receive intents of a certain type while
filtering out those that are not useful for the component.
• The intent filter must contain at least one <action> element.
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
Page | 33
BCA & BSc[IT] SEM-6 ANDROID
8. action
• It adds an action for the intent-filter. It is contained within the <intent-
filter> element.
<action android:name="[Link]" />
9. category
• It adds a category name to an intent-filter. It is contained within the
<intent-filter> element.
<category android:name="[Link]" />
10. uses-configuration
• The uses-configuration components are used to specify the combination
of input mechanisms that are supported by our application.
• It is useful for games that require particular input controls.
<uses-configuration
android:reqTouchScreen=”finger”
android:reqNavigation=”trackball”
android:reqHardKeyboard=”true”
android:reqKeyboardType=”qwerty”/>
<uses-configuration
android:reqTouchScreen=”finger”
android:reqNavigation=”trackball”
android:reqHardKeyboard=”true”
android:reqKeyboardType=”twelvekey”/>
11. uses-features
• It is used to specify which hardware features your application requires.
• This will prevent our application from being installed on a device that
does not include a required piece of hardware such as NFC hardware, as
follows:
<uses-feature android:name=”[Link]” />
12. permission
• It is used to create permissions to restrict access to shared application
components.
Page | 34
BCA & BSc[IT] SEM-6 ANDROID
• We can also use the existing platform permissions for this purpose or
define your own permissions in the manifest.
<permission
android: name=”[Link].DETONATE_DEVICE”
android:protectionLevel=“dangerous”
android:label=”Self Destruct”
android:description=”@string/detonate_description”>
</permission>
Q. Using intent filter, Permission
intent filters are used to declare an app component's ability to respond to
implicit intents from other apps or the system, while permissions are security
controls that restrict access to sensitive data and system features.
Intent Filters
An intent filter is an expression in an app's manifest file
( [Link] ) that specifies the types of intents a component
(activity, service, or broadcast receiver) would like to receive.
• Function: They allow other apps to start your components with an
implicit intent, enabling interaction and data sharing between different
applications.
• Declaration: Intent filters are declared using the <intent-filter> element
in the manifest, containing <action> , <category> ,
and <data> elements to specify accepted criteria.
• Example Use Cases:
o Declaring an activity can handle a specific data type,
like text/plain , for sharing content.
o Specifying that an activity can display a web page by
handling ACTION_VIEW intents with http scheme data.
Permissions
Page | 35
BCA & BSc[IT] SEM-6 ANDROID
Permissions are a mechanism to protect user privacy and system integrity by
requiring apps to request access to restricted data (like contacts or location)
and actions (like using the camera).
• Function: They provide controls that increase user awareness and limit
an app's capabilities.
• Declaration: You declare the permissions your app needs in the manifest
using the <uses-permission> element, for example: <uses-permission
android:name="[Link].READ_CONTACTS" /> .
Types of Permissions
• Install-time Permissions: These are generally automatically granted by
the system when the user installs the app.
• Runtime Permissions (Dangerous Permissions): For access to sensitive
data (location, camera, microphone, contacts, etc.), your app must
request permission from the user at runtime, while the app is running.
The user sees a system dialog and can choose to grant or deny the
request.
• Special Permissions: These cover specific system-level operations and
require the user to explicitly grant permission through a dedicated
settings screen.
Requesting Permissions
1. Declare in Manifest: List all necessary permissions in
your [Link] file.
2. Check at Runtime: Before using a feature that requires a dangerous
permission, check if the permission is already granted.
3. Request Permission: If not granted, use
the requestPermissions() method to prompt the user with the system
dialog.
4. Handle the Response: Override
the onRequestPermissionsResult() method to handle the user's
decision.
Page | 36
BCA & BSc[IT] SEM-6 ANDROID
Interaction Between Filters and Permissions
Permissions can interact with intent filters in a few ways:
• Component Access Control: You can protect an app component itself
(e.g., an activity or content provider) with a permission, so only apps
with that specific permission can interact with it, regardless of the intent
filter.
• Google Play Filtering: Google Play automatically filters the apps visible
to a user based on the features implied by the permissions requested in
the manifest. For example,
requesting [Link] without specifying the feature
is optional ( android:required="false" ) will hide your app from devices
without a camera.
Q. Managing Application resources in a hierarchy & Working with
different types of resources
• Apart from coding for the application, you take care of various
other resources like static content that your code uses, such as bitmaps,
colors, layout definitions, user interface strings, animation instructions, and
more. These resources are always maintained separately in various sub-
directories under res/ directory of the project.
MyProject/
app/
manifest/
[Link]
java/
[Link]
res/
drawable/
[Link]
layout/
activity_main.xml
[Link]
Page | 37
BCA & BSc[IT] SEM-6 ANDROID
values/
[Link]
[Link]. Directory & Resource Type
1 anim/
XML files that define property animations. They are saved in res/anim/
folder and accessed from the [Link] class.
2 color/
XML files that define a state list of colors. They are saved in res/color/
and accessed from the [Link] class.
3 drawable/
Image files like .png, .jpg, .gif or XML files that are compiled into
bitmaps, state lists, shapes, animation drawable. They are saved in
res/drawable/ and accessed from the [Link] class.
4 layout/
XML files that define a user interface layout. They are saved in
res/layout/ and accessed from the [Link] class.
5 menu/
XML files that define application menus, such as an Options Menu,
Context Menu, or Sub Menu. They are saved in res/menu/ and accessed
from the [Link] class.
6 raw/
Arbitrary files to save in their raw form. You need to
call [Link]() with the resource ID, which
is [Link] to open such raw files.
7 values/
XML files that contain simple values, such as strings, integers, and
colors. For example, here are some filename conventions for resources
you can create in this directory −
[Link] for resource arrays, and accessed from the [Link] class.
[Link] for resource integers, and accessed from
the [Link] class.
[Link] for resource boolean, and accessed from the [Link] class.
[Link] for color values, and accessed from the [Link] class.
[Link] for dimension values, and accessed from the [Link] class.
[Link] for string values, and accessed from the [Link] class.
[Link] for styles, and accessed from the [Link] class.
8 xml/
Page | 38
BCA & BSc[IT] SEM-6 ANDROID
Arbitrary XML files that can be read at runtime by
calling [Link](). You can save various configuration files
here which will be used at run time.
Accessing Resources in Code
• When your Android application is compiled, a R class gets generated, which
contains resource IDs for all the resources available in your res/ directory.
You can use R class to access that resource using sub-directory and
resource name or directly resource ID.
Example
To access res/drawable/[Link] and set an ImageView you will use
following code −
ImageView imageView = (ImageView) findViewById([Link]);
[Link]([Link]);
Here first line of the code make use of [Link] to get ImageView
defined with id myimageview in a Layout file.
Second line of code makes use of [Link] to get an image with
name myimage available in drawable sub-directory under /res.
Page | 39