0% found this document useful (0 votes)
2 views36 pages

Module IV Technology I - Android

The document provides an overview of Android, an open-source, Linux-based operating system for mobile devices, detailing its architecture, key features, and development environment. It covers aspects such as user experience, productivity, connectivity, privacy, and security, as well as the layered structure of Android that includes the Linux kernel, Android Runtime, and application framework. Additionally, it highlights the tools and libraries available for developers to create applications that enhance user interaction and functionality.

Uploaded by

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

Module IV Technology I - Android

The document provides an overview of Android, an open-source, Linux-based operating system for mobile devices, detailing its architecture, key features, and development environment. It covers aspects such as user experience, productivity, connectivity, privacy, and security, as well as the layered structure of Android that includes the Linux kernel, Android Runtime, and application framework. Additionally, it highlights the tools and libraries available for developers to create applications that enhance user interaction and functionality.

Uploaded by

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

U20CSOT01 MOBILE APPLICATION DEVELOPMENT

MODULE IV TECHNOLOGY I - ANDROID


Introduction – Establishing the development environment – Android architecture – Activities and
views – Interacting with UI – Persisting data using SQLite – Packaging and deployment –
Interaction with Server Side applications using Google Maps, GPS and Wi-Fi – Integration with
Social Media applications.
Introduction
What is Android?
Android is an open-source, Linux-based operating system primarily designed for touchscreen mobile
devices such as smartphones and tablets. It was developed by Android Inc., which was acquired by
Google in 2005.
Key Features of Android
• Open Source: Based on Linux kernel, available under Apache License
• Customizable UI: Highly customizable home screens, widgets, and launchers
• Google Services Integration: Seamless integration with Gmail, Maps, Drive, etc.
• Multi-tasking: True multi-tasking capability
• Large App Ecosystem: Google Play Store with millions of apps
• Multiple Language Support: Supports numerous languages
• Various Connectivity Options: GSM, CDMA, Wi-Fi, Bluetooth, NFC, 5G/4G/3G
• Rich Media Support: Supports various audio, video, and image formats
Android is a software package and linux based operating system for mobile devices such as tablet
computers and smart phones released first version in 2007. It is developed by Google and later the OHA
(Open Handset Alliance). Android is a complete set of software for mobile devices such as tablet
computers, notebooks, smart phones, electronic book readers, set-top boxes etc. It contains a linux-
based Operating System, middleware and key mobile applications. It can be thought of as a mobile
operating system. But it is not limited to mobile only. It is currently used in various devices such as
mobiles, tablets, televisions etc.
Java language is mainly used to write the android code even though other languages can be used. The
goal of android project is to create a successful real-world product that improves the mobile experience
for end users. There are many code names of android such as Lollipop, Kitkat, Jelly Bean, Ice cream
Sandwich, Froyo, Ecliar, Donut etc.
Features of Andriod :
Android is a versatile and feature-rich operating system that powers billions of devices worldwide. Its
features range from core system capabilities to user-centric tools for customization, privacy, and
productivity.

P a g e 1 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT

Core System and Architecture


At its heart, Android is a powerful software stack built for a wide range of devices.
• Linux Kernel Foundation: The operating system is built on the Linux kernel, which handles
core system services like security, memory management, and process management. This kernel
also acts as an abstraction layer between the software and the device's hardware .
• Optimized Runtime: Android applications run in the Android Runtime (ART) , which is
designed to be fast and efficient for mobile devices with limited memory and processing power.
It uses optimizations like pre-verification and install-time bytecode optimization to speed up
app execution .
• Hardware Abstraction: A Hardware Abstraction Layer (HAL) provides standard interfaces
for hardware vendors, allowing Android to work seamlessly with various components like
cameras, GPS, and accelerometers across thousands of different devices .
User Experience and Customization
Android is known for its flexibility and personalization options, allowing users to make their device
truly their own.
• Visual Customization: You can personalize your device with a system-wide dark theme to
save battery and reduce eye strain, or customize your lock screen . Unlike some other platforms,
Android allows you to place widgets on your home screen for at-a-glance information from
apps like your calendar or music player .
• Intuitive Navigation: Modern versions of Android feature a fully gestural navigation system
that allows you to use edge swipes to go back, go home, and switch between apps, creating a
more immersive, full-screen experience .
• Accessibility Features: Android includes powerful built-in accessibility tools. Live
Transcribe provides real-time captions for conversations and media in over 70 languages,
while Sound Amplifier can filter background noise to clarify speech and other audio .

P a g e 2 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT

Productivity and Multitasking


Android is designed to help you get more done, whether for work or personal projects.
• Powerful Multitasking: You can run two apps side-by-side with split-screen mode, which is
excellent for taking notes while watching a video or comparing items. Picture-in-Picture
(PiP) lets you continue a video call or streaming show in a small window while you use other
apps .
• Smart Interactions: Android simplifies everyday tasks. Smart Reply in notifications suggests
quick responses to messages, while you can instantly translate text in menus or signs just by
pointing your camera at them .
• Flexible App Choices: You have the freedom to set your own default apps for web browsing,
messaging, or navigation, ensuring your phone works the way you want it to .
Connectivity and Sharing
Android offers robust options for staying connected and sharing content with others.
• Seamless File Sharing: Quick Share (formerly Nearby Share) allows you to quickly and
securely transfer files, photos, and links to other nearby Android devices, Chromebooks, and
even some Windows PCs .
• Versatile Network Support: Android supports a wide range of connectivity options,
including 5G for faster speeds, Wi-Fi, Bluetooth, and NFC for contactless payments. Many
Android phones also feature dual SIM with eSIM support, making it easy to manage separate
work and personal numbers on one device .
Privacy and Security
Android puts you in control of your data and keeps your device safe with multiple layers of protection.
• Granular Permissions: You have fine-grained control over what information apps can access.
You can grant permissions, such as for location, only while the app is in use. You'll also receive
notifications if an app accesses your location in the background .
• Built-in Protection: Google Play Protect continuously scans apps on your device for harmful
behavior. The platform also receives regular security updates and includes advanced features
like file-based encryption and a secure biometric authentication framework for fingerprint and
face unlock .
• Data Minimization: Android restricts apps from accessing non-resettable device identifiers
(like your IMEI) to prevent tracking. Features like scoped storage ensure apps have limited
access to your files, only being able to see the media they created or that you specifically grant
access to .
Intelligent Features and Digital Wellbeing
Android leverages on-device intelligence to make your life easier and help you find a healthy balance
with technology.
• AI-Powered Tools: Features like Circle to Search let you quickly search for anything on your
screen by simply circling it. Google Lens is deeply integrated, allowing you to identify objects,
plants, and landmarks, or copy and paste text from the real world using your camera .
• Digital Wellbeing: Tools like the Digital Wellbeing dashboard give you a clear picture of
your screen time, how often you unlock your phone, and how many notifications you receive.
P a g e 3 | 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.

Android Runtime (ART) and Native Libraries


P a g e 6 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT

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

Activities and Views


The core building blocks or fundamental components of android are activities, views, intents, services,
content providers, fragments and [Link].

• 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: The Presentation Controller


An Activity is a fundamental component of an Android application. It represents a single screen
with a user interface. Think of it as the "controller" or "presenter" for a specific task or screen in
your app.
• Analogy: An Activity is like a page in a book or a window in a desktop application.
• Key Characteristics:
o Each Activity is an independent, self-contained unit.
o An app can have one or more Activities.
o Activities manage their own lifecycle (creation, pause, resume, destruction).
o One Activity is designated as the "main" or "launcher" Activity (the entry point).
The Activity Lifecycle
The Activity lifecycle is a set of states an Activity can be in, managed by the Android system.
Understanding this is critical to building stable apps. The system calls specific callback methods as
the Activity moves between states.

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.

The View: The UI Building Block


A View is the basic building block for user interface components in Android. A View occupies a
rectangular area on the screen and is responsible for drawing and event handling.
• Analogy: A View is like a Lego brick. You combine different types of bricks to build a
complex structure (the screen).
P a g e 10 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT

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

• The Activity sets a root layout using setContentView([Link].activity_main).


• The root is a ViewGroup (like ConstraintLayout). It's invisible but organizes its children.
• The root can contain other ViewGroups (like LinearLayout) which act as nested containers.
• The leaves of this tree are Views (like Button, TextView) that actually display data and
receive user input.
Types of Views

Category Examples Purpose

Widgets TextView, Button, Interactive or display components


EditText, ImageView, that the user directly sees and interacts
CheckBox, Switch with to perform actions or view
information.
Layouts LinearLayout, Invisible containers that define the
RelativeLayout, structure and arrangement of child
ConstraintLayout, views. ConstraintLayout is the modern,
FrameLayout, GridLayout recommended choice.

AdapterViews ListView, RecyclerView, Dynamic collection views that use an


Spinner Adapter to bind large sets of data to
items. RecyclerView is the modern,
high-performance successor to
ListView.

Connecting Activity and Views: The Complete Picture


The Activity and its Views work in tandem. The Activity inflates the View hierarchy, manages its
lifecycle, and handles user interactions.

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

The UI Interaction Architecture

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

4. APPLICATION FRAMEWORK (Java/Kotlin space)


• WindowManagerService
A system service that manages window states, focus, and layer ordering. It works closely with
InputDispatcher to route events correctly.
• ViewRootImpl
Acts as the bridge between the WindowManager and the app’s View hierarchy.
o It receives dispatched events from the system.
o Converts them into Android MotionEvent objects.
o Delivers them to the root view of the activity.
5. ACTIVITY & VIEW HIERARCHY
• The event is passed down the View hierarchy (starting from the topmost ViewGroup).
• The system determines which view should handle the touch based on:
o onInterceptTouchEvent (for ViewGroups) – decides whether to intercept the event or
pass to children.
o dispatchTouchEvent – propagates the event down the tree.
o onTouchEvent – handles the touch at the view level.
6. EVENT LISTENERS & CALLBACKS
Once a view receives the event, it can respond using:
• OnClickListener – triggered on ACTION_UP when a tap is recognized.
• OnTouchListener – receives raw touch events (down, move, up) and can consume them early.
• OnKeyListener – handles key events (hardware buttons or soft keyboard).
Types of User Interactions

P a g e 14 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT

1. The Event Object: MotionEvent


When the system detects a touch, it packages all the data into a MotionEvent object. This object
contains:
• Action: The type of touch event (e.g., ACTION_DOWN (finger
down), ACTION_MOVE (finger moves), ACTION_UP (finger lifts), ACTION_CANCEL).
• Coordinates: The X and Y position of the touch.
• Meta-data: Pressure, size, and pointer index (for multi-touch).
2. Entry Point: [Link]()
The event first enters the Application Framework layer at the Activity level.
• dispatchTouchEvent() is the main entry point for event handling in an Activity.
• Default Behavior: By default, this method sends the event down to the View hierarchy (via the
root view). However, an Activity can override this method to intercept all touch events before
they reach any views.
3. The Decision Tree: [Link]()
The event is passed to the top-level ViewGroup (usually a layout
like ConstraintLayout or FrameLayout). At this stage, the system must decide: Should I handle this
myself, or should I give it to my child?
This decision is managed by a crucial method: onInterceptTouchEvent()
Scenario A: Intercept (Parent handles it)
• If the parent ViewGroup returns true for onInterceptTouchEvent():
o Meaning: The parent is saying, "I want this touch sequence."
o Result: The event is sent to the parent's onTouchEvent().
o Use Case: A ScrollView or SwipeRefreshLayout intercepting touches to start scrolling
instead of letting a child button handle the click.
Scenario B: Do Not Intercept (Child handles it)
• If the parent ViewGroup returns false for onInterceptTouchEvent():
o Meaning: "This touch is not for me; pass it to my children."
o Result: The event travels down to the Child View's dispatchTouchEvent().
o The child then repeats the process (if it is a ViewGroup) or handles it directly.
4. The End Point: [Link]()
Once the event reaches a leaf View (like a Button or TextView) that is not a container:
• dispatchTouchEvent() calls onTouchEvent() on that specific view.
• The view determines if it "handles" the event (e.g., a button highlights, or a text field receives
focus).
5. Propagation: Handled vs. Not Handled

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

1. User Interaction Begins


User Touches Screen → This triggers the hardware and kernel layers (as seen in your previous
diagrams), ultimately generating a MotionEvent in the Android framework.
2. MotionEvent Object Creation
The system creates a MotionEvent object containing:
• Action Type: ACTION_DOWN (touch starts), ACTION_MOVE (finger
moves), ACTION_UP (touch ends), or ACTION_CANCEL (event interrupted)
• Data: Coordinates (X, Y), pressure, touch size, pointer information, etc.
The arrow labeled "Data Arrow" indicates that this event object flows through the system to the View
hierarchy.

P a g e 16 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT

3. View Hierarchy Event Dispatch


Level 1: [Link]()
• This is the entry point into the application's UI layer.
• The Activity receives the MotionEvent and, by default, forwards it to the root ViewGroup of its
layout.
Level 2: [Link]()
• The root ViewGroup (or any parent container) receives the event.
• It calls onInterceptTouchEvent() to decide:
o "Check if parent handles event" — This is the key decision point.
Decision Path:

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

Level 3: Child [Link]()


• If the child is a ViewGroup, the process repeats (intercept check, pass to its children).
• If the child is a leaf View (e.g., Button, TextView), it calls its own onTouchEvent().
Level 4: onTouchEvent() — Handled by View
• This is where the event is consumed.
• The View processes the touch (e.g., button highlights, click triggers, text input focus).
• The diagram notes: "Event consumed here by the target View."

Concept Description Key Points

MotionEvent Object containing touch data ACTION_DOWN, ACTION_MOVE,


ACTION_UP, coordinates, pressure

Event Dispatch How events travel through Activity → ViewGroup → View


view hierarchy
onInterceptTouchEvent ViewGroup method to Return true to consume the event before it
intercept events reaches the child

GestureDetector Helper for common gestures Double tap, long press, fling, scroll

Listeners Callback interfaces for onClick, onTouch, onKey, onFocusChange


events

View Binding Modern way to access views Type-safe, null-safe alternative to


findViewById

P a g e 17 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT

Persisting data using SQLite


Introduction to SQLite
SQLite is an embedded, serverless, self-contained SQL database engine. It's the native database
solution for Android due to its lightweight nature and zero-configuration setup.
Key Characteristics:
• Serverless: No separate server process; direct file access
• Zero-configuration: No setup or administration needed
• Cross-platform: Database file is portable across systems
• Transactional: ACID-compliant (Atomicity, Consistency, Isolation, Durability)
• Compact: Library size ~600KB
Why SQLite for Android?
Android includes SQLite as its native database system because:
1. No network overhead - Local storage only
2. Low memory footprint - Perfect for mobile devices
3. Built-in support - No additional libraries required
4. Reliable - Transaction support ensures data safety
The Concept of Data Persistence

• Data persistence is a fundamental concept in software development that refers to the


characteristic of data that outlives the process that created it.
• In the context of Android application development, persistence means storing data in such a
way that it remains available even after the application is closed, the device is restarted, or the
system needs to reclaim memory resources.
• Without persistence, all data entered by users or generated by the application would be lost the
moment the application terminates, making the application virtually useless for any meaningful
work.
• Imagine developing a note-taking application where every note disappears when you close the
app, or a to-do list that resets every time you open it. Such applications would fail to serve their
intended purpose. This is why data persistence mechanisms are crucial components of virtually
all non-trivial Android applications.
• Android provides several persistence options including
✓ SharedPreferences for key-value pairs,
✓ internal and external file storage for raw files
✓ SQLite databases for structured data storage.
Among these options, SQLite databases offer the most robust solution for applications that need
to store complex, relational data with powerful querying capabilities.
SQLite :
SQLite that makes it suitable for storing critical application data is its ACID compliance. ACID stands
for Atomicity, Consistency, Isolation, and Durability - a set of properties that guarantee database

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

The Role of SQLiteOpenHelper in Android

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

META-INF/ Contains the manifest file ([Link]), certificate ([Link]), and


signature list ([Link]). Used for security and verification.

lib/ Native libraries (written in C/C++) organized by Application Binary


Interface (ABI): armeabi-v7a, arm64-v8a, x86, etc.
res/ Uncompiled resources (layouts, images, strings) that were not compiled
into [Link].

assets/ Raw resource files (fonts, JSON files) accessed via AssetManager.

[Link] The compiled Java/Kotlin bytecode converted to Dalvik Executable (DEX)


format. Larger apps may have multiple DEX files ([Link]).

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

The Android App Bundle (AAB)


Since August 2021, AAB (Android App Bundle) is the official publishing format for Google Play.
• How it works: Instead of generating one APK for all devices, the developer uploads an AAB
to Google Play. Google Play then generates optimized APKs (split APKs) specific to the user’s
device configuration (e.g., only arm64 libraries, only hdpi images).
• Advantage: Smaller download sizes for users (typically 15-35% smaller).
The Build Process
Role of Gradle
Gradle is the build system for Android. The build configuration is defined in [Link] files (Project-
level and Module-level). It automates the process of compiling, merging resources, and signing.
Build Types and Product Flavors
• Build Types: Define how the app is built.
o debug: Includes debugging symbols, debuggable=true, uses debug keystore.
o release: Optimized, minified (R8/ProGuard), debuggable=false, requires a release
keystore.
• Product Flavors: Used to create different versions of the app
(e.g., free, paid, staging, production).
Combination: Build Variant = Product Flavor + Build Type (e.g., freeRelease, paidDebug).

P a g e 23 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT

Step-by-Step Build Pipeline


1. Compilers:
o Kotlin/Java code → .class files.
o .class + 3rd party libraries → .dex (Dalvik Executable) files via D8/R8.
2. Resource Compilation:
o res/ directory → Compiled binary [Link].
o [Link] → Binary XML.
3. APK/AAB Generation:
o The Android Asset Packaging Tool (AAPT2) packages all compiled resources and
DEX files into a single archive.
4. Signing:
o The archive is signed (aligned) with a keystore to prove authorship.
5. Post-Processing (Release only):
o Code Shrinking (R8/ProGuard): Removes unused code.
o Resource Shrinking: Removes unused resources.
o Zipalign: Aligns byte boundaries for optimized memory usage at runtime.
Keystore Management
A keystore is a binary file containing a set of private keys. To sign an app:
1. Generate a keystore using keytool (JDK tool) or Android Studio (Build > Generate Signed
Bundle / APK).
2. Use Google Play App Signing (recommended). Google manages your signing key, and you
upload an upload key. This prevents disaster if you lose your local keystore.
Deployment Strategies
Deployment on a Physical Device
• Prerequisites:
o Enable Developer Options (Tap Build Number 7 times in Settings).
o Enable USB Debugging.
o Install USB drivers (for Windows).
• Process: Connect device via USB, click "Run" in Android Studio. ADB (Android Debug
Bridge) installs the APK.
Deployment on an Emulator
• Prerequisites: Android Virtual Device (AVD) configured.
• Process: Android Studio installs the APK to the virtual device. Emulators simulate different
screen sizes, Android versions, and hardware (GPS, Camera).

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:

Provider Description Advantages Disadvantages

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.

2. The Android Client


The client app's responsibilities:
1. Permissions: Requesting runtime permissions for ACCESS_FINE_LOCATION (GPS)
or ACCESS_COARSE_LOCATION (Wi-Fi/Cellular).
2. Fetching Location: Using the FusedLocationProviderClient to get last known location or
request real-time updates.
3. Displaying Maps: Embedding a MapView or SupportMapFragment to display the location
and points of interest using the Google Maps SDK.
4. Networking: Sending location data to the server using libraries like Retrofit or Volley.
5. UI Update: Refreshing the user interface based on the server's response.
3. The Server-Side Application
This is the backend that powers the app. It can be built with any language ([Link], Python, Java, PHP,
etc.). Its responsibilities:
1. API Endpoints: Exposing RESTful endpoints (e.g., POST /api/location/update) to receive data
from the Android client.
2. Database: Storing user locations, profiles, and geographical points of interest. For location-
based queries (e.g., "find all users within 1km"), a spatial database like PostgreSQL with
PostGIS or MongoDB with Geospatial indexes is essential.
3. Business Logic: Processing the incoming location. For example, if a delivery person's location
is updated, the server might check if they are within 100m of a delivery point and automatically
mark it as "arrived."
4. Authentication: Verifying that the incoming request is from a legitimate user.
4. Google Maps API (External Service)
This is a suite of APIs provided by Google that the Android client and backend can use.
• Maps SDK for Android: Used to display interactive maps within the app.
• Geocoding API: Converts an address (e.g., "1600 Amphitheatre Parkway") into geographic
coordinates (lat/lng). Reverse Geocoding does the opposite (lat/lng → address).

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

• Lower battery consumption compared to continuous GPS


• Context awareness based on connected networks (home, work, cafe)
• Network quality metrics that can optimize server communication

Wi-Fi Infrastructure : Shows the external wireless access points.


Android Device : Details the internal application components, including the green Android App at the
top and the purple system services like Wi-Fi Manager and Retrofit below.
Data Processing: Highlights the analytical pipeline for determining location context, network metrics,
and behavioral patterns.
Cloud & Internet: Represents the external backend server and third-party APIs.
This layout clearly illustrates the data flow—from scanning Wi-Fi signals and interacting with the
device's operating system to processing analytics and communicating with the backend cloud.

P a g e 31 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT

Here is a detailed breakdown of the logic:


1. Data Acquisition Phase
• Scanning: The Android App initiates the flow by requesting Wi-Fi information from the Wi-
Fi Manager. This triggers a physical scan of nearby Access Points.
• Context Gathering: The Wi-Fi Manager returns a list of SSIDs (network names), BSSIDs
(MAC addresses), and signal strengths. The app uses this to "Determine Network Quality"
locally before attempting any network calls.
2. The Conditional Logic (alt block)
The diagram uses an Alternative (alt) block to handle the two possible states of the device's connection:
Scenario A: Network Available (Blue Zone)
• Transmission: The app sends an HTTP Request containing the "Wi-Fi Context" to the Backend
Server.
• Persistence: The server interacts with the Database to store the new data or query existing
records based on the user's location.
• Feedback: A JSON response is sent back to the app, which then performs a UI Update (e.g.,
showing a green "Connected" status or loading new content).
Scenario B: No Network (Red Zone)
• Queueing: Instead of simply failing or showing an error, the app performs a "Queue Request
Locally" action. This is a critical offline-first design pattern.
• User Feedback: The app shows an Offline UI (e.g., "Changes will sync when you're back
online"), ensuring the user doesn't think the app has crashed.
3. The Reconnection Logic (Wi-Fi Changes)
This final section explains how the app "heals" its state:
• Observation: The Wi-Fi Manager monitors the hardware. When a connection is restored, it
broadcasts a Network Change Event.
• Retry Mechanism: The Android App listens for this event. Upon receiving it, it automatically
pulls the previously saved requests from its local queue and executes Step 14: Retry Queued
Requests to the Backend Server.
This flow ensures data integrity (no data is lost when the signal drops) and a seamless user experience
(the app remains functional regardless of the internet state).
Core Wi-Fi Classes
Class Purpose Key Methods

WifiManager Main API for Wi-Fi getConnectionInfo(), startScan(),


operations getScanResults()

WifiInfo Current connection details getSSID(), getBSSID(), getRssi(),


getLinkSpeed()

P a g e 32 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT

ScanResult Nearby network SSID, BSSID, level, frequency, capabilities


information

ConnectivityManager Network availability registerNetworkCallback(),


monitoring getActiveNetworkInfo()

NetworkCallback Real-time network onAvailable(), onLost(),


changes onCapabilitiesChanged()

Integration with Social Media applications


Introduction
Social Media Integration (SMI) is the process of connecting an Android application with social
networking platforms (Facebook, Twitter, Instagram, etc.) to enhance user experience. It allows for:
• Single Sign-On (SSO): Reducing friction during login.
• Content Sharing: Posting text, images, or videos to a user’s feed.
• Data Fetching: Retrieving user profile information or friends lists.
Architectural Overview
Modern Android development discourages using platform-specific SDKs (like the old Facebook SDK)
in favor of Authorization Code Flow with PKCE or using Google’s Sign-In as a federated identity
provider.
System Architecture Diagram
Below is a conceptual diagram illustrating the interaction between the Android App, the Social
Platform’s Servers, and the Application Backend (if applicable).

P a g e 33 | 36
Prepared by K Anuranjnai
U20CSOT01 MOBILE APPLICATION DEVELOPMENT

Explanation of the Flow:


1. Initiation: The user taps a button. The Android app calls the Social SDK (e.g., Facebook SDK).
2. Authorization: The SDK opens a web view or native dialog. The user enters their credentials
on the Social Platform's page. Crucially, your app never sees the password.
3. Token Grant: If the user approves, the Social Platform sends an Access Token back to the
SDK within the Android app. This token is a temporary key that says, "This app is allowed to
act on behalf of this user for a limited time."
4. Verification: The Android app sends this token to your application’s Backend Server. This
step is critical for security. The server takes the token and calls the Social Platform’s API
(e.g., [Link]) to verify the token and fetch the user’s unique ID and email.
5. Session Creation: Your server creates its own session token (often a JWT) and sends it back
to the Android app. From this point on, the Android app uses your server’s token, ignoring the
social token for day-to-day operations.
Key Implementation Methods
Firebase Authentication (Recommended)
Firebase acts as a middleware. It abstracts the complexity of OAuth 2.0. You integrate one SDK
(Firebase) to handle multiple providers (Google, Facebook, Twitter, GitHub).
Advantages:
• Unified user object across providers.
• Handles token refresh automatically.
• Easy to link multiple accounts.
OAuth 2.0 with AppAuth (For Custom Backend)
If you are not using Firebase, the AppAuth for Android library is the industry standard. It supports
PKCE (Proof Key for Code Exchange), which is more secure than the implicit flow.
Platform-Specific SDKs (Legacy)
Directly using Facebook SDK or Google Sign-In SDK. While easier for simple sharing, it increases
APK size and requires managing multiple SDK versions.
Implementation: Login and Sharing
The implementation logic differs slightly between platforms, but the architectural pattern remains
consistent. We typically use Activity Results API to handle the login result.
A. Social Login (Authentication)
The primary function of social login is to obtain the user’s identity. The code structure usually follows
this pattern:
1. Client-Side Setup: Instantiate the client (e.g., GoogleSignInClient or LoginManager).
2. Launch Intent: Fire the login intent.
3. Handle Callback: Retrieve the AccessToken in the onActivityResult or via a callback listener.
4. Exchange Token: Send the token to your backend.
P a g e 34 | 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

You might also like