Module IV Technology I - Android
Module IV Technology I - Android
P a g e 1 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
P a g e 2 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
You can then set app timers to help manage your digital habits and promote a healthier
relationship with your device .
Establishing the Development Environment :
Android operating system is a stack of software components which is roughly divided into five sections
and four main layers as shown below in the architecture diagram
Android is structured in the form of a software stack comprising applications, an operating system, run-
time environment, middleware, services and libraries. Each layer of the stack, and the corresponding
elements within each layer, are tightly integrated and carefully tuned to provide the optimal application
development and execution environment for mobile devices.
LINUX KERNEL
• Positioned at the bottom of the Android software stack, the Linux Kernel provides a level of
abstraction between the device hardware and the upper layers of the Android software stack.
• Based on Linux version 2.6, the kernel provides pre-emptive multitasking, low-level core
system services such as memory, process and power management in addition to providing a
network stack and device drivers for hardware such as the device display, Wi-Fi and audio.
ANDROID RUNTIME – ART
• When an Android app is built within Android Studio it is compiled into an intermediate
bytecode format (DEX format).
• When the application is subsequently loaded onto the device, the Android Runtime (ART) uses
a process referred to as Ahead-of-Time (AOT) compilation to translate the byte-code down to
the native instructions required by the device processor. This format is known as Executable
and Linkable Format (ELF).
• Each time the application is subsequently launched, the ELF executable version is run, resulting
in faster application performance and improved battery life. This section provides a key
component called Dalvik Virtual Machine which is a kind of Java Virtual Machine specially
designed and optimized for Android.
• The Dalvik VM makes use of Linux core features like memory management and
multithreading, which is intrinsic in the Java language. The Dalvik VM enables every Android
application to run in its own process, with its own instance of the Dalvik virtual machine.
• The Android runtime also provides a set of core libraries which enable Android application
developers to write Android applications using standard Java programming language.
P a g e 4 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
ANDROID LIBRARIES
• In addition to a set of standard Java development libraries (providing support for such general
purpose tasks as string handling, networking and file manipulation), the Android development
environment also includes the Android Libraries. These are a set of Java-based libraries that are
specific to Android development.
• C/C++ LIBRARIES The Android runtime core libraries are Java-based and provide the primary
APIs for developers writing Android applications. It is important to note, however, that the core
libraries do not perform much of the actual work and are, in fact, essentially Java ―wrappers‖
around a set of C/C++ based libraries
APPLICATION FRAMEWORK
• The Application Framework is a set of services that collectively form the environment in which
Android applications run and are managed.
• This framework implements the concept that Android applications are constructed from
reusable, interchangeable and replaceable components.
• This concept is taken a step further in that an application is also able to publish its capabilities
along with any corresponding data so that they can be found and reused by other applications.
APPLICATIONS
Located at the top of the Android software stack are the applications. These comprise both the native
applications provided with the particular Android implementation (for example web browser and email
applications) and the third party applications installed by the user after purchasing the device.
Android architecture:
Android architecture is designed as a layered system, often visualized as a stack of components. This
layered approach ensures that different parts of the operating system operate independently, promoting
stability, security, and modularity.
At the very bottom is the Linux Kernel, which interacts directly with the hardware. Above this kernel
lie the Hardware Abstraction Layer (HAL) and the Android Runtime (ART) & Native Libraries. The
next layer is the Application Framework, which provides high-level services to applications. Finally, at
P a g e 5 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
the top are the System Applications themselves. This separation means that application developers
interact with the Framework, not directly with the kernel, ensuring a consistent development experience
across vastly different hardware devices.
The Linux Kernel
• At the foundation of the Android architecture lies the Linux Kernel. This is not a modified
version of Linux but a long-term support (LTS) kernel with specific patches and drivers tailored
for mobile environments.
• The kernel serves as the abstraction layer between the hardware and the rest of the software
stack. It is responsible for core system services such as process management, memory
management, networking, and security.
• A critical aspect of the kernel is its driver model, which includes Display, Camera, Bluetooth,
Audio, and Binder drivers. The Binder Driver is particularly important; it is the primary Inter-
Process Communication (IPC) mechanism that allows different applications and the system
framework to communicate efficiently and securely.
• By relying on the Linux kernel, Android inherits proven security features, such as a permission-
based user model where each application runs as a distinct user ID (UID).
Hardware Abstraction Layer (HAL)
• Directly above the kernel but below the Framework is the Hardware Abstraction Layer
(HAL). The HAL is a crucial component for device manufacturers (OEMs).
• It defines a standard interface for hardware vendors to implement without exposing the
internal details of their drivers to the Android framework. For example, the camera HAL
defines functions like open_camera, start_preview, and take_picture. A vendor like
Qualcomm or Samsung implements these functions to work with their specific camera
sensor hardware.
• The Android Framework does not call the kernel driver directly; instead, it calls into the
HAL. This abstraction allows the higher-level framework to remain hardware-agnostic. If
a new device uses a different camera sensor, the vendor only needs to provide a compatible
HAL implementation, and all existing Android applications will continue to function
without modification.
In the middle of the stack reside the Android Runtime (ART) and the Native Libraries.
The Native Libraries are written in C/C++ and form the backbone of system capabilities. Key
libraries include:
• WebKit/Chromium: Powers the WebView for in-app browsing.
• OpenGL ES & Vulkan: 3D graphics libraries for rendering games and UI.
• Media Framework: Handles audio and video playback/recording (Stagefright).
• SQLite: A lightweight relational database engine used for local data storage.
• SSL: Secure sockets layer for internet security.
The Android Runtime (ART) is the engine that runs applications. When you write an Android
app in Kotlin or Java, the code is compiled into Dalvik Executable (DEX) bytecode. ART converts
this bytecode into machine code. Since Android 5.0 (Lollipop), ART replaced the older Dalvik
VM. A major feature of ART is Ahead-of-Time (AOT) and Just-in-Time (JIT) compilation. On
modern Android versions, the system uses a hybrid approach: when an app is installed, ART
performs "profile-guided" compilation. It initially uses JIT compilation for frequently used code,
and during device idle and charging, it performs background AOT compilation on the "hot" code
paths. This balances fast installation, quick startup times, and improved runtime performance.
Application Framework
The Application Framework is the toolkit used by developers. It provides the classes and services
necessary to create robust applications. It sits directly above the native layer and abstracts the
underlying hardware and system services. The primary managers within the Framework include:
• Activity Manager: Manages the lifecycle of application components (Activities,
Services). It also maintains a stack (back-stack) of activities for navigation purposes
and handles process priority based on user interaction to determine which processes to
keep running or kill when memory is low.
• Window Manager: Manages the windows displayed on the screen. It determines the
screen size, handles window layering (e.g., status bar overlaying an app), and
dispatches input events (touch, keyboard) to the appropriate view.
• Content Providers: Enables data sharing between applications. It encapsulates data
(like contacts or media) and provides a consistent URI-based interface for CRUD
(Create, Read, Update, Delete) operations. It enforces security by allowing apps to
grant temporary permissions to specific data sets.
• View System: The set of UI components used to build an application's user interface
(e.g., Button, TextView, RecyclerView). It handles layout calculations, drawing, and
event handling.
• Notification Manager: Manages status bar notifications, alerts, and app badges.
• Package Manager: Tracks all installed applications, manages their permissions, and
handles app installation/uninstallation
P a g e 7 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
• Activity - An activity is a class that represents a single screen. It is like a Frame in AWT.
• View - A view is the UI element such as button, label, text field etc. Anything that you see is a
view.
• Intent- Intent is used to invoke components. It is mainly used to
✓ Start the service
✓ Launch an activity
✓ Display a web page
✓ Display a list of contacts
✓ Broadcast a message
✓ Dial a phone call etc.
• Service- Service is a background process that can run for a long time. There are two types of
services local and remote. Local service is accessed from within the application whereas
remote service is accessed remotely from other applications running on the same device. For
example, a service might play music in the background while the user is in a different
application, or it might fetch data over the network without blocking user interaction with an
activity.
• Content Provider- Content Providers are used to share data between the applications. A
content provider component supplies data from one application to others on request. Such
requests are handled by the methods of the ContentResolverclass. The data may be stored in
the file system, the database or somewhere else entirely. 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.
• Fragment- Fragments are like parts of activity. An activity can display one or more fragments
on the screen at the same time.
P a g e 8 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
The Activity class defines the following call backs i.e. events. You don't need to implement all the
callbacks methods. However, it's important that you understand each one and implement those that
ensure your app behaves the way users expect.
P a g e 9 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
▪ onCreate()- This is the first callback and called when the activity is first
created
▪ onStart()- This callback is called when the activity becomes visible to the user.
▪ onResume()- This is called when the user starts interacting with the
application. onPause()- The paused activity does not receive user input and
cannot execute any code and called when the cactivity is being resumed.
▪ onStop()- This callback is called when the activity is no longer visible.
▪ onDestroy()- This callback is called before the activity is destroyed by the
system.
▪ onRestart()- This callback is called when the activity restarts after stopping it.
Why is the Lifecycle Important?
Android can kill your app's process at any time to free memory. If you don't save state (like
user input) in onPause() or onSaveInstanceState(), it will be lost forever. The lifecycle
provides hooks to manage resources efficiently.
• Key Characteristics:
o [Link] is the base class for all UI components.
o Widgets are subclasses of View that are interactive (e.g., Button, TextView, EditText).
o Layouts are subclasses of ViewGroup (which itself is a subclass of View) that contain
and arrange child Views (e.g., LinearLayout, ConstraintLayout).
P a g e 11 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
1. Inflation: In onCreate(), the Activity calls setContentView(). This reads an XML layout file,
parses it, and builds the View tree in memory.
2. Binding: The Activity gets references to the Views it needs to interact with. Modern
Approach: Use View Binding (generates a binding class) instead of findViewById for better
type safety and null safety.
3. Interaction: A user clicks a Button.
4. Event Handling: The click event travels up the View hierarchy and triggers
the OnClickListener set by the Activity.
5. Response: The Activity's listener code runs, performing some logic (e.g., fetching data from
an EditText).
6. UI Update: The Activity updates the UI by modifying the properties of a View (e.g., setting
new text in a TextView).
Interacting with UI
Overview of UI Interaction in Android
User Interface (UI) interaction is the bridge between the user and your application. In Android, this
interaction flows through a well-defined architecture that starts with a physical touch on the screen
and ends with your application's response.
Key Components in UI Interaction:
• View System: The UI components (Buttons, TextViews, etc.)
• Event Listeners: Interfaces that detect user actions
• Event Handlers: Methods that respond to user actions
• System Services: WindowManager, InputManager that process raw touch events
P a g e 12 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
1. PHYSICAL LAYER
• Touch Screen (Hardware Layer)
The physical screen detects a touch (finger, stylus, etc.) and generates raw electrical signals.
2. LINUX KERNEL
• Input Device Driver
This kernel-level driver converts the raw hardware signals into standard Linux input
events (e.g., EV_ABS for absolute coordinates, EV_KEY for touch down/up).
It writes these events to device nodes like /dev/input/eventX.
3. NATIVE LAYER (C++ space)
• InputReader Thread
A system thread that constantly reads events from /dev/input/*.
It performs pre-processing such as:
o Translating coordinates to screen resolution.
o Detecting gestures (tap, swipe, etc.).
o Adding pressure, size, or tool type information.
o Queuing events for the next stage.
• InputDispatcher Thread
Takes processed events from InputReader and determines which window should receive them
based on:
o Window focus (foreground app).
o Z-ordering (which UI is on top).
o Touchable regions (hit-testing).
It then dispatches the events to the appropriate application process.
P a g e 13 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
P a g e 14 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
P a g e 15 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
The return value (true or false) determines the flow of the remaining events in the touch sequence (the
subsequent ACTION_MOVE and ACTION_UP):
• Handled (true):
o The view/group consumed the event.
o Result: The event flow stops searching. The system will send the remaining events in
that gesture (the MOVE and UP) directly to this view/group.
• Not Handled (false):
o The view/group did not consume the event.
o Result: The event bubbles up to the parent.
o If the parent does not handle it, it continues up to the Activity. If the Activity does not
handle it, the event is discarded.
Touch Events
P a g e 16 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
onInterceptTouchEvent() Action
Return
true (Intercept) The parent ViewGroup handles the event itself via its own
onTouchEvent().
false (Don't Intercept) The event is passed down to the child View via
[Link]().
GestureDetector Helper for common gestures Double tap, long press, fling, scroll
P a g e 17 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
P a g e 18 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
transactions are processed reliably. Understanding these properties is essential for any developer
working with databases.
Atomicity
Each transaction is treated as a single, indivisible unit of work that either completes entirely or has no
effect at all. In SQLite, this is implemented through the write-ahead log or rollback journal that records
all changes before they are applied to the main database file.
Consistency
Any transaction brings the database from one valid state to another valid state. Database constraints
such as foreign key relationships, unique constraints, and check constraints help maintain consistency.
Isolation
Concurrent execution of transactions results in a system state that would be obtained if transactions
were executed sequentially. When multiple threads or processes access the same database
simultaneously, isolation prevents them from seeing each other's partially completed changes. SQLite
implements isolation through database-level locking, and starting from version 3.7.0, it supports write-
ahead logging (WAL) mode that allows concurrent readers and a single writer to work simultaneously
without blocking.
Durability
Guarantees that once a transaction has been committed, it will remain committed even in the event of
power loss, system crash, or other failures. SQLite achieves durability by ensuring that all committed
changes are written to persistent storage before the transaction is reported as complete. This involves
flushing data to the actual physical storage medium rather than just keeping it in memory caches.
SQLite Architecture and Internal Structure
The Layered Architecture of SQLite
SQLite is not a monolithic block of code but rather a carefully designed system consisting of multiple
components that work together to process SQL statements, manage storage, and ensure data integrity.
P a g e 19 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
At the highest level, the SQLite architecture consists of three main subsystems: the interface layer, the
compiler layer, and the virtual machine layer. The interface layer exposes the public API that
applications use to interact with the database. This includes functions
like sqlite3_open(), sqlite3_exec(), and the prepared statement interface. When an Android application
makes a call through the SQLiteDatabase class, it is ultimately invoking these C-level functions.
The compiler layer is responsible for parsing SQL statements into an abstract syntax tree, analyzing
the syntax, checking semantics, and generating an execution plan. This layer includes the tokenizer that
breaks SQL text into tokens, the parser that builds the syntax tree according to SQL grammar rules, and
the code generator that produces virtual machine bytecode representing the operations needed to
execute the statement.
The virtual machine layer executes the bytecode generated by the compiler. This virtual machine,
often called the VDBE (Virtual Database Engine), processes operations one by one, interacting with the
lower-level storage subsystem to read and write data. The virtual machine approach provides a clean
separation between SQL processing and data storage, making the system more maintainable and secure.
Below the virtual machine lies the B-tree and pager layers. The B-tree layer organizes the database into
pages and implements the tree structures that allow efficient searching and indexing. Each table and
index in an SQLite database is stored as a separate B-tree structure. The pager layer manages the
database file at the page level, handling read and write operations, implementing the ACID properties
through journaling mechanisms, and managing the cache of database pages in memory.
At the lowest level, the operating system interface abstracts away platform-specific details about file
I/O, memory allocation, and threading, allowing SQLite to run on virtually any operating system with
minimal changes.
Database File Structure
An SQLite database is a single ordinary file on the device's filesystem, typically stored in the
application's private data directory at /data/data/<package-name>/databases/. Despite appearing as a
simple file, internally it has a carefully designed structure that enables efficient access and transaction
management.
The database file is divided into pages, which are the fundamental units of storage. The page size is
configurable but is typically 4096 bytes (4 KB) on most Android devices, matching the native filesystem
block size. Each page serves a specific purpose within the database.
The first page of the database file, page 1, is the database header page, which contains critical metadata
about the database including the page size, the write version, the read version, the location of the
schema, and other important parameters.
Following the header page are pages that comprise the B-tree structures for tables and indices. Each
table in the database corresponds to a B+ tree, with leaf pages containing the actual row data and internal
pages containing keys that direct navigation to the appropriate leaf pages. Indexes are implemented as
separate B-tree structures where the leaf pages contain indexed values and pointers to the corresponding
table rows.
For applications that use write-ahead logging (WAL) mode, two additional files appear alongside the
main database file: the write-ahead log file with a .wal extension and the shared memory file with
a .shm extension. The WAL file acts as a transaction log where changes are written before being
checkpointed to the main database file. This approach improves concurrency by allowing readers to
access the main database while writers append to the WAL file, and it reduces the number of disk writes
required for transactions. The shared memory file facilitates communication between multiple processes
accessing the same database by maintaining a shared index of the WAL file's contents.
P a g e 20 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
This diagram visually simplifies the steps, starting from the application code, moving through the
constructor and database opening, and branching into the different scenarios (creation, upgrade, or
downgrade) before returning the database instance.
The Logical Flow
1. Instantiation: When you call new MyDatabaseHelper(...), Android simply stores the
configuration. No file operations occur yet.
2. The Trigger: The process actually starts only when you call getWritableDatabase() or
getReadableDatabase().
3. The Decision Tree:
o If File Doesn't Exist: The system creates the .db file and triggers onCreate(). This is
where you run your CREATE TABLE statements.
o If File Exists: The system compares the version number stored in the database file
header with the version number you passed in the constructor.
▪ Match: Just opens the database.
▪ Stored < Requested: Triggers onUpgrade(). Use this to add columns or
migrate data.
▪ Stored > Requested: Triggers onDowngrade().
4. Completion: Once the appropriate setup or migration method finishes, the SQLiteDatabase
object is returned to your app for CRUD operations.
Once your database helper is implemented, you need to perform Create, Read, Update, and Delete
(CRUD) operations. SQLiteDatabase provides methods for these operations, but it's important to
understand the implications of each approach.
P a g e 21 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
The insert(), update(), delete(), and query() methods are convenience methods that abstract away the
complexity of constructing SQL statements, but they also have limitations for complex operations.
The insert() method accepts a table name and a ContentValues object containing column-value pairs.
The ContentValues class is essentially a map where keys are column names and values are the data to
be stored. You should always provide a null column hack parameter (often set to null) unless you're
inserting an empty row, in which case you specify the column name that can be set to null. This method
returns the row ID of the newly inserted row, or -1 if an error occurred.
For updating existing records, the update() method takes the table name, a ContentValues object with
the new values, a where clause, and where arguments. The where clause should include placeholders
represented by question marks, with the actual values provided in the where arguments array. This
approach automatically handles escaping of values, protecting against SQL injection attacks. The
method returns the number of rows affected.
Deleting records uses the delete() method with a similar pattern: table name, where clause, and where
arguments. Be extremely careful with deletion operations, especially when using null as the where
clause, as this will delete all rows in the table. It's often wise to wrap deletions in transactions and
perform them in a background thread to avoid blocking the UI.
Reading data requires a different approach because it returns a Cursor object containing the results.
The query() method is the most flexible way to retrieve data, accepting parameters for the table,
columns to return, selection criteria, selection arguments, group by, having, order by, and limit. The
returned Cursor provides a positionable window into the result set, allowing you to iterate through rows
and extract column values by index or by name.
Packaging and deployment
Introduction
For an Android application to move from a developer's Integrated Development Environment (IDE) to
a user's smartphone, it must undergo a process called packaging and deployment.
• Packaging is the process of compiling code, resources, and assets into a single distributable
file (an .apk or .aab).
• Deployment is the process of installing that package onto a target device (physical or virtual)
or distributing it via an app store.
Understanding this pipeline is essential for debugging, optimizing app size, and releasing a professional
product.
The Android Application Package (APK)
What is an APK?
An APK (Android Package Kit) is the file format used by the Android operating system for
distribution and installation of mobile apps. It is essentially a compressed archive (ZIP file) containing
all the components necessary for the app to run.
Structure of an APK
When you unzip an APK, you find the following structure:
P a g e 22 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
Component Description
assets/ Raw resource files (fonts, JSON files) accessed via AssetManager.
[Link] The compiled binary file containing all precompiled resources (strings,
styles, dimensions).
[Link] The binary version of the manifest file. It declares permissions, activities,
services, and the application’s metadata.
P a g e 23 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
P a g e 24 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
Ad-Hoc Distribution
• APK: You can build a release APK (Build > Build Bundle(s) / APK(s) > Build APK(s)) and
share the file directly. Users must enable "Install from Unknown Sources" in their settings to
install it.
• AAB: You cannot install an AAB directly on a device. You must use bundletool to convert it to
APKs for local testing.
Google Play Store Distribution
1. Create Developer Account: Pay a one-time registration fee ($25).
2. Prepare Release: Build a signed AAB.
3. Google Play Console:
o Create an App listing (Title, Description, Graphics).
o Upload the AAB to a track (Internal Testing, Closed Testing, Open Testing, or
Production).
o Fill out Content rating questionnaire.
o Set pricing (Free or Paid).
4. Review & Publish: Google reviews the app (automated + human check). Once approved, it
goes live.
Conceptual diagram
Here is a breakdown of the four main stages:
1. Source Files (Input)
Everything starts with your development files:
• Res/ & Manifest: XML layouts, strings, and the [Link].
• Kotlin/Java Source: The actual logic you wrote.
• Assets/ & 3rd Party Libs: Static files (fonts/JSON) and external code libraries.
2. Build Process (The Transformation)
This is where the "heavy lifting" happens inside Android Studio/Gradle:
• AAPT2: Compiles resources into a binary format ([Link]).
• Compilers: Turn your Java/Kotlin code into .class files (bytecode).
• R8 / ProGuard: Optimizes the code by removing unused parts and "obfuscating" it (making it
hard to read for hackers).
• DEX Files: The final bytecode format that the Android Runtime actually understands.
• APK/AAB Packager: Bundles everything together into a single package.
3. Signing (Security)
An Android app cannot be installed unless it is digitally signed:
P a g e 25 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
• Debug Keystore: Used automatically during development so you can test on your own phone.
• Release Keystore: A secure, private key used when you are ready to publish. This proves the
app really came from you and hasn't been tampered with.
4. Deployment (Distribution)
The final stage is getting the signed package to a device:
• USB/ADB: Installing directly to a Physical Device for testing.
• AVD: Running the app on an Emulator on your computer.
• Google Play: The standard path for users. You upload an App Bundle (AAB). Google Play then
uses that bundle to generate a "perfectly sized" APK specifically optimized for each user’s
specific device (screen size, CPU type, etc.).
P a g e 26 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
Interaction with Server Side applications using Google Maps, GPS and Wi-Fi
Location-Based Services in Android
Introduction
Modern Android applications often need to know a user's location to provide relevant services. This
involves a three-part ecosystem:
1. Location Sources: The device hardware (GPS, Wi-Fi, Cellular) that determines the physical
location.
2. The Android Client: The app running on the device that collects this location data.
3. The Server-Side Application: A remote backend (e.g., on AWS, Google Cloud) that receives,
processes, and stores location data, and sends back relevant responses.
This interaction enables services like ride-sharing (Uber), food delivery (Zomato), location-based
reminders, and asset tracking.
Conceptual Diagram
This sequence diagram illustrates the end-to-end lifecycle of a Location-Based Service (LBS) within
an Android application. It tracks how data moves from a user's physical location to a backend server
and finally back to a visual map.
Phase 1: Permission & Initialization
P a g e 27 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
1. User Action: The process begins when the user opens the app or triggers a specific feature (like
"Find nearby coffee shops").
2. Permission Handshake: Android requires explicit consent for privacy-sensitive data. The
AndroidApp checks for permissions and prompts the user. The flow only continues once the
user clicks Grant Permissions.
Phase 2: Acquiring Raw Location Data
3. Hardware Request: The app communicates with the Location Provider (which uses a
combination of GPS satellites, Wi-Fi triangulation, and Cell Tower signals).
4. Data Retrieval: The provider sends back the raw coordinates:
o Latitude & Longitude: The exact numerical position.
o Accuracy: A radius (in meters) indicating how "sure" the GPS is of that spot.
Phase 3: Processing & External Communication
5. Local Processing: Before sending data to the server, the app may perform Reverse Geocoding
(turning coordinates into a readable address) and prepares a JSON "payload."
6. HTTP POST: The app sends the data to your Backend Server via a secure API call.
o Example Payload: { "user_id": "123", "lat": 40.7128, "lng": -74.0060 }
7. Server-Side Logic: Your backend receives the coordinates, saves them to a database (for
history/tracking), and queries for relevant information (like "Which shops are within 5km of
these coordinates?").
8. Server Response: The backend sends back a JSON response containing the results (nearby
places, status messages, etc.).
Phase 4: Visualization & Mapping
9. Map Tile Request: To show the user where they are, the app talks to the Google Maps API. It
sends the coordinates along with a unique API Key to verify the request.
10. Map Data Return: Google provides the visual "tiles" (the actual images of the streets and
terrain) and specific place details (icons, ratings).
11. UI Update: Finally, the AndroidApp refreshes the screen, showing the user's blue dot on a
map surrounded by the nearby locations fetched from the server.
Core Components
1. Location Sources on Android
Android uses a fusion of hardware and software to determine location. The primary providers are:
GPS (Global Uses satellites to High Accuracy (up to Slow to get a first fix. High
Positioning triangulate position. 5-10 meters). Works battery consumption.
System) Requires a clear view of the without internet. May not work well indoors
sky. or in dense urban areas.
P a g e 28 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
Wi-Fi Scans for nearby Wi-Fi Fast. Works well Requires internet for the
access points. The device indoors. Moderate lookup. Less accurate than
or Google's servers battery use. GPS (20-50 meters).
correlate these MAC
addresses with known
locations.
Cellular Uses the signal strength Very fast. Works Low accuracy (hundreds
(Network) from nearby cell towers to almost anywhere with of meters to kilometers).
triangulate a rough a signal. Lowest
location. battery consumption.
P a g e 29 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
• Places API: Provides information about points of interest (restaurants, hospitals, etc.) near a
location.
• Directions API: Calculates routes, distances, and estimated travel times between locations.
Server-Side Considerations
When building the backend, consider the following for an undergraduate project:
• API Design: Use REST principles. A typical endpoint might be:
o GET /api/users/{userId}/location → Get a user's location.
o POST /api/trips/{tripId}/locations → Upload a stream of locations for a trip.
• Database: Use a database that supports spatial queries.
• Security: Never expose your Google Maps API Key in the client app if it has usage
restrictions. For sensitive operations (like Directions API with significant costs), proxy the
request through your own server. Your server calls Google, then sends the result to the app.
Challenges :
1. Battery Drain: Frequent location updates can drain the battery.
o Solution: Use setPriority(Priority.PRIORITY_BALANCED_POWER_ACCURACY)
in LocationRequest. Request updates only when the app is in the foreground or use
significant motion triggers.
2. Privacy: Users are sensitive about location data.
o Solution: Always explain why you need location permissions. Use a clear and concise
privacy policy. Allow users to delete their location history.
3. Offline Functionality: GPS works without internet, but maps and server communication do
not.
o Solution: Cache map tiles for offline areas (if using Google Maps, this is a premium
feature). Queue location updates on the device using WorkManager and send them
when connectivity is restored.
4. Accuracy: GPS can be inaccurate in cities ("urban canyons") or indoors.
o Solution: Always check the accuracy field of the Location object. You can filter out
updates that are less accurate than your threshold (e.g., ignore if accuracy > 100m).
Interaction with Server-Side Applications using Wi-Fi in Android
Introduction
Wi-Fi in Android applications serves two critical purposes:
1. Network Connectivity: The medium through which your app communicates with remote
servers
2. Location Context: Wi-Fi networks themselves can provide location context (Wi-Fi Positioning
System/WPS)
Unlike GPS, Wi-Fi offers unique advantages for server interactions:
• Indoor/Urban reliability where GPS fails
P a g e 30 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
P a g e 31 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
P a g e 32 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
P a g e 33 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
B. Social Sharing
Sharing is simpler than login because it does not require a backend server in many cases. It uses
Android’s Intent System or the Social SDK’s sharing dialog.
• Implicit Intents: You can use ACTION_SEND to open a native share sheet. This allows the
user to choose which app (Instagram, Messages, etc.) to share to.
• SDK Specific Sharing: For a branded experience (e.g., "Share to Facebook Feed"), you use
the SDK. This avoids the chooser dialog and posts directly, though it requires the user to have
the social app installed and be logged in.
Architectural Diagram
Diagram Analysis:
• Left Side (Client): The interaction starts and ends on the device. The Social SDK acts as a
bridge between your app and the social platform’s UI. It handles the complex OAuth handshake
securely.
• Top Right (Social Platforms): These are external servers. They validate credentials and issue
tokens.
• Bottom Right (Your Infrastructure): This is the most critical part for security. Your
Android app should never trust the token alone. Your backend server must verify the token with
the Social Platform to ensure it hasn't been revoked and to fetch the authoritative user ID. After
verification, your server issues a proprietary token, making your app independent of the social
platform’s token expiration for future API calls.
P a g e 35 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT
Security Considerations
When integrating social media, must adhere to strict security guidelines to avoid data breaches:
1. Never Hardcode Secrets: Do not store App Secrets (the secret key from Facebook/Google) in
your Android code. Android apps can be decompiled. The App Secret should only reside on
your Backend Server.
2. Token Verification: As illustrated in the diagram, always verify the token on the server side.
A malicious user could generate a fake token on a rooted device. Server-side verification
ensures the token is genuine before granting access to your database.
3. Scopes: Request only the minimal permissions (scopes) required. If you only need the user’s
email and name, do not request user_friends or user_posts. Over-requesting permissions scares
users and may lead to app store rejection.
4. Network Security: Ensure that token transmission between the Android app and your server is
done over HTTPS (SSL/TLS). Never send tokens over plain HTTP.
Summarize :
• Lifecycle Awareness: Understanding the Activity and Fragment lifecycle is non-negotiable.
Proper handling of onPause(), onStop(), and onDestroy() prevents memory leaks and data loss.
• Component Integration: The [Link] file acts as the application's seal, requiring
explicit declarations for all components and permissions before they can function.
• Data Persistence: For complex data structures, SQLite/Room is superior to
SharedPreferences, offering structured query capabilities and type safety.
• UI/UX Standards: Adhering to Material Design guidelines ensures consistency across
devices, while ConstraintLayout helps create flexible, flat view hierarchies that improve
rendering performance.
• Future Scope: To scale this application further, focus would shift to
implementing WorkManager for background tasks, integrating Cloud Firestore for real-time
data syncing, and writing comprehensive UI tests using Espresso.
P a g e 36 | 36
Prepared by K Anuranjnai