Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
III BCA BIG DATAS Semester – V
Paper 13{B}: MOBILE APPLICATION DEVELOPMENT
Syllabus
UNIT:1
Introduction to Android
Features of Android
Understanding the Android Software Stack(Android Architecture)
Android Application Lifecycle / Android Activity Lifecycle
Views-Layout Android SDK
Android Installation / Android Environment Setup
Building your First android application
Android Manifest file.
UNIT-2
1. Anatomy of an Android Application
2. Android terminologies
3. Creating user interface with basic views
4. Application context
5. Services
6. Intents
7. Linking activities with intents
8. Receiving and Broadcasting intents
9. Using intent filter
10. Permissions
UNIT-3
1. Android User Interface Design Elements
2. User Interface Screen elements
3. Designing User interface with Layouts
4. Drawing and working with Animation
5. Views
6. Input Controls: Buttons, Radio buttons, Toggle Buttons, Checkboxes,
7. Input Events,
8. Menus,
9. Dialog styles and themes
UNIT-4
1. Testing Android Application
2. Publishing Android Application
3. Android Preferences
4. Managing Android Application resources
5. Working with different types of resources
UNIT-5
1. Internal and External storage
2. SQLite databases
3. Sharing data between applications using content provider
4. Andriod network APIs
5. Android web APIs
6. JSON Parsing
7. Android Telephony APIs
8. Google maps
9. GPS Location
10. Sensors in android
11. Bluetooth/Wi-Fi in android
III BCA BD SEMESTER V 1|Page
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
UNIT – 1
What is Mobile Application development?
Mobile application development is a process for building mobile applications that run
on mobile devices
These applications can be either be preinstalled or downloaded & installed by the user
The process requires creating software that can be installed on the device & enabling
backend services for data access through API‟s(Application programming interface)
and testing the application on target devices
Most important mobile application platforms are ios (iphone operating system) from
Apple and Android from google
Ios Apple‟s mobile operating system built specifically for iphones . However Android
runs on mobile devices manufactures by various OEMs(original Equipment
Manufacturer) including google
There are many similarities between the two, both use different software development
kits(SDKs).
What is Android & History of Android?
What is Android:
Android is an open-source mobile operating system primarily designed for
touchscreen mobile devices like smartphones and tablets.
It is based on a modified version of the Linux kernel and other open-source
software.
Android was initially developed by Android Inc., which was later acquired by Google
in 2005.
It provides a rich application framework that allows developers to create innovative
apps and games, primarily using the Java or Kotlin programming languages.
Android apps are distributed via Google Play Store, the official app marketplace.
History of Android?
Here’s a timeline highlighting the major milestones in Android’s development:
1. Android Inc. and Early Days (2003–2005)
Founded in October 2003 by Andy Rubin, Rich Miner, Nick Sears, and Chris White.
Original goal: Build an advanced operating system for digital cameras.
Later pivoted to creating a mobile OS to compete with Symbian and Windows Mobile.
2. Google Acquisition (2005)
Google acquired Android Inc. in August 2005.
Andy Rubin and his team joined Google, and development continued under the radar.
3. Android Announcement and Open Handset Alliance (2007)
In November 2007, Google announced Android as part of the Open Handset Alliance
(OHA).
OHA was a consortium of hardware, software, and telecom companies aimed at promoting open
standards for mobile devices.
4. First Android Release (2008)
Android 1.0 was released in September 2008.
The first commercial Android phone was the HTC Dream (T-Mobile G1).
III BCA BD SEMESTER V 2|Page
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Features of Android:
1. Open Source
Android is developed under the Android Open Source Project (AOSP).
Developers and manufacturers can freely modify the source code to suit their needs.
Encourages innovation and customization (e.g., Samsung’s One UI, Xiaomi’s MIUI).
2. User-Friendly Interface
Clean and intuitive UI design.
Supports touch gestures like swipe, tap, and pinch-to-zoom.
Includes customizable widgets and home screens.
3. Multitasking
Allows multiple apps to run in the background.
Recent apps menu enables easy switching.
Android 7.0+ supports split-screen mode for using two apps side by side.
4. Connectivity Options
Supports a wide range of connectivity features:
o Wi-Fi
o Bluetooth
o NFC (Near Field Communication)
o USB, 4G/5G, GPS
o Hotspot and tethering
5. Google Services Integration
Tight integration with Google apps:
o Gmail, Google Maps, Google Drive, YouTube, Google Assistant, etc.
Google Play Store provides access to over 3 million apps.
6. Notifications
Real-time notifications for messages, emails, updates, etc.
Interactive notifications (e.g., reply to messages directly).
Notification management per app.
7. Security Features
Regular security patches and updates.
App permission manager (control access to camera, mic, etc.).
Google Play Protect scans apps for malware.
Biometric authentication: fingerprint, face unlock.
8. Customization
Change home screens, icons, fonts, and wallpapers.
Use third-party launchers for a personalized look.
Widgets for clocks, weather, news, etc.
9. Multilingual Support
Supports over 100 languages.
Can easily switch between languages and input methods (keyboards).
10. Storage and File Management
Internal and external storage support (SD card).
Built-in file manager for managing files and folders.
Supports cloud backup via Google Drive.
11. Voice Commands & AI Integration
Google Assistant for hands-free actions like setting reminders, calling, or checking
weather.
AI used in features like smart replies, adaptive brightness, and predictive app usage.
III BCA BD SEMESTER V 3|Page
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Understanding the Android Software Stack(Android Architecture)
The Android software stack/ Android Architecture is a set of layers that work together
to run Android applications and manage hardware and system resources.
It includes everything from the low-level hardware interaction to the high-level
applications you use daily.
1. Linux Kernel Layer (Bottom Layer)
This is the foundation of the Android platform. A modified version of the Linux kernel provides
core system services, including:
Security: Handles security between applications and the system.
Memory Management: Efficiently manages memory allocation and deallocation for
processes.
Process Management: Manages the lifecycle of processes and allocates resources.
Network Stack: Handles network communication.
Device Drivers: Contains all the low-level drivers for various hardware components like
the display, camera, Bluetooth, Wi-Fi, keypad, and flash memory. This provides an
abstraction layer between the hardware and the upper software layers.
III BCA BD SEMESTER V 4|Page
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
2. Hardware Abstraction Layer (HAL)
The HAL sits just above the Linux kernel. It's a crucial layer that allows Android to be
hardware-agnostic.
Standard Interfaces: The HAL provides standard interfaces that expose device hardware
capabilities (e.g., camera, Bluetooth, GPS) to the higher-level Java API framework.
Modular Libraries: It consists of multiple library modules, each implementing an
interface for a specific type of hardware component. When a framework API needs to
access hardware, the Android system loads the relevant HAL module. This ensures that
hardware vendors can implement their drivers without affecting the higher layers of the
OS.
3. Android Runtime (ART) & Native C/C++ Libraries Layer
This layer is critical for running Android applications.
Android Runtime (ART):
o ART is the runtime environment that executes app bytecode (DEX files). It
replaced the older Dalvik Virtual Machine.
o Ahead-of-Time (AOT) Compilation: ART compiles app bytecode into native
machine code before the app runs, resulting in faster app startup times and
improved performance. It also includes Just-in-Time (JIT) compilation.
o Optimized Garbage Collection (GC): ART includes an optimized garbage collector
for efficient memory management.
o Each Android app runs in its own process with its own instance of ART,
enhancing security and stability.
Native C/C++ Libraries:
Many core Android system components and services (including parts of ART and
HAL) are built using native code.
These libraries are written in C and C++ and provide crucial functionalities.
Examples include:
o libc: The standard C library.
o Media Framework: For playing and recording audio and video formats.
o SQLite: A lightweight database for data storage.
o OpenGL ES (Open Graphics Library for Embedded Systems): For 2D and 3D
graphics rendering.
o WebKit: The web rendering engine used by Android's browser.
o FreeType: For font rendering.
o SSL (Secure Sockets Layer): For internet security.
o Surface Manager: Manages access to the display subsystem and composites
application surfaces.
4. Application Framework Layer
This layer provides the essential APIs (Application Programming Interfaces) and
services that developers use to build Android applications. It's written in Java and
exposes the entire feature set of the Android OS.
The important blocks of application framework are
Activity Manager: Manages the lifecycle of applications and provides a common
navigation back stack.
Content Providers: Enable apps to access data from other applications (e.g., Contacts,
Calendar) or to share their own data.
III BCA BD SEMESTER V 5|Page
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Resource Manager: Provides access to non-code resources such as localized strings,
graphics (bitmaps), and layout files.
Notification Manager: Enables all apps to display custom alerts in the status bar.
View System: A rich and extensible UI system that allows developers to build an app's
user interface using elements like lists, grids, text boxes, and buttons.
Package Manager: Manages information related to installed application packages.
Location Manager: Deals with location awareness capabilities.
Telephony Manager: Provides access to telephony services.
5. Applications Layer (Top Layer)
This is the topmost layer of the Android software stack, where all user-facing applications
reside.
System Apps: Android comes with a set of core applications pre-installed, such as the
phone dialer, messaging app, camera, gallery, contacts, and web browser. These apps
also provide key capabilities that developers can access from their own applications.
Third-Party Apps: This layer also includes all the applications that users download from
the Google Play Store or other sources. Each application runs in its own secure sandbox
environment, which aids in security and stability.
Android Application Lifecycle
The Android application lifecycle refers to the different states an application goes
through from the time it's launched until it's closed, either by the user or the system.
These states are managed through a series of callback methods that allow developers to
manage resources, handle user interactions, and save application state.
Activity Lifecycle:
onCreate(): Called when the activity is first created. This is where you initialize the
activity, such as inflating the layout and initializing UI elements.
onStart(): Called when the activity is becoming visible to the user.
onResume(): Called when the activity is ready to start interacting with the user.
onPause(): Called when the current activity is being paused and the previous activity is
being resumed. This is where you should save any user data or persistent changes
before the activity is stopped.
onStop(): Called when the activity is no longer visible to the user.
onDestroy(): Called before the activity is destroyed. This is the final chance to clean up
resources.
onRestart(): Called when an activity is stopped and is about to be started again.
III BCA BD SEMESTER V 6|Page
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Application Class Lifecycle:
The Application class, which represents the base class for maintaining global
application state, has its own lifecycle.
It is instantiated before any other components and exists for the entire duration of the
application process.
The Application class is created when the application is launched and is destroyed only
when the application is closed or killed by the system.
Importance of Understanding the Lifecycle:
Resource Management:
Properly managing resources within each state helps prevent memory leaks and
ensures smooth performance.
User Experience:
Handling state transitions gracefully ensures a consistent and intuitive user
experience.
Error Prevention:
Understanding the lifecycle helps developers avoid common issues like crashes due to
incorrect resource management or improper handling of state changes.
Code Maintainability:
A well-structured lifecycle implementation leads to cleaner, more maintainable code.
III BCA BD SEMESTER V 7|Page
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Views-Layout in Android
In Android SDK, "Views" and "Layouts" are the fundamental building blocks for creating
user interfaces.
The views represents a single UI elements (such as a button or text field) while a Layout
is a container for grouping multiple views together to arrange them in a specific way.
1. Views (Widgets)
What they are: Views are the basic UI components that users can see and interact with.
They are small rectangular boxes on the screen responsible for drawing content and
handling user events (like taps, swipes, etc.).
Examples of common Views:
o TextView: Displays static text.
o EditText: Allows users to input and edit text.
o Button: Triggers an action when clicked.
o ImageView: Displays images.
o CheckBox: Allows multiple selections.
III BCA BD SEMESTER V 8|Page
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Attributes: Views have various attributes that define their appearance and behavior, such as:
android:id: A unique identifier for the view.
android:layout_width and android:layout_height: Define the width and height of the
view (e.g., wrap_content to fit content, match_parent to fill the parent, or specific
dimensions like 100dp).
android:text: The text displayed by a TextView or Button.
android:src: The image source for an ImageView.
android:hint: A placeholder text for an EditText.
android:padding: Space between the view's content and its edges.
android:layout_margin: Space around the view, outside its borders.
2. ViewGroups (Layouts)
What they are: ViewGroups are invisible containers that hold and organize other Views
and/or other ViewGroups. They define the structure and arrangement of the UI
elements within them. ViewGroups are essentially "layouts."
Examples of common Layouts:
o LinearLayout: Arranges child views in a single row (horizontal) or single column
(vertical).
Useful for forms, toolbars, or sequential arrangements.
Key attribute: android:orientation (either horizontal or vertical).
o RelativeLayout: Positions child views based on their relationship to each other or
to the parent container.
Declaring Layouts:
You can declare your UI layouts in two primary ways:
1. XML (Recommended): This is the most common and preferred method. You define your
Views and ViewGroups in XML files (typically located in the res/layout directory).
Android Studio provides a visual Layout Editor (drag-and-drop) to make this easier,
along with a code editor for direct XML manipulation.
2. Programmatically (at runtime): You can also create and manipulate View and
ViewGroup objects directly in your Kotlin or Java code. While possible, it's generally less
readable and maintainable for complex UIs compared to XML.
Android Installation, Building you First Android application
Step 1 - System Requirements
For Windows:
Microsoft Windows 7/8/10 (32-bit or 64-bit)
4 GB RAM minimum, 8 GB RAM recommended (plus 1 GB for the Android Emulator)
2 GB of available disk space minimum, 4 GB recommended (500 MB for IDE plus 1.5 GB
for Android SDK and emulator system image)
1280 x 800 minimum screen resolution
III BCA BD SEMESTER V 9|Page
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Step 2. Download Android Studio
1. Go to the official Android Studio download page: https://developer.android.com/studio/
2. Click the "Download Android Studio" button.
3. Read and accept the terms and conditions.
4. Choose the appropriate installer for your operating system (Windows .exe, macOS .dmg,
Linux .tar.gz).
3. Install Android Studio
The installation process is generally straightforward and guided by a wizard.
For Windows:
Step1: After the downloading has finished, open the file from downloads and run it. It will
prompt the following dialog box.
Click on next. In the next prompt, it'll ask for a path for installation. Choose a path and hit
next.
Step 4: It will start the installation, and once it is completed, it will be like the image shown
below.
Click on next.
III BCA BD SEMESTER V 10 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Step 5: Once " Finish " is clicked, it will ask whether the previous settings need to be
imported [if the android studio had been installed earlier], or not. It is better to choose the
'Don't import Settings option'.
Step 6: This will start the Android Studio.
Meanwhile, it will be finding the available SDK components.
Step 7: After it has found the SDK components, it will redirect to the Welcome dialog box.
III BCA BD SEMESTER V 11 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Click on Next .
Choose Standard and click on Next. Now choose the theme, whether the Light theme or
the Dark one. The light one is called the IntelliJ theme whereas the dark theme is
called Dracula . Choose as required.
III BCA BD SEMESTER V 12 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Android SDK
The Android SDK, or Software Development Kit, is a comprehensive collection of tools,
libraries, documentation, and sample code that developers use to create applications for
the Android operating system.
It's essentially the "toolkit" provided by Google that enables you to build, test, and debug
Android apps.
Components of Android SDK:
SDK Platforms: Each new version of Android (e.g., Android 14, Android 15) comes with its
own SDK Platform. This package contains the necessary files to compile your app for that
specific Android version, ensuring it can utilize the latest features and APIs.
Android SDK Tools:
Android SDK tools is an important component of Android SDK. It consists of a
complete set of development and debugging tools.
Android SDK Build Tools: These tools are crucial for compiling your app's source
code and resources into an Android Package (APK). An APK is the file format used
to distribute and install Android applications.
Android Emulator: A virtual device that runs on your computer, mimicking a real
Android device. This allows you to test your applications on various screen sizes,
Android versions, and hardware configurations without needing a physical device.
Emulators can simulate incoming calls, messages, network speeds, and device
location.
Android SDK Platform Tools: This is a set of command-line tools that interact
directly with Android devices and emulators. The most important one is Android
Debug Bridge (ADB), which allows you to install apps, debug applications,
transfer files, and execute various commands on connected devices. Another
notable tool is fastboot, used for flashing custom system images onto devices.
Libraries: The SDK includes extensive libraries that provide pre-built code
modules and APIs (Application Programming Interfaces) for common tasks.
These libraries save developers time and effort by offering functionalities for
networking, data storage, UI development, accessing device features (camera,
GPS, sensors), and integrating with Google services (Maps, Firebase,
Analytics).
Documentation: Comprehensive documentation for all the APIs, tools, and
guidelines for Android development. This is an invaluable resource for
developers to understand how to use the various components and best
practices.
Sample Code and Tutorials: Practical examples and tutorials that demonstrate
how to implement specific features or build different types of Android
applications.
Debugger: Tools that help developers identify and fix issues in their code. This
allows for step-by-step execution, inspection of variables, and tracing program
flow.
SDK Manager: A tool (often integrated into Android Studio) that allows you to
easily view, download, update, and uninstall different SDK components and
Android platform versions.
III BCA BD SEMESTER V 13 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Features:
Write Code: Using languages like Java or Kotlin, leveraging the provided libraries and APIs.
Build Applications: Compiling source code and resources into an APK.
Test Applications: Using the emulator or physical devices, with debugging tools to identify
and resolve issues.
Optimize Performance: Tools for profiling and analyzing app performance.
Deploy Applications: Preparing apps for distribution on platforms like the Google Play Store.
Android Manifest File
What is an Android Manifest File?:
Android manifest is an XML file That contains essential information about our android
App.
It serves as a blueprint that defines various aspects of the app's behavior, requirements,
and interactions with the Android operating system and other applications.
Purpose of the Android Manifest File
The Android Manifest file, typically named AndroidManifest.xml, is a critical file in
Android app development. Its primary purposes are:
App Identification:
The manifest file identifies the app to the Android operating system, providing
essential information such as the app's package name and version code.
This information is crucial for the system to manage and update the app.
Permissions:
It specifies the permissions required by the app to access device resources or interact
with other apps. Android enforces these permissions to protect user privacy and
security.
App Components:
The manifest defines the app's components, including activities, services, broadcast
receivers, and content providers. These components are the building blocks of an
Android app.
Intent Filters:
It declares intent filters for components, which specify the types of intents they can
respond to. This allows other apps and the system to interact with the app's
components.
App Configuration:
Various app configurations, such as screen orientations, supported screen sizes, and
minimum Android API levels, are specified in the manifest.
App Icon and Label:
The manifest defines the app's launcher icon and label, which appear on the device's
home screen.
III BCA BD SEMESTER V 14 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Structure of the Android Manifest File:
The structure of the file usually takes the form of a code-like instruction and looks
usually like this:
Key Elements:
III BCA BD SEMESTER V 15 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
UNIT-2
Anatomy of Android Application/CORE COMPONERNTS
The anatomy of an Android application refers to its fundamental building blocks and
how they interact to create a functional app.
These components are loosely coupled by the application manifest
file AndroidManifest.xml that describes each component of the application and how
they interact.
There are following four main components that can be used within an
Android application.
Activities:
An Activity represents a single screen with a user interface.
It's the primary entry point for user interaction. Most apps consist of multiple activities,
each handling a specific user task or screen
Activities have a lifecycle (created, started, resumed, paused, stopped, destroyed) that
the Android system manages. Developers override lifecycle methods to manage
resources and UI state.
An activity is implemented as a subclass of Activity class as follows
Services :
A Service is a component that performs long-running operations in the background
without a user interface.
They're used for tasks that shouldn't interrupt the user, such as playing music, fetching
data from a network, or performing computations.
A service is implemented as a subclass of Service class as follows –
Broadcast Receivers 📡
A Broadcast Receiver is a component that responds to system-wide broadcast
announcements.
These broadcasts can originate from the system (e.g., low battery, screen on/off,
incoming SMS) or from other applications.
Broadcast receivers typically don't have a UI and are used to perform small, quick tasks
in response to events.
III BCA BD SEMESTER V 16 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each
message is broadcaster as an Intent object.
Content Providers 📊
A Content Provider manages a shared set of application data.
They provide a structured and secure way for apps to access and share data (e.g.,
contacts, calendar events, media files) with other applications, or to store data for their
own use.
They abstract the underlying data storage mechanism (e.g., SQLite database, file system,
web).
A content provider is implemented as a subclass of ContentProvider class and must
implement a standard set of APIs that enable other applications to perform
transactions.
Additional Components:
Android terminologies
III BCA BD SEMESTER V 17 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Android development involves many specific terms. Here's a breakdown of some key Android
terminologies:
Core Components:
Activity: A single, focused thing that the user can do. Most apps consist of multiple activities.
Service: A component that runs in the background to perform long-running operations or to
perform work for remote processes. Services do not provide a user interface.
Broadcast Receiver: A component that enables the system to deliver events to the app, even if
the app is not currently running.
Content Provider: A component that supplies data from one application to others on request.
They are like a database interface, allowing structured access to data.
Intent: An abstract description of an operation to be performed. It's a messaging object used to
request an action from another app component. Intents can be used to start an activity, start a
service, or deliver a broadcast.
Fragment: A modular section of an activity, which has its own lifecycle, input events, and can
be added or removed while the activity is running. Fragments allow for more flexible UI
designs, especially on larger screens like tablets.
Project Structure & Tools 🛠
APK (Android Package Kit): The package file format used by the Android operating system
for distribution and installation of mobile applications and middleware. It's essentially the
executable file for Android apps.
AndroidManifest.xml: An essential file in every Android app project. It describes the
fundamental characteristics of the app and defines each of its components. It declares
permissions the app needs, hardware features it uses, etc.
Gradle: An advanced build automation system used by Android. It automates the process of
compiling, packaging, and signing your Android application.
SDK (Software Development Kit): A set of software development tools and libraries required
to develop applications for a specific platform, in this case, Android.
ADB (Android Debug Bridge): A versatile command-line tool that lets you communicate with
an emulator instance or connected Android device. It's used for installing apps, debugging, and
accessing device shells.
Emulator: A software application that mimics the hardware and software of an Android
device, allowing developers to test their apps on a virtual device without needing a physical
one.
Android Studio: The official Integrated Development Environment (IDE) for Android
application development, based on IntelliJ IDEA.
III BCA BD SEMESTER V 18 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
UI & Design Concepts 🎨
Layout: Defines the structure for the user interface in your app, such as a LinearLayout or
RelativeLayout. It's essentially a container for UI elements.
View: The basic building block of user interface components. Things like TextView (for
displaying text), Button, ImageView are all views.
ViewGroup: An invisible container that holds other Views and ViewGroups, and defines their
layout properties. LinearLayout and RelativeLayout are examples of ViewGroups.
Material Design: A design language developed by Google, providing guidelines for visual,
motion, and interaction design across platforms and devices.
XML (extensible Markup Language): Often used to define the layout of Android user
interfaces.
Context in Android:
In Android development, Context is a fundamental and crucial concept. It's an interface
that provides access to application-specific resources and classes, as well as up-calls for
application-level operations such as launching activities, broadcasting and receiving
intents, and accessing preferences.
Essentially, Context is like a handle to the environment your application is running in. It
allows your app to interact with the Android system and its own resources.
What Context Provides?
Resources: The resources such as layouts, images and strings which are stored in
resource objects are accessed through the Context.
System Services: it provides access to system services such as Power Manager,
Notification Manager and Location Manager.
Preferences: The preference is used to store and retrieve data in key value pair which
can be accessed through Context.
Asset Manager: It is used to access raw asset files that are packaged with the
application.
Database: it provides access to the database used by the application.
How Does this Work?
1. It is the Context of the current/active state of the application.
Usually, the app got multiple screens like display/inquiry/add/delete screens(A general
requirement of a basic app). So when the user is searching for something, the Context is an
inquiry screen in this case.
2. It is used to get information about the activity and application.
The inquiry screen's Context specifies that the user is in inquiry activity, and he/she can
submit queries related to the app
III BCA BD SEMESTER V 19 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
3. It is used to get access to resources, databases, shared preferences, etc.
Via Rest services, API calls can be consumed in android apps. Rest Services usually hold
database data and provide the output in JSON format to the android app. The Context for the
respective screen helps to get hold of database data and the shared data across screens
4. Both the Activity and Application classes extend the Context class.
In android, Context is the main important concept and the wrong usage of it leads to memory
leakage. Activity refers to an individual screen and Application refers to the whole app and
both extend the Context class.
Types of Context in Android
There are mainly two types of Context that are available in Android.
1. Application Context and
2. Activity Context
The Overall view of the App hierarchy looks like the following:
Application Context: This Context is tied to the lifecycle of the entire application. It's a
singleton instance and remains the same throughout the app's lifetime.
How to get it: getApplicationContext()
When to use it: When you need a Context that outlives the current activity or service,
such as for singleton classes, database operations, or anything that needs to persist
across the app's lifecycle. Using it prevents memory leaks that can occur if you hold onto
an Activity Context longer than the Activity itself.
Activity Context: This Context is tied to the lifecycle of a specific Activity. Each Activity has its
own Context instance.
How to get it: this (within an Activity), getContext() (within a Fragment),
view.getContext() (from a View).
When to use it: When you need to perform UI-related operations, inflate layouts, or
interact with resources specific to that particular Activity. This is the most common
Context used in UI components.
III BCA BD SEMESTER V 20 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Creating user interface with basic views
Creating user interfaces (UIs) with basic views in Android involves using XML layout files to define the UI
components (like buttons, text boxes, and images) that appear on the screen.
Basic Views in Android
View Description
TextView Displays text to the user.
EditText Allows the user to input text.
Button Triggers an action when clicked.
ImageView Displays images or icons.
CheckBox Lets users select multiple options.
RadioButton Used for single selection within a RadioGroup.
Switch A toggle switch for ON/OFF actions.
ProgressBar Shows a loading indicator.
Example Program:
OUTPUT:
III BCA BD SEMESTER V 21 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Services In Android:
In Android, a Service is an application component that can perform long-running
operations in the background without a user interface.
Unlike an Activity, a Service doesn't interact with the user directly.
Services are ideal for tasks that need to continue even when the user switches to
another app or the app's UI is no longer visible.
What Services are Used For:
Services are commonly used for:
Playing music in the background: A music player app can use a service to play music
even when the user navigates away from the app.
Downloading files: A service can handle large file downloads, allowing the user to
continue using the app or other apps while the download progresses.
Performing network operations: Fetching data from a server, syncing data, or
sending messages.
Monitoring data: Such as tracking location updates or continuously checking for new
messages.
Interprocess Communication (IPC): Allowing different components or even different
applications to communicate with each other.
Types of Android Services
Foreground
A foreground service performs an operation that is noticeable to the user.
They must display a persistent notification in the notification bar, informing the user
that the service is actively running. This notification usually cannot be dismissed unless
the service is stopped.
Foreground services are less likely to be killed by the Android system even when
memory is low because they are considered important to the user experience.
They are typically used for tasks like playing music, recording audio, or providing
navigation directions.
Background Services:
A background service performs operations that are not directly noticed by the user.
These services are more susceptible to being killed by the Android system, especially if
the app is not in the foreground and system resources are low.
Bound Services
A service is "bound" when an application component calls bindService().
Bound services provide a client-server interface, allowing components to interact with
the service, send requests, receive results, and even perform Interprocess
Communication (IPC).
III BCA BD SEMESTER V 22 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
A bound service runs only as long as at least one client component is bound to it. When
all clients unbind, the system destroys the service.
Example: A music player service that allows an Activity to control playback (play,
pause, skip).
Service Lifecycle
The Android Service lifecycle defines how an Android system manages a Service
component from its creation to its destruction. Understanding this lifecycle is crucial
for correctly initializing resources, performing background operations, and releasing
resources efficiently to prevent memory leaks and optimize app performance.
Services can operate in two primary ways, each with a slightly different lifecycle
path: started and bound. A service can also be both started and bound
simultaneously.
Service Lifecycle Methods
Regardless of whether a service is started or bound, the following core lifecycle
methods are invoked at different stages:
onCreate():
o This is the first method called when the service is created.
o It's used for one-time setup that needs to happen before the service begins its
work (e.g., initializing variables, creating background threads).
o If the service is already running, this method will not be called again.
onDestroy():
o This is the last callback the service receives before it's destroyed.
o It's where you should release all remaining resources (e.g., stop threads,
unregister listeners, close network connections) to prevent memory leaks.
III BCA BD SEMESTER V 23 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Started Service Lifecycle
A started service is initiated when another component (like an Activity) calls startService().
It typically performs a single operation and then stops itself or is stopped by another
component.
onStartCommand(Intent intent, int flags, int startId):
o Called each time a client calls startService().
o This is where the service begins its main work.
o The intent contains the data passed by the client.
o The return value of this method (e.g., START_STICKY, START_NOT_STICKY,
START_REDELIVER_INTENT) indicates how the system should handle the
service if it gets killed.
o A started service must explicitly stop itself by calling stopSelf() or be stopped
by another component calling stopService().
Lifecycle Flow for a Started Service:
1. onCreate(): (if the service is not already running)
2. onStartCommand(): (called for each startService() request)
3. Service runs its tasks.
4. stopSelf() or stopService(): (to stop the service)
5. onDestroy(): (when the service is no longer in use)
Bound Service Lifecycle:
A bound service is created when another component (a client) calls bindService(). It provides
a client-server interface, allowing components to interact with the service and perform
interprocess communication (IPC). A bound service runs as long as there are active clients
bound to it.
onBind(Intent intent):
o Called when another component binds to the service using bindService().
o This method must return an IBinder interface that clients use to communicate
with the service.
o If you don't want to allow binding, return null.
onUnbind(Intent intent):
o Called when all clients have disconnected from the service.
o You can return true from this method if you want onRebind() to be called later if
new clients bind to the service.
onRebind(Intent intent):
o Called when new clients connect to the service after onUnbind() has been
called. This only happens if onUnbind() returned true.
Lifecycle Flow for a Bound Service:
1. onCreate(): (if the service is not already running)
2. onBind(): (when the first client binds)
3. Clients interact with the service.
4. onUnbind(): (when all clients unbind, if applicable)
5. onRebind(): (if new clients rebind after unbind, and onUnbind() returned true)
6. onDestroy(): (when the service is no longer needed and all clients have unbound)
III BCA BD SEMESTER V 24 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Intent in Android:
In Android, an Intent is a messaging object that you can use to request an action from
another app component. It's like a messenger that carries a message (data) and a
destination (component) to perform a specific task.
What is an Intent?
An Intent serves as a powerful communication mechanism between different
components of an Android application, and even between different applications.
It's essentially a description of an operation to be performed. When you create an
Intent, you're telling the Android system what you want to do.
Key Use Cases of Intents
Intents are fundamental to Android development and are primarily used for the following:
Starting an Activity: This is the most common use. You can launch a new screen
(Activity) within your app or an Activity in another app. For example, opening a web
page in a browser, playing a video, or displaying an image.
Starting a Service: You can use an Intent to initiate a background operation using a
Service. For example, downloading a file or playing music in the background.
Delivering a Broadcast: Intents can be used to send broadcast messages to the system
or other apps. For example, when the battery is low, a broadcast is sent to notify
interested applications.
Communicating with a ContentProvider: While not directly used to interact with a
ContentProvider (which is typically done via ContentResolver), Intents can indirectly
lead to operations that involve a ContentProvider, such as when selecting an image from
the gallery.
Types of Intents
There are two main types of Intents in Android:
1. Explicit Intents
An explicit Intent specifies the component to be started by its full class name. You use explicit
Intents when you know exactly which component you want to launch. They are typically used
for starting components within the same application.
Example:
Java
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
Here, SecondActivity.class explicitly tells the system to start SecondActivity.
In Android, an Intent is a messaging object that you can use to request an action from another
app component. It's like a messenger that carries a message (data) and a destination
(component) to perform a specific task. 🚀
What is an Intent?
An Intent serves as a powerful communication mechanism between different components of an
Android application, and even between different applications.
Key Use Cases of Intents
Intents are fundamental to Android development and are primarily used for the following:
Starting an Activity: This is the most common use. You can launch a new screen
(Activity) within your app or an Activity in another app. For example, opening a web
page in a browser, playing a video, or displaying an image.
III BCA BD SEMESTER V 25 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Starting a Service: You can use an Intent to initiate a background operation using a
Service. For example, downloading a file or playing music in the background.
Delivering a Broadcast: Intents can be used to send broadcast messages to the system
or other apps. For example, when the battery is low, a broadcast is sent to notify
interested applications.
Communicating with a ContentProvider: While not directly used to interact with a
ContentProvider (which is typically done via ContentResolver), Intents can indirectly
lead to operations that involve a ContentProvider, such as when selecting an image from
the gallery.
Types of Intents
There are two main types of Intents in Android:
1. Explicit Intents
An explicit Intent specifies the component to be started by its full class name. You use explicit
Intents when you know exactly which component you want to launch. They are typically used
for starting components within the same application.
Example:
Java
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
Here, SecondActivity.class explicitly tells the system to start SecondActivity.
2. Implicit Intents
An implicit Intent does not name a specific component. Instead, it declares a general action to
be performed, allowing the Android system to find the appropriate component (or
components) to handle that action. Implicit Intents are often used to request an action from
another application.
Example:
Java
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.google.com"));
startActivity(intent);
In this example, ACTION_VIEW is a general action, and http://www.google.com is the data.
Components of an Intent
An Intent object can contain the following information:
Component Name (for Explicit Intents): The fully qualified class name of the target
component (e.g., com.example.myapp.MyActivity).
Action: A string that specifies the general action to be performed (e.g., ACTION_VIEW,
ACTION_SEND, ACTION_CALL).
Data: The URI (Uniform Resource Identifier) of the data to be acted upon, along with its
MIME type. For example, a URI to a contact, a web page, or an image.
Category: A string containing additional information about the kind of component that
should handle the intent. For example, CATEGORY_BROWSABLE means the activity can
be safely launched from a browser.
Extras: A Bundle of key-value pairs that contain additional information needed to
perform the requested action. This is like sending extra parameters along with the main
request. For example, text to share, or a subject line for an email.
III BCA BD SEMESTER V 26 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Flags: These are various flags that modify how the intent is handled. For instance, flags
can specify how an activity should be launched (e.g., creating a new task, clearing the
back stack).
How to Link Activities Using Intents
You primarily link activities using explicit intents, where you explicitly specify the
target activity you want to launch.
1. Create an Intent Object
First, you create an Intent object. In its constructor, you'll typically pass two parameters:
The context (usually this if you're in an Activity, or getApplicationContext()).
The class of the activity you want to start.
2. Call startActivity()
Once you've created the Intent, you pass it to the startActivity() method. This method tells the
Android system to launch the activity specified in the Intent.
3. (Optional) Passing Data to the New Activity
You can also pass data from the current activity to the new activity using the putExtra()
method of the Intent object. Data is passed as key-value pairs using a Bundle.
Sending Data (in MainActivity):
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("key_name", "value"); // Example: passing a string
startActivity(intent);
Receiving Data (in SecondActivity):
In the onCreate() method of SecondActivity, you can retrieve the data using getIntent() and
then various get...Extra() methods.
4. (Optional) Getting a Result Back from the New Activity
If you want the launched activity to return a result to the calling activity, you use
startActivityForResult() instead of startActivity().
Starting Activity for Result (in MainActivity):
Returning a Result (in SecondActivity):
5. Register Activities in AndroidManifest.xml
Every activity you use in your application must be declared in the AndroidManifest.xml file. If
an activity is not declared, the app will crash when you try to launch it.
By following these steps, you can effectively link activities in your Android application
using Intents, enabling seamless navigation and data exchange between different parts of your
app.
Broadcasting Intents
Broadcasting intents means sending out a message that any interested component
(typically a Broadcast Receiver) can pick up. These are used for system events (like
battery low, screen on/off) or custom app-specific events.
How to Broadcast Intents
You can send two main types of broadcasts:
III BCA BD SEMESTER V 27 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
1. Standard Broadcasts
These are asynchronous, meaning they are sent to all registered receivers, but the order of
reception is not guaranteed. They are generally more efficient for system-wide notifications.
2. Ordered Broadcasts
These are synchronous, meaning they are delivered to one receiver at a time, in an order
defined by the receivers' priority (specified in their intent filter, android:priority). Each
receiver can potentially modify the result data or abort the broadcast entirely, preventing it
from reaching subsequent receivers.
Security Considerations for Broadcasts
Explicit Intents for App-Internal Broadcasts: When sending broadcasts within your
own app, consider using explicit intents if possible, or specifying a package.
Local Broadcasts (LocalBroadcastManager): For broadcasts that are strictly within your
own application's process and should not leave it, use LocalBroadcastManager. This is more
efficient and secure as it prevents other apps from receiving or sending these internal
broadcasts.
Permissions in Android:
Android permissions are a fundamental part of the operating system's security and
privacy model.
They control an app's access to sensitive user data and restricted device functionalities.
The goal is to give users control and transparency over what their apps can do.
Why Permissions?
Privacy: Protects user data like contacts, location, photos, microphone recordings, etc.
Security: Prevents malicious apps from performing harmful actions like making calls
without consent, sending SMS messages, or accessing system files.
Transparency: Informs users about the capabilities an app needs before or during its
use.
Workflow for Requesting Runtime Permissions
1. Declare in Manifest: Always declare all necessary permissions in your
AndroidManifest.xml using the <uses-permission> tag, regardless of their protection
level. This tells the system what your app might need.
2. Check Permission Status: Before performing an operation that requires a dangerous
permission, check if your app already has that permission using
ContextCompat.checkSelfPermission().
3. Explain Rationale (if needed): If shouldShowRequestPermissionRationale() returns
true, it means the user previously denied the permission but did not permanently deny
it (by checking "Don't ask again"). In this case, you should display an educational UI
(e.g., a dialog or snackbar) explaining why your app needs the permission for a specific
feature to work. This helps the user understand the value proposition before seeing the
system permission dialog again.
4. Request Permission: Use registerForActivityResult() with
ActivityResultContracts.RequestPermission() (for single permission) or
RequestMultiplePermissions() (for multiple permissions) to trigger the system
permission dialog. This is the recommended modern approach.
III BCA BD SEMESTER V 28 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
5. Handle User Response: In the callback from registerForActivityResult(), check
whether the user granted or denied the permission. Adjust your app's behavior
accordingly. If denied, consider disabling the feature or providing an alternative.
6. Handle Permanent Denial: If the user denies a permission and checks "Don't ask again,"
shouldShowRequestPermissionRationale() will return false on subsequent checks. In this
scenario, you cannot directly prompt the user again.
Types of Permissions:
Android categorizes permissions based on the level of risk they pose to user privacy
and system integrity. This determines how and when the user grants them.
Normal Permissions:
Risk Level: Low risk. They allow access to data or actions that extend beyond an app's
sandbox but pose very little risk to the user's privacy or the operation of other apps.
Granting: Automatically granted by the system at install time if declared in the
AndroidManifest.xml. The user is not prompted at runtime.
Examples: INTERNET (access to the internet), ACCESS_NETWORK_STATE (view
network connection status), VIBRATE (control vibrator).
Runtime Permissions(Dangerous Permissions):
Risk Level: Higher risk. They give apps access to private user data or control over the device
that could negatively impact the user's privacy or device operation.
Granting: Must be explicitly requested by the app at runtime, and the user must grant them
through a system dialog. Users can revoke these permissions at any time from app settings.
Examples (often grouped):
Calendar: READ_CALENDAR, WRITE_CALENDAR
Camera: CAMERA
Contacts: READ_CONTACTS, WRITE_CONTACTS, GET_ACCOUNTS
Microphone: RECORD_AUDIO
Sensors: BODY_SENSORS
SMS: SEND_SMS, RECEIVE_SMS, READ_SMS, RECEIVE_WAP_PUSH, RECEIVE_MMS
Signature Permissions:
Risk Level: Specific to internal app components or shared functionalities within a set of
apps from the same developer.
Granting: Granted automatically by the system at install time only if the requesting
app is signed with the exact same certificate as the app (or OS) that declared the
permission.
Use Case: Used for inter-app communication where you want to restrict access only to
your own applications.
Special Permissions:
III BCA BD SEMESTER V 29 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Risk Level: Very high risk. These permissions give an app significant control over the
device or access to highly sensitive data. They often require the user to navigate to a
special settings screen to grant them.
Granting: User must explicitly grant these, usually through a dedicated system settings
screen, not a standard runtime dialog.
Examples:
SYSTEM_ALERT_WINDOW (Draw over other apps)
WRITE_SETTINGS (Modify system settings)
MANAGE_EXTERNAL_STORAGE
Permission Groups
Android groups related dangerous permissions into "permission groups" (e.g.,
"Location," "Contacts," "Camera").
When a user grants a dangerous permission from a group, all other permissions within
that same group are automatically granted to the app. This simplifies the user
experience by reducing the number of individual prompts.
However, if you request permissions from different groups, the user will be prompted
for each group separately.
III BCA BD SEMESTER V 30 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
UNIT-3
Screen elements used in Android UI design
User Interface elements are the building blocks of apps and websites. They play a crucial
role in creating interactive and user friendly interfaces, allowing users to navigate and interact
with the system.
Different types of UI Design elements:
1. Input Controls:
They are UI design elements that allow users to input information into the
system. They are essential for collecting data and enabling user interactions.
Some common input controls are.
a. Text Fields: Text fields are used to collect textual information from users.
They can be single line or multiline and are often used to entering names,
addresses or comments.
b. Dropdown Menus: Dropdown menus provide users with a list of
options from which they can select one. They are commonly used for
selecting a country, language or category.
c. Checkboxes: Checkboxes allow users to select one or multiple options
from a list. They are often used in forms or settings to enable users to
choose their preferences.
d. Radio buttons: They are a type of selection tool that allows users to
choose only one option from a list of choices.
2. Navigational Components:
Navigational components are UI elements that help users move around the
app or website. They provide users with a clear intuitive way to navigate through
different sections and pages.
Some common navigational components are
a. Menus: Menus provide users with a list of options for accessing different
sections or features of the app or website. They can be displayed as
horizontal or vertical lists, depending on the design.
b. Tabs: Tabs provide users with the ability to move between various
sections or views within an app or website. They are commonly used for
organizing content into categories or providing different perspectives on
the same information.
3. Informational components:
Informational components are UI elements that provide information to
users. They communicate important messages, updates, or instruction to uses.
a. Notifications: Notifications notify users about important events or
updates within the app or website. They can be used to inform users
about new messages, or system errors.
b. Tooltips: Tooltips provide additional information or context when users
hover over or click on certain elements. They can be used to explain the
purpose or functionality of a button, icon, or link.
c. Progress Bars: Progress bars visually indicate the progress of a task or
process. They are commonly used in forms, checkouts, or file uploads to
show users how far they are in completing a specific task.
III BCA BD SEMESTER V 31 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
4. Buttons: buttons are essential UI elements that allow users to perform specific
actions or submit forms. They are typically displayed as shapes with labels and
provide a visual cue to users. Buttons can be designed in various styles and sizes
to fit the overall aesthetic of the interface.
5. Icon: Icons are visual representations used to communicate information or
trigger specific actions. They are commonly used in UI design to enhance the
visual language and provide a quick and intuitive way for users to interact with
the system.
Android Layouts:
Android provides the following view groups or Layouts
Linear Layout:
LinearLayout is one of the most basic layouts in android studio, that arranges multiple
sub-views (UI elements) sequentially in a single direction i.e. horizontal or vertical manner
by specifying the android:orientation attribute.
If one applies android:orientation="vertical" then elements will be arranged one after
another in a vertical manner (i.e. top to bottom) and
If you apply android:orientation="horizontal" then elements will be arranged one after
another in a horizontal manner (i.e. left to right).
Key Features:
Arranges child views linearly (one after another).
Direction can be vertical (top to bottom) or horizontal (left to right).
You can control spacing, alignment, weight distribution, etc.
III BCA BD SEMESTER V 32 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
When to Use:
For simple layouts where views are arranged in a single line.
If you want to evenly distribute space using layout_weight.
Limitations:
Not optimal for complex layouts — consider using ConstraintLayout or RelativeLayout
for better performance.
XML Syntax:
Constraint Layout:
Constraint Layout is a flexible layout that allows views to be positioned using
constraints instead of nesting layouts.
It helps in reducing the view hierarchy and improves performance by a lot.
It is the most popular and recommended layout for designing complex interfaces in
modern Android applications.
Why Use Constraint Layout?
Avoids nested layouts (like nested LinearLayouts or RelativeLayouts).
Optimizes performance by flattening the view hierarchy.
Allows positioning and resizing of views based on constraints to other views or parent.
Basic XML Syntax:
III BCA BD SEMESTER V 33 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Important Constraint Attributes:
Attribute Meaning
Top of view aligned to top of another
layout_constraintTop_toTopOf
view/parent
layout_constraintBottom_toBottomOf Bottom aligned similarly
layout_constraintStart_toStartOf Start edge aligned
layout_constraintEnd_toEndOf End edge aligned
layout_constraintLeft_toLeftOf /
Deprecated; use Start/End
Right_toRightOf
RelativeLayout in Android
RelativeLayout is a ViewGroup that allows you to position child views relative to each other or
to the parent container. It's more flexible than LinearLayout, but less powerful than
ConstraintLayout.
Key Features:
Place views above, below, to the left/right of each other.
Align views with parent edges.
Good for moderately complex layouts.
Basic Syntax:
Limitations:
Can become hard to manage with many views.
Nested relationships can get confusing.
Deprecated in favor of ConstraintLayout in modern apps.
When to Use:
For simple to moderate layouts.
When positioning elements relative to each other is sufficient.
If you're targeting older devices and want backward compatibility.
Frame Layout
III BCA BD SEMESTER V 34 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
In Android, FrameLayout is one of the simplest layout types, mainly used to display a single child
view.
Overview
Purpose: To block out an area on the screen to display a single item.
Behavior:
o All child views are positioned at the top-left corner of the layout by default.
o If you add more than one child, they overlap each other (like stacking).
Common Usage:
o As a container for fragments.
o To place one view on top of another (e.g., an image with text overlay).
o As a placeholder in dynamic UI loading.
Key Points
Extends: ViewGroup
Can contain multiple children, but best for one child for clarity.
Children can be aligned using layout_gravity (e.g., center, bottom, right).
Height/width behavior depends on match_parent, wrap_content, or exact size.
Syntax Example:
Advantages
Simple and lightweight.
Good for overlaying elements.
Ideal for dynamic content (like fragments).
III BCA BD SEMESTER V 35 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Limitations
Not suited for complex UI layouts with multiple views arranged in rows/columns — use
LinearLayout or ConstraintLayout for that.
If multiple children are added, you must manually handle their positions.
Android Table Layout
In Android, TableLayout is a ViewGroup that arranges its child views in rows and columns,
similar to an HTML table.
Overview
Purpose: Organize UI elements in a grid-like structure without requiring explicit row and
column dimensions.
Structure:
o Contains TableRow elements (each row can have one or more child views).
o Each TableRow acts like a horizontal LinearLayout.
Column alignment: All rows share the same column structure.
Key Points
Extends: LinearLayout (with vertical orientation internally).
Children of TableLayout must be TableRow (though technically other views are allowed, but
less common).
Columns are automatically sized based on the largest child in that column.
Can stretch or shrink specific columns using:
o android:stretchColumns
o android:shrinkColumns
Can collapse a column using:
o android:collapseColumns
Advantages
Great for forms and data entry screens.
Easy alignment of labels and fields.
Limitations
Not as flexible for responsive design compared to ConstraintLayout.
Complex tables can get verbose in XML.
Grid Layout:
In Android, GridLayout is a ViewGroup that arranges its children in a rectangular grid of
rows and columns. It’s more flexible and modern than TableLayout because it gives you fine
control over how each cell is occupied.
1. Overview
Purpose: Arrange child views in a grid with defined rows and columns.
Structure:
o You specify the number of rows and columns.
o A child can span multiple rows or columns.
Flexibility: Can control each child’s position and size using layout parameters.
Key Points
Extends: ViewGroup.
Supports rowSpan and colSpan (similar to HTML tables).
Automatically handles alignment (left, right, center) within each cell.
III BCA BD SEMESTER V 36 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Child position is controlled by:
o layout_row
o layout_column
o layout_rowSpan
o layout_columnSpan
o layout_gravity
Advantages
More modern and flexible than TableLayout.
Supports complex layouts without nesting multiple LinearLayouts.
Easy to merge cells using span properties.
Limitations
Slightly more verbose than LinearLayout for simple layouts.
Requires more planning for cell positions.
Drawing and Animations in Android:
Drawing and animations in Android are fundamental to creating engaging and visually rich
user interfaces. Android provides a robust set of APIs that allow developers to draw custom graphics
and bring UI elements to life through various animation techniques.
Drawing in Android
Android's drawing capabilities revolve around the Canvas and Paint classes, along with custom
View components.
1. Custom Views and onDraw():
To draw custom content, you typically extend the View class and override its
onDraw(Canvas) method. The Canvas object represents the drawing surface, and the Paint
object holds information about how the drawing should look (color, stroke width, text size,
etc.).
Canvas Operations
The Canvas class provides a wide range of drawing primitives:
drawRect(): Draws a rectangle.
drawCircle(): Draws a circle.
drawArc(): Draws an arc.
drawLine(): Draws a line.
drawPath(): Draws a custom path (series of lines, curves, etc.).
drawBitmap(): Draws a bitmap image.
drawText(): Draws text.
Paint Properties
The Paint class defines the visual properties of what's being drawn:
Color: setColor(), setARGB()
Style: setStyle(Paint.Style.FILL/STROKE/FILL_AND_STROKE)
Stroke Width: setStrokeWidth()
Text Size: setTextSize()
Text Alignment: setTextAlign()
Animations in Android:
Animation in Android adds motion and interactivity to your app, making the user interface
more dynamic and engaging. Android provides several ways to animate views,
III BCA BD SEMESTER V 37 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Animation types in Android:
View Animation: These are the classic Android animations that manipulate the
position, size, and opacity of a view.
Property Animations(ObjectAnimator/ValueAnimator): The modern animation
framework that lets you animate any property of an object, such as a view’s translation,
rotation, or alpha. Property animation is more flexible and powerful than the traditional
view animation.
Drawable Animations
Frame-by-frame image sequence.
Uses AnimationDrawable.
Physics-based Animations
Spring animations, fling animations for more natural motion.
Available in androidx.dynamicanimation.
Recycler View in Android:
What is RecyclerView?:
Purpose: Efficiently display large or dynamic data collections.
Key Feature: View recycling — only a few view items are created and reused while
scrolling.
Flexibility: Can be customized to behave like a list, grid, or staggered layout using
LayoutManagers.
Introduced in: Android Lollipop (API 21) as part of the AndroidX RecyclerView
library.
Major component of RecyclerView :
RecylerView.Adapter : It provide recylerview to bind the data set to each item view.
Recyclerview.ViewHolder : It is mandatory to apply over recyclerview to draw the UI for
each individual item into list.
RecyclerView.LayoutManager: You have many options for view managing into
recyclerview like
1. For linear data set/ linear view -> Go for LinearLayout Manager
2. For Glid data set / grid view -> Go for GlidLayout Manager
3. For Custom layout view/ Staggered -> Go for StraggerGlidLayoutManager
RecyclerView.ItemDecorator : To decorate each of your view, you can customise your
item/ divider etc.
RecylerView.ItemAnimator : RecyclerView comes up with default animation fetures like
when you add new data or delete a item, it will show a very decent animation.
Internal working of RecyclerView
Let’s understand the mechanism of how the process of recyclerview works with data set and
new view using scrolling up or down.
III BCA BD SEMESTER V 38 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
ViewPort: All visible view item on the screen of recyclerview is part of Android ViewPort. It
varies when screen sized increases or decrease like in the above example viewport size is 3.
Scrap View: The immediate view item of recyclerview that just gone away either from top /
bottom of screen. Also the view that is just moved from view port. This view is not longer going
to display and moving into mechanism to recycle the view with new data.
Recycle View: After getting view into scrap stage it is going to recycler for further new data.
Dirty View: Your old view is recycled and ready to attach with new data.
Binding View: New data is will set over the recycled item view and going to visible into
recyclerview.
Visible View: Visible views are part of android viewport. it may going to scrap view or it may
just came from binding with new data form recylerview.
ListView in Android:
A ListView in Android is a ViewGroup that displays a list of scrollable items in a vertical
list. Each item in the list is represented by a view, and all items are managed by an
adapter.
Key Points
Purpose: To display a large number of items in a vertically scrollable list.
Common Use: Menus, contact lists, chat lists, etc.
Adapter Role: Connects the data source (array, database, etc.) to the ListView for
display.
Main Components
1. ListView – The UI element to display the list.
2. Adapter – Binds data to the list items.
III BCA BD SEMESTER V 39 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
o Examples:
ArrayAdapter
SimpleAdapter
CursorAdapter
BaseAdapter
3. List Item Layout – Defines how each row/item looks.
Important Methods in ListView
setAdapter(Adapter adapter) → Connects adapter to the ListView.
setOnItemClickListener(...) → Detects clicks on list items.
getItemAtPosition(int position) → Gets data at a specific position.
smoothScrollToPosition(int position) → Smoothly scrolls to an item.
Advantages
Easy to implement for simple lists.
Optimized for large datasets using View recycling.
Disadvantages
Limited flexibility compared to RecyclerView.
Harder to handle complex item layouts.
GridView in Android
A GridView in Android is a ViewGroup that displays items in a two-dimensional,
scrollable grid. It’s useful when you need to show data in rows and columns—like a
gallery of images, product listings, or app icons.
Key Points
Purpose: Displays items in a grid (rows & columns).
Adapter: Connects the data (text, images, etc.) to the grid cells.
Scroll: Supports vertical scrolling.
Spacing: You can control spacing between rows and columns.
Main Components
1. GridView – The container that displays items.
2. Adapter – Supplies the data and creates the views for each cell.
o Common choices:
ArrayAdapter
SimpleAdapter
BaseAdapter
3. Grid Item Layout – Defines how each cell looks.
Important XML Attributes
android:numColumns → Number of columns in the grid.
android:verticalSpacing → Space between rows.
android:horizontalSpacing → Space between columns.
android:stretchMode → How columns should be stretched.
Advantages
Perfect for displaying images, icons, or product listings.
Scrolls vertically, making it easy to handle large datasets.
Disadvantages
Less flexible than RecyclerView for complex layouts.
Not as memory-efficient for very large lists.
III BCA BD SEMESTER V 40 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
WebView in Android
A WebView in Android is a view that allows you to display web pages (HTML, CSS,
JavaScript) inside your Android app — basically, it’s like embedding a mini web
browser into your app.
Key Points
Purpose: Show web content directly in the app without opening an external browser.
Use Cases:
o Display your website inside the app.
o Show online documentation or help pages.
o Integrate third-party web tools.
Limitations:
o Needs internet permission for online content.
o Not as powerful as full browsers for complex features.
Steps to Use WebView
1. Add WebView to layout (XML).
2. Enable permissions (if loading online content).
3. Load a URL or HTML content in Java code.
Input Controls in Android:
In Android, input controls are the UI elements that allow users to enter and modify data in
an app — like typing text, selecting options, or toggling settings. They are part of the View
hierarchy and are usually subclasses of EditText, Button, Spinner, etc.
Android provides a variety of input controls. For your UI. The figure below shows some
popular ones.
Button:
Buttons are essential UI elements that allow users to perform specific actions or submit forms.
They are typically displayed as shapes with labels and provide a visual cue to users. Buttons
can be designed in various styles and sizes to fit the overall aesthetic of the interface. These
buttons have three states: normal, disabled, and pressed.
Text field: Use the EditText class to get user input that consists of textual characters, including
numbers and symbols. EditText extends the TextView class, to make the TextView editable.
Checkboxes
Use a set of checkboxes when you want the user to select any number of choices, including
zero choices:
Each checkbox is independent of the other boxes in the set, so selecting one box doesn't
clear the other boxes. (If you want to limit the user's selection to one choice, use radio
buttons.)
III BCA BD SEMESTER V 41 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
A user can clear a checkbox that was already selected.
Users expect checkboxes to appear in a vertical list, like a to-do list, or side-by-side if the
labels are short.
Radio buttons
Use radio buttons when you have two or more options that are mutually exclusive. When the
user selects one, the others are automatically deselected. (If you want to enable more than
one selection from the set, use checkboxes.)
Toggle buttons and switches
A toggle input control lets the user change a setting between on and off. Android provides
the ToggleButton class, which shows a raised button with "OFF" and "ON".
Examples of toggles include the on/off switches for Wi-Fi, Bluetooth, and other options in
the Settings app.
Android also provides the Switch class, which is a short slider that looks like a rocker switch
for on and off. Both are extensions of the CompoundButton class.
Spinner
A Spinner provides a quick way for the user to select one value from a set. The user taps on
the spinner to see a drop-down list with all available values.
Check boxes in android:
Checkboxes in Android are UI elements that allow users to select one or more options
from a set. They are commonly used for settings, preferences, or multiple-choice
selections.
III BCA BD SEMESTER V 42 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
What is a Checkbox?
A Checkbox is a specific type of two-state button that can be either checked (on) or
unchecked (off). Users can tap on a checkbox to toggle its state. When multiple
checkboxes are presented together, users can select any combination of them, unlike
radio buttons where only one option can be selected.
Checkboxes in Android are UI elements that allow users to select one or more options
from a set. They are commonly used for settings, preferences, or multiple-choice
selections.
Key Attributes and Usage
When implementing checkboxes in Android, you'll typically interact with the CheckBox
class in your XML layout files and corresponding Kotlin/Java code. Some key attributes
and usage points include:
o android:text: Sets the text label displayed next to the checkbox.
o android:checked: A boolean attribute to set the initial state of the checkbox (true
for checked, false for unchecked).
o onCheckedChangedListener: This listener is crucial for handling state changes.
You attach this listener to the checkbox to perform actions when its checked state
changes.
Basic Implementation Steps
1. Add CheckBox to Layout (XML): You define the checkbox within your
activity_main.xml (or similar layout file) using the <CheckBox> tag.
Accessibility and Best Practices
Provide Clear Labels: Always use the android:text attribute or contentDescription for
accessibility to clearly describe the purpose of the checkbox.
Group Related Checkboxes: If you have multiple related checkboxes, consider placing
them within a LinearLayout or ConstraintLayout to maintain visual coherence.
Maintain State: If the user's selection needs to persist across app launches or screen
rotations, save the checkbox state using mechanisms like SharedPreferences or a
ViewModel.
Radio buttons in Android:
o Radio buttons in Android are UI elements that allow users to select one option
from a set of mutually exclusive choices. Unlike checkboxes, where multiple
III BCA BD SEMESTER V 43 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
options can be selected, radio buttons ensure that only one selection is active within
a group.
What are Radio Buttons?
A Radio Button is a two-state button that can be either selected (on) or deselected (off).
They are always used in groups, typically within a RadioGroup. When a user selects one radio
button within a RadioGroup, any previously selected radio button in that same group is
automatically deselected. This "one or none" selection behavior is their defining characteristic.
Key Components and Attributes
To implement radio buttons effectively, you'll work with two main components:
1. RadioButton: The individual button element.
2. RadioGroup: A container that groups multiple RadioButton elements together to
enforce the mutual exclusivity.
Common attributes for RadioButton and RadioGroup:
android:text (for RadioButton): Sets the text label displayed next to the radio button.
android:checked (for RadioButton): A boolean attribute to set the initial state of the
radio button (true for selected, false for deselected). Only one radio button in a
RadioGroup should have android:checked="true" initially.
android:orientation (for RadioGroup): Determines how the radio buttons within the
group are arranged (horizontal or vertical).
onCheckedChangeListener (for RadioGroup): This listener is crucial for handling
selection changes within the RadioGroup. You attach this listener to the RadioGroup to
perform actions when a different radio button is selected.
When to Use Radio Buttons
Radio buttons are ideal for:
Mutually exclusive choices: When a user must pick only one option from a predefined
set (e.g., gender, payment method, difficulty level).
Small number of options: Typically best for 2-5 options. For a larger number of
options, consider using a Spinner (dropdown).
Visibility of all options: When all available options should be immediately visible to
the user without needing to open a dropdown.
Accessibility and Best Practices
Clear Labels: Ensure each RadioButton has a clear and concise android:text that
accurately describes the option.
Group Semantically: Always enclose related RadioButton elements within a
RadioGroup to enforce correct behavior and improve accessibility.
Initial Selection: It's good practice to have one radio button pre-selected in a group,
especially if a default choice makes sense for the user. If no default is selected, make
sure your logic handles the case where no option is chosen.
State Persistence: If the user's selection needs to persist (e.g., across app restarts),
save the chosen state using SharedPreferences or a similar data persistence mechanism.
III BCA BD SEMESTER V 44 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Buttons in Android:
o Buttons in Android are fundamental UI elements that allow users to interact with an
application by tapping them to perform an action. They are a primary means of user
input and navigation.
What are Buttons?
o A Button in Android is a view that users can tap to trigger an event or action within
the application. When a button is tapped, it typically provides visual feedback (like a
ripple effect) and then executes a predefined piece of code.
Key Attributes and Usage
When working with Button elements in Android, you'll commonly use the following attributes
in your XML layout and interact with them in your Kotlin/Java code:
android:text: Sets the text displayed on the button. This is often the most important
attribute as it tells the user what the button does.
android:id: A unique identifier for the button, allowing you to reference it in your code.
android:layout_width and android:layout_height: Define the size of the button.
Common values include wrap_content (button resizes to fit its content) and
match_parent (button expands to fill its parent).
android:onClick: (Optional but convenient) Allows you to specify the name of a
method in your Activity that will be called when the button is tapped. This method must
be public, return void, and take a View as its only parameter.
setOnClickListener: The primary programmatic way to handle button taps in your
code. You attach a listener to the button that defines the action to be performed when
clicked.
Basic Implementation Steps
1. Add Button to Layout (XML): You define the button within your layout file (e.g.,
activity_main.xml) using the <Button> tag.
Types of Buttons
Beyond the standard Button, Android offers several specialized button types for different use
cases:
ImageButton: Displays an image instead of text. Useful for icons or graphical buttons.
FloatingActionButton (FAB): A special type of button used for a primary action on a
screen, often circular and floating above other UI elements. (Part of Material Design).
MaterialButton: A more customizable and modern button from Material Design,
offering various styles like outlined, text-only, and contained buttons.
ToggleButton: A button that can be in one of two states (on/off), often represented by
different text or icons.
Switch: Similar to a ToggleButton but provides a more visual "slider" style.
III BCA BD SEMESTER V 45 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Best Practices
Clear and Concise Labels: Ensure button text clearly indicates its action (e.g., "Submit,"
"Save," "Cancel," "Next").
Consistent Placement: Place important action buttons in predictable locations.
Provide Feedback: Use toasts, dialogs, or visual changes to confirm that an action has
been performed.
Disable When Inactive: If a button's action is not currently possible, disable it to
prevent user frustration.
Accessibility: Use contentDescription for ImageButtons to provide a textual description
for screen readers.
Input Events in Android
In Android, input events are actions that occur when the user interacts with the app’s
UI, such as tapping the screen, pressing keys, or touching/dragging on a view.
These events are detected and handled through event listeners or by overriding
specific event-handling methods.
Event Listeners
Event Listener is an interface within the View class that contains one call-back
method.
These methods are going to be called by the Android framework when the View which
is registered with the listener is triggered by user interaction with the item in UI.
Included in the event listener interfaces are the following callback methods:
onClick():
This method is called when the user touches the item or focuses upon the item with the
navigation-keys or trackball and presses the suitable "enter" key or presses down on the
trackball.
onLongClick():
This is called when the user either touches and holds the item, or focuses upon the item with
the navigation-keys or trackball and presses and holds the suitable "enter" key or presses
and holds down on the trackball (for one second).
onFocusChange():
This is called when the user navigates onto or away from the item, using the navigation-keys
or trackball.
onKey():This is called when the user is focused on the item and presses or releases a
hardware key on the device.
onTouch():This is called when the user acts qualified as a touch event, including a press, a
release, or any movement gesture on the screen (within the bounds of the item).
onCreateContextMenu():This is called when a Context Menu is being built (as the result of a
sustained "long click").
Event Listener Registration
In android, Event Registration is the process by which an Event Handler gets
registered with an Event Listener so that the handler is called when the Event Listener
fires the event.
Following are the different ways to register event listeners in our android applications.
III BCA BD SEMESTER V 46 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
By specifying event handlers directly in activity_main.xml file, we can register event
listeners
By using Activity class that implements a listener interface, we can register event
listeners
By using an anonymous class.
Event Handlers
Event Handlers are useful to define several callback methods when we are building
custom components from view. Following are some of the commonly used callback
methods for event handling in android applications.
Method Description
onKeyDown() This method is called when a new key event occurs.
onKeyUp() This method is called when a key up event occurs.
onTrackballEvent() This method is called when a trackball motion event occurs.
onTouchEvent() This method is called when a touch screen motion event occurs.
onFocusChanged() This method is called when the view gains or loses focus.
Menus in Android:
In Android, menus are UI components that provide users with a set of options or actions related to
the current screen or app. They help improve navigation and user experience without cluttering the
main interface.
III BCA BD SEMESTER V 47 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Types of menus
1. Options Menu
Appears when the user clicks the menu button (or overflow icon ⋮ on modern devices).
Typically used for global actions (e.g., Settings, Search).
Defined using XML inside the res/menu/ directory.
Inflated in the onCreateOptionsMenu() method.
2. Context Menu
Appears when the user long-presses on a view.
Used for actions related to a specific item (e.g., Edit, Delete).
Created using registerForContextMenu() and onCreateContextMenu().
3. Popup Menu
Appears anchored to a specific view when triggered (like a small dropdown).
Good for quick actions without changing the current activity.
4. Sub Menu
A menu item that opens a nested menu inside another menu.
Can be used inside Options or Context Menus.
5. Navigation Drawer Menu
A side panel that slides from the left (or right).
Contains app navigation links and actions.
Implemented using NavigationView and DrawerLayout.
6. The app bar
The app bar (also called the action bar) is a dedicated space at the top of
each Activity screen. When you create an Activity from a template (such as Empty
Template), an app bar is automatically included for the Activity.
Menu Type Trigger Use Case
Options Menu Menu/Overflow button Global app actions
Context Menu Long press Actions for specific item
Popup Menu Click on anchor view Quick view-specific actions
Sub Menu Part of another menu Group related actions
Navigation Drawer Swipe from side / hamburger icon Main app navigation
UNIT-IV
III BCA BD SEMESTER V 48 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Android Testing and types of Android Testing
Android Testing is the process of verifying that an Android application works correctly, meets
requirements, and provides a smooth user experience.
It ensures that your app is functional, reliable, secure, and performs well across different devices,
Android versions, and screen sizes.
Why Android Testing is Important
Detect bugs early before release.
Ensure compatibility with multiple devices and OS versions.
Maintain performance under various conditions.
Improve user satisfaction and app ratings.
Types of Android Testing:
Android testing has two primary categories: functional and non-
functional testing. Now, let's explore them in more detail.
Functional Testing:
Level Description Example
Tests individual components (classes,
Unit Testing JUnit test for a calculation function.
methods).
Integration Verifying that database and API
Tests how components work together.
Testing integration works.
UI / Functional
Tests user interface and app functions. Clicking buttons, filling forms.
Testing
Checking all features work on a
System Testing Tests the complete app as a whole.
device.
Acceptance Ensures the app meets client/business
UAT before release.
Testing requirements.
Non Functional Testing:
III BCA BD SEMESTER V 49 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Type Purpose Tools
Human testers interact with the app
Manual Testing No tools or basic debugging tools.
manually.
Automated Scripts & frameworks automatically run
Espresso, UI Automator, Appium.
Testing tests.
Checks visual components and
UI Testing Espresso, UI Automator.
interactions.
Performance Tests speed, responsiveness, and
Android Profiler, JMeter.
Testing stability.
Security Testing Finds vulnerabilities in the app. OWASP ZAP, Drozer.
Compatibility Checks app behavior on different
Firebase Test Lab, BrowserStack.
Testing devices & OS versions.
Regression Ensures existing features still work after Automated UI tests with
Testing changes. Espresso/Appium.
Popular Android Testing Tools
JUnit → Unit testing.
Espresso → UI testing within Android Studio.
UI Automator → Cross-app functional UI testing.
Appium → Cross-platform mobile automation.
Robolectric → Unit testing Android code without emulator.
Firebase Test Lab → Cloud-based device testing.
MonkeyRunner / Monkey → Random UI event testing.
Publishing Android Application:
Publishing an Android application means making your app available for users, usually through
the Google Play Store or other distribution channels.
Here’s a clear step-by-step guide for publishing on Google Play:
1. Prepare Your App for Release
Before publishing, ensure:
Remove debug code/logs (Log.d, System.out.print, etc.).
Set release build type in Android Studio.
Optimize performance (reduce app size, check memory usage).
Test thoroughly (manual + automated tests).
Check policies (Google Play content, privacy, and security guidelines).
2. Generate a Signed APK / App Bundle
Google now recommends App Bundles (.aab) instead of APK.
1. In Android Studio:
o Build → Generate Signed Bundle / APK.
o Select Android App Bundle.
2. Create a Keystore (if not already made).
3. Set Build Type to release.
III BCA BD SEMESTER V 50 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
4. Finish and get your .aab file.
3. Create a Google Play Developer Account
Go to Google Play Console.
Sign in with your Google account.
Pay the one-time $25 USD registration fee.
Fill in required details.
4. Upload Your App
1. In Google Play Console:
o Click Create App.
o Enter App name, Default language, App type (Game/App), and Pricing
(Free/Paid).
2. Fill App details:
o Short and long description.
o App icon, screenshots, and promotional graphics.
o Feature graphic (1024×500 px).
3. Content rating questionnaire.
4. Privacy Policy URL (mandatory).
5. Upload your .aab file in the Production release section.
5. App Review & Publishing
Google reviews your app for policy compliance.
Review time: Usually a few hours to 7 days.
Once approved → Your app is live on Google Play.
6. After Publishing
Monitor user reviews & ratings.
Use Google Play Console analytics for installs, crashes, and retention.
Push updates regularly.
Respond to feedback.
Other Publishing Options
Direct APK sharing → Share via email, website, or cloud storage (not recommended for
public apps).
Third-party app stores → Amazon Appstore, Samsung Galaxy Store, etc.
Enterprise distribution → For internal company apps.
Using android Preferences
Using Android Preferences means storing small amounts of app data (like settings,
user choices, or flags) in a persistent way, so they remain saved even after the app is
closed or the device is restarted.
In Android, the most common way to store such data is SharedPreferences.
SharedPreferences (Traditional Approach)
III BCA BD SEMESTER V 51 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
What it is: SharedPreferences is an API that allows you to save and retrieve primitive
data types (like strings, integers, booleans, floats, and longs) as key-value pairs to an
XML file on the device's storage. This data persists even if the app is closed or the device
is rebooted.
Use Cases: It's suitable for storing user settings, application configuration, or small
pieces of data that need to be remembered across user sessions (e.g., a "dark mode"
preference, a last-used username).
How it works:
You get a SharedPreferences instance, typically using getSharedPreferences() (for
named files, useful for app-wide preferences) or getPreferences() (for activity-specific,
unnamed files).
To write data, you get a SharedPreferences.Editor object by calling edit() on your
SharedPreferences instance. Then you use methods like putString(), putInt(), etc., and
finally call apply() (asynchronous, recommended) or commit() (synchronous) to save
the changes.
To read data, you use methods like getString(), getInt(), etc., providing the key and a
default value.
Modes: MODE_PRIVATE is the most common and secure mode, making the preference file
accessible only by your application. MODE_WORLD_READABLE and
MODE_WORLD_WRITABLE are deprecated due to security concerns.
Limitations/Drawbacks:
Synchronous Operations: SharedPreferences operations, especially commit(), can
block the main UI thread, leading to ANRs (Application Not Responding) if done
frequently or with large amounts of data. Even apply() has some synchronous disk I/O.
Lack of Type Safety: It only handles primitive types, and there's no compile-time
checking for the types you store or retrieve, which can lead to runtime errors.
III BCA BD SEMESTER V 52 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
No Atomic Updates: Race conditions can occur if multiple threads try to modify
SharedPreferences simultaneously.
Limited Error Handling: It doesn't provide a robust way to handle I/O errors.
DataStore (Modern & Recommended Approach)
What it is: DataStore is a modern and improved data storage solution from Google,
designed to overcome the drawbacks of SharedPreferences. It's built on Kotlin
Coroutines and Flow, providing an asynchronous and type-safe way to store data.
Types of DataStore:
o Preferences DataStore: Similar to SharedPreferences in that it stores data in
key-value pairs without a predefined schema. It's the direct successor to
SharedPreferences.
o Proto DataStore: Allows you to store strongly typed objects (defined using
Protocol Buffers). This provides full type safety and is generally recommended
for more complex data structures.
Preference API (for UI Settings)
What it is: This is a separate set of APIs (often used with PreferenceFragmentCompat
from AndroidX) that helps you build a user interface for your app's settings. While it
uses SharedPreferences (or DataStore, in modern implementations) under the hood to
save the user's choices, it's distinct from the SharedPreferences API itself.
Components: Includes UI elements like CheckBoxPreference, EditTextPreference,
ListPreference, PreferenceScreen, etc., which simplify creating a settings screen.
Purpose: To provide a consistent and easy-to-implement way for users to configure
your application's behavior.
Managing application resources
Managing application resources in a hierarchy in Android is crucial for building flexible,
maintainable, and adaptable apps that can cater to various device configurations and
user preferences.
Android's resource system allows you to provide different versions of resources (like
layouts, drawables, strings, etc.) based on specific criteria, and the system automatically
picks the most appropriate one at runtime.
Need of Android application resources:
Maintainability: Keeping UI elements, images, and other resources separate from
the code allows for easier updates and maintenance without modifying core logic.
Localization: Externalized resources support localization and the ability to
present content in different languages and formats.
Adaptability resources allow the app to adjust to various devices screen sizes,
densities and orientations automatically.
Performance Optimization. Android can select the best resources for each
devices reducing unnecessary scaling and memory Usage.
Dynamic changes: Resources allow the app to dynamically adapt to
configuration changes such as changing orientations, languages or themes.
Consistency and theming: It ensures a consistent design throughout the app by
using styles and themes, making the UI easier to manage and modify.
Importance of resources in android applications:
III BCA BD SEMESTER V 53 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
1. Separation of concerns: Resources allow you to separate content from the code
making the app easier to maintain and update.
2. Localization: Resources enable easy localization, allowing the app to be translated
into different languages and adapt to various cultural contexts without changing the
core functionality.
3. Adaptability: Resources help the app adapt to different device configurations such as
screen sizes, densities and orientations by providing alternative resources for specific
configurations.
4. Consistency: By defining resources like colors, styles, and dimensions, you can
ensure a consistent look and feel across the app making it easier to manage and
update the app's design.
5. Performance optimization: Using optimized resources can improve app
performance, reducing memory consumption, and improving load times.
6. User experience: Resources like drawables, animations and layouts allow you to
create engaging and interactive user interfaces that improve the overall user
experience.
7. Reusability: Resources can be reused across different parts of the app, redundancy
And simplifying updates.
Working with Different Resources in Android:
Android applications use various types of resources to separate non-code elements
from the application logic, promoting maintainability, flexibility, and support for
different device configurations.
These resources are typically stored in the res/ directory of an Android project and are
categorized by type.
Types of Android Resources & How to Work with Them:
Layout Resources (res/layout/):
o XML files defining the structure of the user interface (UI) for activities,
fragments, or custom views.
o Example: activity_main.xml defines the layout for the main activity.
Drawable Resources (res/drawable/):
o Image files (PNG, JPG, GIF), XML-defined shapes, state lists, or vector assets.
o Used for icons, backgrounds, or custom UI elements.
o Example: my_icon.png, button_background.xml.
Value Resources (res/values/):
o XML files containing various primitive values:
III BCA BD SEMESTER V 54 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Strings (strings.xml): Text strings for UI elements, messages, and
localization.
Colors (colors.xml): Hexadecimal color values for consistent theming.
Dimensions (dimens.xml): Size values (e.g., margins, padding, text sizes)
with units like dp, sp, px.
Styles and Themes (styles.xml, themes.xml): Define the appearance of UI
elements and the overall application theme.
Integers (integers.xml): Integer values.
Booleans (bools.xml): Boolean values.
Arrays (arrays.xml): Arrays of strings, integers, or typed arrays.
Menu Resources (res/menu/):
o XML files defining application menus, such as options menus or context menus.
Raw Resources (res/raw/):
o Arbitrary files like audio, video, or other data files that need to be accessed
directly by the application.
Font Resources (res/font/):
o Custom font files (e.g., TTF, OTF) to be used within the application.
Accessing Resources:
Resources are accessed using their unique resource IDs, which are automatically
generated in the R class during compilation.
In Code: Use R.<resource_type>.<resource_name>. For example,
R.string.app_name, R.drawable.my_icon, R.layout.activity_main.
In XML: Use the @ symbol followed by the resource type and name. For example,
@string/app_name, @drawable/my_icon, @layout/activity_main.
Providing Alternative Resources:
Android allows providing alternative resources for different device configurations (e.g.,
screen size, orientation, language, density).
This is achieved by creating specially named resource directories within res/ that
include configuration qualifiers.
For example, res/layout-land/ for landscape layouts or res/values-es/ for Spanish
strings.
Android automatically selects the most appropriate resource at runtime based on the
device's current configuration.
UNIT-V
Storage API’S:
In Android development, APIs (Application Programming Interfaces) are
fundamental for how different software components interact. They can be broadly
categorized into Internal APIs and External APIs.
Internal Storage API:
III BCA BD SEMESTER V 55 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Internal storage is the primary storage area on an Android device, typically a dedicated
portion of the device's flash memory. It's designed for private app data.
Characteristics:
Private to your app: Data stored here is isolated and not accessible by other apps by
default. This provides a high level of security for sensitive information.
Automatic deletion: When your app is uninstalled, all data stored in its internal
storage directory is automatically removed.
Limited space: The amount of internal storage available to an app is often limited by
the device's system.
Always available: Internal storage is always available, regardless of whether external
storage (like an SD card) is mounted or not.
No user interaction: Users generally don't directly interact with files stored in internal
storage.
Common Use Cases:
Configuration files: Storing user preferences, settings, or application state.
Small databases: For SQLite databases used by your app.
Temporary files: Cache files or data that doesn't need to persist beyond the app's
lifecycle or for sharing.
APIs for Internal Storage:
You primarily use the Context class to access internal storage directories:
getFilesDir(): Returns a File object representing the directory where your app can
store its private files.
Java
File file = new File(context.getFilesDir(), "my_private_file.txt");
getCacheDir(): Returns a File object representing the directory where your app can
store temporary cache files. The system may delete these files when storage runs low.
Java
File cacheFile = new File(context.getCacheDir(), "my_temp_data.txt");
openFileInput(String name) and openFileOutput(String name, int mode): These
methods allow you to read from and write to files directly within your app's internal
storage directory.
Java
// Writing to a file
FileOutputStream fos = context.openFileOutput("my_data.txt", Context.MODE_PRIVATE);
fos.write("Hello, Internal Storage!".getBytes());
fos.close();
// Reading from a file
FileInputStream fis = context.openFileInput("my_data.txt");
// ... read data ...
fis.close();
getDir(String name, int mode): Creates (or opens an existing) directory within your
app's internal storage.
III BCA BD SEMESTER V 56 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
External Storage API:
External storage refers to publicly accessible storage, which can be the device's built-in
shared storage (often referred to as "emulated" external storage) or a removable
storage medium like an SD card.
Characteristics:
Publicly accessible: Data stored here can be read by other apps (with appropriate
permissions) and by the user directly when the device is connected to a computer.
Persistence: Data generally remains even after your app is uninstalled, unless it's
stored in app-specific directories that are cleaned up.
Larger space: External storage usually offers more space than internal storage.
Availability: External storage might not always be available. You must check its state
before attempting to access it.
Permissions required: Writing to external storage requires the
WRITE_EXTERNAL_STORAGE permission, and reading requires
READ_EXTERNAL_STORAGE These are runtime permissions from Android 6.0
(Marshmallow) onwards.
Common Use Cases:
Media files: Photos, videos, audio files that the user might want to access or share.
Large datasets: Files that are too large for internal storage.
Files for sharing: Data intended to be shared with other apps or users.
APIs for External Storage:
Accessing external storage involves different methods depending on whether you're storing
app-specific files (which are private to your app but on external storage) or public
media/general files.
App-Specific Files on External Storage:
These files are stored in directories that are dedicated to your app on external storage.
While they are on external storage, they are generally deleted when your app is
uninstalled.
getExternalFilesDir(String type): Returns a File object representing a directory where
your app can place its own persistent files on external storage. type can be
Environment.DIRECTORY_PICTURES, Environment.DIRECTORY_DOCUMENTS, etc., to
organize files.
Java
File appSpecificDir = new
File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
"my_image.jpg");
getExternalCacheDir(): Returns a File object for your app's external cache directory.
These files can be cleared by the system if needed.
Java
File externalCacheFile = new File(context.getExternalCacheDir(),
"external_temp_data
Public Files on External Storage:
These files are intended to be shared and are not deleted with your app's uninstallation.
They are typically stored in standard, shared directories on external storage.
III BCA BD SEMESTER V 57 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Environment.getExternalStoragePublicDirectory(String type): This method,
deprecated in Android 10 (API level 29), used to return a File object for standard
public directories (like Environment.DIRECTORY_PICTURES,
Environment.DIRECTORY_DOWNLOADS).
Java
// Deprecated in Android 10+
File publicGallery = Environment.getExternalStoragePublicDirectory(Environment.
Permissions for External Storage:
android.permission.READ_EXTERNAL_STORAGE: To read any file on external storage
(not needed for files in your app's private external directories from API 19+).
android.permission.WRITE_EXTERNAL_STORAGE: To write any file on external
storage (not needed for files in your app's private external directories).
o Note: From Android 10 (API level 29) onwards, WRITE_EXTERNAL_STORAGE is
generally deprecated for direct file access. Apps should use Scoped Storage with
MediaStore or SAF for public files, or store files in their app-specific directories.
Runtime Permissions: For Android 6.0 (Marshmallow) and higher, these storage
permissions are dangerous permissions and must be requested from the user at
runtime.
SQLite Databases and managing data using SQLite:
SQLite is a popular open-source, relational database management system (RDBMS)
embedded directly into Android.
It's a lightweight, serverless, self-contained, and transactional database engine, making it
ideal for mobile applications that need local data storage.
Why Use SQLite in Android?
Offline Access: Allows your app to function even without an internet connection by
storing data locally.
Performance: Generally fast for local data operations compared to network requests.
Data Persistence: Data remains available even after the app is closed or the device is
rebooted.
Structured Data: Provides a robust way to store and manage structured data with
tables, rows, and columns.
Key characteristics of SQLite in Android:
Embedded:
SQLite is built into Android, eliminating the need for separate server installations or
configurations.
Lightweight and Efficient:
It's designed for resource-constrained environments like mobile devices, making it efficient
for local data storage.
SQL Compliant:
SQLite supports standard SQL queries for managing data, including operations like creating
tables, inserting, updating, deleting, and retrieving data.
III BCA BD SEMESTER V 58 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Transactional:
It ensures data integrity through transactional operations, guaranteeing that either all
changes within a transaction are applied or none are.
Working with SQLite in Android:
Android provides classes within the android.database.sqlite package to interact with SQLite
databases.
SQLiteOpenHelper:
This is a key helper class for managing database creation and versioning. It
provides onCreate() for initial database setup (table creation, etc.) and onUpgrade() for
handling database schema changes across different app versions.
SQLiteDatabase:
This class represents the SQLite database itself and provides methods for executing SQL
queries, managing transactions, and performing CRUD (Create, Read, Update, Delete)
operations on the data.
Cursor:
When retrieving data from the database using a query, the results are returned in
a Cursor object, which allows you to iterate through the rows and columns of the result set.
Best Practices for Managing SQLite Databases
Singleton Pattern for SQLiteOpenHelper: Use a singleton pattern for your
SQLiteOpenHelper instance to prevent multiple open database connections, which can
lead to errors and performance issues.
Close Cursor and SQLiteDatabase: Always close Cursor objects and SQLiteDatabase
connections when you're done with them to prevent resource leaks. Use try-finally
blocks for robustness.
Asynchronous Operations: For complex or long-running database operations (like
querying large datasets), perform them on a background thread (e.g., using AsyncTask,
Executors, or Kotlin Coroutines) to avoid blocking the main UI thread and causing
Application Not Responding (ANR) errors.
Content Providers (for larger apps/sharing data): If your app needs to expose its
data to other applications or uses a CursorLoader for efficient UI updates, consider
implementing a ContentProvider. This provides a standardized interface for data access.
ORM Libraries: For more complex data models and to reduce boilerplate code,
consider using Object-Relational Mapping (ORM) libraries like Room Persistence
Library (Google's recommended solution), Realm, or GreenDAO. Room builds on top of
SQLite and provides an abstraction layer, making database interactions much easier and
safer by checking SQL queries at compile time.
Database Versioning and Migration: Plan for database schema changes. The
onUpgrade() method in SQLiteOpenHelper is vital for migrating data when your app's
database schema evolves.
III BCA BD SEMESTER V 59 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Transactions: Use beginTransaction(), setTransactionSuccessful(), and
endTransaction() for multiple database operations that need to be atomic (either all
succeed or all fail). This ensures data integrity.
Share Data Through Content Providers
On the Android platform, one application cannot directly access (read/write) other
application's data. All persistent data of an app is private to that app. Every application has its own
id data directory and own protected memory area. This means that an app cannot query or
manipulate the data of another app. However, if you want to enable an app to query or manipulate
the data of another app, you need to use the concept of content providers.
What is a Content Provider?
Content provider is a set of data wrapped up in a custom API to read and write. It acts as an
interface that allows you to store and retrieve data from a data source. And also allows you to
share an app’s data with other apps. Content providers decouple the app layer from the data layer
by abstracting the underlying data source, thereby making apps data-source independent. They
allow full permission control by monitoring which app components or users should have access to
the data making data sharing easy. As a result, any app with appropriate permissions can add,
remove, update, and retrieve data of another app including the data in some native Android
databases.
There are 2 types of Content Providers :
Custom content providers: These are created by the developer to suit the requirements of an app.
Native content providers: These provide access to built-in databases, such as contact manager,
media player, and other native databases. You need to grant the required permissions to your app
before using native content providers.
Creating a Content Provider
Following are the steps which are essential to follow in order to create a Content Provider:
Create a class in the same directory where the that MainActivity file resides and this
class must extend the ContentProvider base class.
To access the content, define a content provider URI address.
Create a database to store the application data.
Implement the six abstract methods of ContentProvider class.
Register the content provider in AndroidManifest.xml file using <provider> tag .
III BCA BD SEMESTER V 60 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Working of the Content Provider
UI components of android applications like Activity and Fragments use an
object CursorLoader to send query requests to ContentResolver. The ContentResolver
object sends requests (like create, read, update, and delete) to the ContentProvider as a
client. After receiving a request, ContentProvider process it and returns the desired result.
Below is a diagram to represent these processes in pictorial form.
Android network APIs:
Android network APIs are a collection of Application Programming Interfaces (APIs) within the
Android framework that enable mobile applications to interact with and utilize network
functionalities. These APIs provide developers with the tools and protocols necessary to build
applications that can communicate over various networks, access online resources, and
integrate with remote services.
Key aspects of Android network APIs:
Facilitating Network Communication: They provide standardized ways for Android
applications to send and receive data over networks, including the internet, local area
networks (LANs), and cellular networks. This includes handling protocols like
HTTP/HTTPS for web-based communication, and potentially others like TCP/UDP for
more direct socket-based interactions.
Accessing Network Capabilities: These APIs allow applications to leverage specific
network features and information, such as checking network connectivity status,
determining network type (Wi-Fi, mobile data), and potentially accessing advanced
network capabilities like those offered by 5G networks (e.g., differentiated connectivity,
location services, network insights).
Integration with External Services: They are crucial for integrating Android apps with
various external services and APIs, such as social media platforms, payment gateways,
cloud services, and custom backend servers. This enables features like user
authentication, data synchronization, and real-time updates.
Examples of Android Network APIs and related components:
III BCA BD SEMESTER V 61 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
o java.net package: Provides core Java networking classes for basic network
operations.
o ConnectivityManager: Allows applications to monitor network connectivity
status and request network connections based on specific criteria.
o Libraries for RESTful API interaction: Popular third-party libraries like
Retrofit, Volley, and OkHttp simplify the process of making HTTP requests and
handling responses for interaction with RESTful web services.
What is Web API and why we use it ?
Web API is an API as the name suggests, it can be accessed over the web using the
HTTP protocol. It is a framework that helps you to create and develop HTTP based
RESTFUL services. The web API can be developed by using different technologies such
as java, ASP.NET, etc. Web API is used in either a web server or a web browser.
Basically Web API is a web development concept.
Web API is the enhanced form of the web application. ASP.NET Web API: ASP.NET
stands for Active Server Pages.NET. It is mostly used for creating web pages and web
technologies. It is considered a very important tool for developers to build dynamic
web pages using languages like C# and Visual Basic.
Where to use Web API?
1. Web APIs are very useful in implementation of RESTFUL web services using .NET
framework.
2. Web API helps in enabling the development of HTTP services to reach out to client
entities like browser, devices or tablets.
3. ASP.NET Web API can be used with MVC for any type of application.
4. A web API can help you develop ASP.NET application via AJAX.
5. Hence, web API makes it easier for the developers to build an ASP.NET application that is
compatible with any browser and almost any device.
Why to Choose Web API?
A Web API services are preferable over other services to use with a native application
that does not support SOAP but require web services.
For creating resource-oriented services, the web API services are the best to choose. By
using HTTP or restful service, these services are established.
If you want good performance and fast development of services, the web API services are
very helpful.
For developing light weighted and maintainable web services, web API services are really
helpful to develop that service. It supports any text pattern like JSON, XML etc.
The devices that have tight bandwidth or having a limitation in bandwidth, then the Web
API services are the best for those devices.
Steps to use Web API:
Most APIs require an API key. Once you find an API you want to play with, look in the
documentation for access requirements. Most APIs will ask you to complete an identity
verification, like signing in with your Google account. You’ll get a unique string of letters
and numbers to use when accessing the API.
III BCA BD SEMESTER V 62 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
The easiest way to start using an API is by finding an HTTP client online, like REST-Client,
Postman, or Paw. These ready-made tools help you structure your requests to access
existing APIs with the API key you received. You’ll still need to know some of the syntaxes
from the documentation, but there is very little coding knowledge required.
The next best way to pull data from an API is by building a URL from existing API
documentation.
Popular API Examples:
1. Google Maps API's: Google Maps APIs allows developers to use Google Maps on
Webpages using a JavaScript or Flash interface.
2. YouTube API's: Google's API lets developers integrate YouTube and functionality into
websites or applications. YouTube APIs include the YouTube analytics API, YouTube Data
API, YouTube live streaming API, YouTube Player APIs and others.
3. The Flickr APIs: It is used by developers to access the Flick photo sharing community
data.
4. Twitter APIs: Twitter offers two APIs, the REST API allows developers to access core
Twitter data and the search API provides methods for developers to interact with twitter
search and trends data.
JSON parsing in android using telephony APIs:
JSON stands for JavaScript Object Notation. It is an independent data exchange format and
is the best alternative for XML. JSON is a lightweight and structured language.
Android provides four different classes to manipulate JSON data. These classes
are JSONArray,JSONObject,JSONStringer and JSONTokenizer.
JSON Elements:
An JSON file consist of many components. Here is the table defining the components of an JSON
file and their description –
JSON - Parsing
For parsing a JSON object, we will create an object of class JSONObject and specify a string
containing JSON data to it. Its syntax is –
III BCA BD SEMESTER V 63 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
String in;
JSONObject reader = new JSONObject(in);
The last step is to parse the JSON. A JSON file consist of different object with different
key/value pair e.t.c. So JSONObject has a separate function for parsing each of the component
of JSON file. Its syntax is given below −
The method getJSONObject returns the JSON object. The method getString returns the
string value of the specified key.
Apart from the these methods , there are other methods provided by this class for better
parsing JSON files. These methods are listed below −
Android Telephony API
The Android Telephony API provides developers with access to the underlying
telephone hardware and functionalities on an Android device. This allows applications
to interact with phone features like calls, SMS, MMS, and network information.
III BCA BD SEMESTER V 64 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Key components and functionalities of the Android Telephony API include:
TelephonyManager: This class provides information about the phone's state and
services, such as network type, data connection status, call state, and device identifiers
(like IMEI).
It also allows registering for notifications when these states change using
PhoneStateListener.
With TelephonyManager, applications can:
Monitor Phone State: Track changes in call state (idle, ringing, off-hook), service state,
signal strength, and more. This is typically done by registering a PhoneStateListener.
Retrieve Device Information: Access details about the device, SIM card, and network
provider. This can include:
o Device ID (e.g., IMEI for GSM, MEID/ESN for CDMA)
o Phone number for line 1
o Network country ISO code
o Network operator name
o SIM country ISO code
o SIM serial number
o SIM state
o Subscriber ID (IMSI)
o Voice mail number and alphabetic tag
o Network type (e.g., GSM, CDMA, LTE, 5G)
o Roaming status
SmsManager: This class enables applications to send and receive SMS messages
programmatically.
Telecom Framework: This newer framework manages audio and video calls, including
both SIM-based calls (using the telephony framework) and Voice over IP (VoIP) calls. It
provides a unified way to handle call management, audio routing, and interactions with
connected devices like headsets.
Permissions: Accessing most telephony information and functionalities requires
specific permissions declared in your app's AndroidManifest.xml file. The most common
permission needed is READ_PHONE_STATE, which grants access to the phone's state
and certain information. Other permissions like CALL_PHONE (for direct calls) and
SEND_SMS/RECEIVE_SMS are also essential for their respective functionalities.
Android allows applications to access to view the access the state of the wireless
connections at very low level. Application can access almost all the information of a wifi
connection.
III BCA BD SEMESTER V 65 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Android provides WifiManager API to manage all aspects of WIFI connectivity. We can
instantiate this class by calling getSystemService method. Its syntax is given below –
In order to scan a list of wireless networks, you also need to register your BroadcastReceiver. It
can be registered using registerReceiver method with argument of your receiver class object.
Its syntax is given below –
The wifi scan can be start by calling the startScan method of the WifiManager class. This
method returns a list of ScanResult objects. You can access any object by calling the get method
of list. Its syntax is given below –
Apart from just Scanning, you can have more control over your WIFI by using the methods
defined in WifiManager class. They are listed as follows –
Sensors in Android:
Most of the android devices have built-in sensors that measure motion, orientation, and
various environmental condition. The android platform supports three broad categories of
sensors.
III BCA BD SEMESTER V 66 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Motion Sensors
Environmental sensors
Position sensors
Some of the sensors are hardware based and some are software based sensors. Whatever the
sensor is, android allows us to get the raw data from these sensors and use it in our
application. For this android provides us with some classes.
Android provides SensorManager and Sensor classes to use the sensors in our application. In
order to use sensors, first thing you need to do is to instantiate the object of SensorManager
class. It can be achieved as follows.
SensorManager sMgr;
sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
The next thing you need to do is to instantiate the object of Sensor class by calling the
getDefaultSensor() method of the SensorManager class. Its syntax is given below −
Sensor light;
light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
Once that sensor is declared , you need to register its listener and override two methods which
are onAccuracyChanged and onSensorChanged. Its syntax is as follows −
sMgr.registerListener(this, light,SensorManager.SENSOR_DELAY_NORMAL);
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
}
Types of Sensors:
Motion Sensors:
Measure acceleration and rotational forces along three axes. Examples include:
III BCA BD SEMESTER V 67 | P a g e
Zenex Vision Degree College Phno:9515786774,965250444 Android Application Development
Accelerometer: Detects acceleration along the x, y, and z axes.
Gyroscope: Measures rotational velocity.
Gravity Sensor: Measures gravitational force.
Linear Acceleration Sensor : Measures linear acceleration excluding gravity.
Rotation Vector Sensor : Represents device orientation as a rotation vector.
Position Sensors:
Measure the physical position of the device. Examples include:
Orientation Sensor : Measures the orientation of the device in 3D space.
Magnetometer: Measures the strength and direction of the magnetic field.
Environmental Sensors:
Measure environmental parameters. Examples include:
Light Sensor: Measures ambient light levels.
Pressure Sensor: Measures atmospheric pressure.
Temperature Sensor: Measures ambient temperature.
Humidity Sensor: Measures humidity.
III BCA BD SEMESTER V 68 | P a g e