CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
❖ Location Based Services (LBS) in Android
Location Based Services (LBS) are Android features that allow applications to detect,
track, and use the geographical location of a device to provide location-specific services to
users.
Examples include Google Maps, cab booking apps, food delivery apps, weather apps, etc.
1. What are Location Based Services?
Definition:
Location Based Services use GPS, Wi-Fi, mobile networks, and sensors to determine a
device’s location and provide services based on that location.
Common Uses of LBS:
• Navigation and maps
• Finding nearby places (ATM, hospitals)
• Location tracking
• Geo-fencing
• Emergency services
2. Location Providers in Android
Android uses multiple location providers:
Provider Description
GPS Provider Uses satellites, highly accurate, works outdoors
Network Provider Uses mobile network & Wi-Fi, faster but less accurate
Fused Location Provider Google’s combined API (recommended)
Passive Provider Receives updates from other apps
Fused Location Provider is recommended because it balances accuracy, power usage,
and speed.
3. Permissions Required for LBS
Add permissions in [Link]:
<uses-permission android:name="[Link].ACCESS_FINE_LOCATION"/>
<uses-permission android:name="[Link].ACCESS_COARSE_LOCATION"/>
For Android 6.0+, runtime permission is mandatory.
❖ Using Global Positioning System (GPS) in Android
The Global Positioning System (GPS) is a satellite-based navigation system that allows
Android devices to determine their exact geographical location (latitude, longitude, altitude)
anywhere on Earth.
In Android, GPS is commonly used in Location Based Services (LBS) such as maps,
navigation, tracking, and location-aware applications.
1. What is GPS?
Definition:
GPS is a satellite-based system that uses signals from multiple satellites to calculate the
precise location of a device.
Page 1 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
Key Features:
• High accuracy (up to a few meters)
• Works best outdoors
• Independent of internet connection
• Uses satellites instead of network signals
2. How GPS Works (Conceptual Flow)
1. GPS satellites continuously transmit signals
2. Android device receives signals from at least 4 satellites
3. Device calculates position using triangulation
4. Location data is returned as latitude & longitude
3. GPS vs Network Location
Feature GPS Network Location
Accuracy High Medium
Speed Slower Faster
Internet Not required Required
Battery usage High Low
Works indoors No Yes
4. Permissions Required for GPS
Add the following permissions in [Link]:
<uses-permission android:name="[Link].ACCESS_FINE_LOCATION"/>
<uses-permission android:name="[Link].ACCESS_COARSE_LOCATION"/>
5. Using GPS with LocationManager (Core Android)
Step 1: Layout XML
activity_main.xml
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<Button
android:id="@+id/btnGPS"
android:text="Get GPS Location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/tvGPS"
android:text="GPS Location will appear here"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"/>
</LinearLayout>
Page 2 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
Step 2: Kotlin Code Using GPS Provider
[Link]
class MainActivity : AppCompatActivity(), LocationListener {
private lateinit var locationManager: LocationManager
override fun onCreate(savedInstanceState: Bundle?) {
[Link](savedInstanceState)
setContentView([Link].activity_main)
locationManager = getSystemService(Context.LOCATION_SERVICE) as
LocationManager
[Link] {
if ([Link](
this, [Link].ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
){
[Link](
this,
arrayOf([Link].ACCESS_FINE_LOCATION),
101
)
return@setOnClickListener
}
[Link](
LocationManager.GPS_PROVIDER,
5000,
5f,
this
)
}
}
override fun onLocationChanged(location: Location) {
val lat = [Link]
val lon = [Link]
[Link] = "Latitude: $lat\nLongitude: $lon"
}
}
6. GPS Using Fused Location Provider (Recommended)
Google’s Fused Location Provider API internally uses GPS, Wi-Fi, and mobile networks
for better accuracy and lower battery usage.
[Link] { location ->
if (location != null) {
val lat = [Link]
val lon = [Link]
[Link] = "Lat: $lat, Lon: $lon"
}
}
Page 3 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
7. Enabling GPS Programmatically
Check if GPS is enabled:
val isGPSEnabled =
[Link](LocationManager.GPS_PROVIDER)
Prompt user to enable GPS:
startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
8. Applications of GPS in Android
Application Use
Navigation apps Turn-by-turn navigation
Tracking apps Vehicle & fitness tracking
Emergency apps SOS location sharing
Maps Location & directions
Geofencing Location-based alerts
9. Advantages of GPS
✔ High location accuracy
✔ No internet required
✔ Global coverage
10. Limitations of GPS
High battery consumption
Slow initial fix
Poor indoor performance
❖ Geocoding Locations in Android
Geocoding is the process of converting geographic coordinates (latitude and longitude)
into a human-readable address, while Reverse Geocoding converts an address into
geographic coordinates.
Geocoding is widely used in maps, navigation apps, food delivery apps, and location-
based services.
1. What is Geocoding?
Definition:
Geocoding converts latitude and longitude into a readable address such as street name,
city, state, and country.
Reverse Geocoding:
Converts an address into latitude and longitude.
2. Types of Geocoding
Type Description Example
Geocoding Coordinates → Address (22.3039, 70.8022) → Rajkot, Gujarat
Reverse Geocoding Address → Coordinates “Rajkot, Gujarat” → (22.3039, 70.8022)
Page 4 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
3. Android Geocoder Class
Android provides the Geocoder class for geocoding and reverse geocoding.
Requirements
• Internet connection (for most devices)
• Location permission (if using current location)
4. Permissions Required
Add in [Link]:
<uses-permission android:name="[Link].ACCESS_FINE_LOCATION"/>
<uses-permission android:name="[Link]"/>
5. Reverse Geocoding Example (Latitude → Address)
Layout XML
activity_main.xml
<LinearLayout xmlns:android="[Link]
android:orientation="vertical"
android:padding="16dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btnAddress"
android:text="Get Address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/tvAddress"
android:text="Address will appear here"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"/>
</LinearLayout>
Kotlin Code
[Link]
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
[Link](savedInstanceState)
setContentView([Link].activity_main)
[Link] {
val latitude = 22.3039
val longitude = 70.8022
val geocoder = Geocoder(this, [Link]())
val addresses = [Link](latitude, longitude, 1)
if (![Link]()) {
val address = addresses[0]
val fullAddress = buildString {
append([Link](0)).append("\n")
append([Link]).append(", ")
append([Link]).append("\n")
Page 5 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
append([Link])
}
[Link] = fullAddress
} else {
[Link] = "Address not found"
}
}
}
}
6. Forward Geocoding Example (Address → Latitude & Longitude)
val geocoder = Geocoder(this, [Link]())
val addressList = [Link]("Rajkot, Gujarat", 1)
if (![Link]()) {
val location = addressList[0]
val lat = [Link]
val lon = [Link]
[Link] = "Latitude: $lat\nLongitude: $lon"
}
7. Common Address Components
Method Description
getAddressLine(0) Full address
locality City
adminArea State
postalCode PIN code
countryName Country
8. Applications of Geocoding
• Displaying user’s current address
• Finding nearby places
• Location tagging
• Delivery & navigation apps
• Emergency services
9. Limitations of Geocoder
Depends on internet connectivity
May return null on some devices
Not suitable for bulk requests
For large-scale geocoding, use Google Maps Geocoding API.
Page 6 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
❖ Mapping Locations in Android
Mapping Locations means displaying geographical locations on a map using latitude and
longitude. In Android, this is commonly done using Google Maps, which allows developers
to show maps, markers, routes, and user locations.
This topic is very important for BCA / BSc IT (Saurashtra University) and is widely used
in real-world Android applications.
1. What is Mapping Locations?
Definition:
Mapping Locations refers to the process of displaying places, routes, or user locations on a
digital map using mapping APIs.
Examples:
• Showing current location on Google Map
• Marking hospitals, colleges, or ATMs
• Displaying route from source to destination
2. Google Maps in Android
Android uses Google Maps API to display maps.
Features of Google Maps API
• Zoom in/out
• Add markers
• Show user’s current location
• Map types (Normal, Satellite, Hybrid)
• Polylines and routes
3. Requirements for Mapping Locations
1. Permissions
Add in [Link]:
<uses-permission android:name="[Link]"/>
<uses-permission android:name="[Link].ACCESS_FINE_LOCATION"/>
2. Google Maps API Key
• Create API key from Google Cloud Console
• Enable Maps SDK for Android
Add inside <application> tag:
<meta-data
android:name="[Link].API_KEY"
android:value="YOUR_GOOGLE_MAPS_API_KEY"/>
4. Full Visual Example: Mapping Location with Marker
Step 1: Layout XML
activity_maps.xml
<fragment
xmlns:android="[Link]
android:id="@+id/map"
android:name="[Link]"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Page 7 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
Step 2: Kotlin Code
[Link]
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var mMap: GoogleMap
override fun onCreate(savedInstanceState: Bundle?) {
[Link](savedInstanceState)
setContentView([Link].activity_maps)
val mapFragment = supportFragmentManager
.findFragmentById([Link]) as SupportMapFragment
[Link](this)
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
// Example Location: Rajkot, Gujarat
val rajkot = LatLng(22.3039, 70.8022)
// Add marker
[Link](
MarkerOptions()
.position(rajkot)
.title("Rajkot, Gujarat")
)
// Move camera
[Link]([Link](rajkot, 12f))
}
}
5. Showing User’s Current Location on Map
Add permission check and enable location:
if ([Link](
this, [Link].ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
){
[Link] = true
}
This displays a blue dot representing the user’s location.
6. Map Types
[Link] = GoogleMap.MAP_TYPE_NORMAL
[Link] = GoogleMap.MAP_TYPE_SATELLITE
[Link] = GoogleMap.MAP_TYPE_HYBRID
7. Adding Multiple Markers
val locations = listOf(
LatLng(22.3039, 70.8022), // Rajkot
LatLng(21.1702, 72.8311), // Surat
LatLng(23.0225, 72.5714) // Ahmedabad
)
for (loc in locations) {
[Link](MarkerOptions().position(loc))
}
Page 8 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
8. Applications of Mapping Locations
Application Usage
Google Maps Navigation
Cab booking apps Driver & rider tracking
Delivery apps Order location
Emergency services SOS location
Tourism apps Nearby attractions
9. Advantages of Mapping Locations
✔ Easy visualization of geographic data
✔ Interactive maps
✔ Real-time updates
✔ User-friendly navigation
10. Limitations
Requires internet
API key dependency
Battery usage with continuous updates
❖ More Topics in Location Based Services (LBS)
Location Based Services in Android are not limited to just GPS and Maps. Modern Android
applications use advanced LBS techniques to deliver accurate, efficient, and intelligent
location-aware features.
1. Fused Location Provider (Advanced LBS)
Definition:
Fused Location Provider is a Google Play Services API that combines GPS, Wi-Fi, cellular
networks, and sensors to provide the best possible location with minimum battery usage.
Advantages:
• Better accuracy
• Low battery consumption
• Automatic provider selection
Key Class:
FusedLocationProviderClient
Usage Example:
[Link] { location ->
if (location != null) {
val lat = [Link]
val lon = [Link]
}
}
Page 9 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
2. Location Updates (Real-Time Tracking)
Definition:
Location updates continuously track a user’s movement over time.
Used In:
• Fitness tracking apps
• Navigation apps
• Vehicle tracking systems
Example:
val locationRequest = [Link]().apply {
interval = 5000
fastestInterval = 2000
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
}
3. Geofencing
Definition:
Geofencing creates a virtual boundary around a geographic location and triggers an action
when the user enters or exits that area.
Example Use Cases:
• Attendance systems
• Location-based reminders
• Security alerts
Geofence Types:
• Enter
• Exit
• Dwell
4. Location Accuracy Levels
Android supports different accuracy modes:
Mode Accuracy Battery Usage
HIGH_ACCURACY Very High High
BALANCED_POWER_ACCURACY Medium Medium
LOW_POWER Low Low
NO_POWER Very Low Minimal
5. Background Location Tracking
Definition:
Tracking location when the app is running in background.
Requirements:
• Foreground service
• Notification visible to user
• Android 10+ background permission
Permission:
<uses-permission
android:name="[Link].ACCESS_BACKGROUND_LOCATION"/>
Page 10 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
6. Location Permissions Model
Android uses a runtime permission system.
Permission Purpose
ACCESS_FINE_LOCATION GPS accuracy
ACCESS_COARSE_LOCATION Network-based
ACCESS_BACKGROUND_LOCATION Background tracking
7. Location History & Logging
Definition:
Storing past locations for analysis.
Used In:
• Fitness apps
• Delivery tracking
• Travel history
Example Storage:
• SQLite / Room
• Cloud (Firebase)
8. Reverse Location Lookup
Definition:
Converting coordinates to place names (Reverse Geocoding).
Example Output:
Latitude: 22.3039
Longitude: 70.8022
Address: Rajkot, Gujarat, India
9. Location-Based Notifications
Definition:
Notifications triggered by location changes.
Example:
• Notify user when near college
• Alert when entering restricted area
10. Indoor Location Services
Definition:
Location tracking inside buildings using:
• Wi-Fi signals
• Bluetooth beacons
• Sensors
Used In:
• Shopping malls
• Airports
• Hospitals
11. Location Sharing
Definition:
Sharing real-time location with other users.
Page 11 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
Used In:
• Google Maps live location
• Family tracking apps
Technologies Used:
• GPS
• Internet
• Cloud database
12. Location Privacy & Security
Concerns:
• User privacy
• Unauthorized tracking
Best Practices:
• Ask permission clearly
• Use location only when needed
• Allow user to disable tracking
13. Battery Optimization in LBS
Techniques:
• Reduce update frequency
• Use balanced accuracy
• Stop updates when not required
14. LBS Architecture Diagram (Textbook)
GPS / Wi-Fi / Cell Towers
↓
Fused Location Provider
↓
Android Location API
↓
Application Logic
↓
Maps / Alerts / Tracking
15. Real-World Applications of Advanced LBS
Application LBS Feature
Google Maps Navigation, traffic
Uber / Ola Live driver tracking
Swiggy / Zomato Order location
Fitness Apps Route & distance
Emergency Apps SOS location
Page 12 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
❖ Android Networking API
Introduction
Android Networking API allows Android applications to connect to the internet and
exchange data with remote servers. Using networking APIs, apps can fetch data from web
services, APIs, cloud servers, and send user data securely over the network.
Networking is essential for:
• Online applications
• Cloud-based apps
• Real-time data synchronization
Need for Networking in Android
• Fetch data from server
• Upload user data
• Access REST APIs
• Download images, videos, files
• Real-time communication
Network Types Supported by Android
1. Wi-Fi
2. Mobile Data (2G / 3G / 4G / 5G)
3. Ethernet (limited devices)
Internet Permission
To use networking, the following permission must be declared in [Link]:
<uses-permission android:name="[Link]"/>
To check network state:
<uses-permission android:name="[Link].ACCESS_NETWORK_STATE"/>
Core Android Networking APIs
1. ConnectivityManager
Definition:
ConnectivityManager is used to check network connectivity status.
Example:
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val network = [Link]
if (network != null && [Link]) {
// Internet available
}
2. NetworkInfo
Provides information about the current network:
• Connected or not
• Network type (Wi-Fi / Mobile)
3. HttpURLConnection
Definition:
HttpURLConnection is a built-in Android API for making HTTP network requests.
Page 13 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
Steps:
1. Create URL
2. Open connection
3. Set request method
4. Read response
Example:
val url = URL("[Link]
val connection = [Link]() as HttpURLConnection
[Link] = "GET"
val input = [Link]().readText()
HTTP Request Methods
Method Description
GET Fetch data
POST Send data
PUT Update data
DELETE Remove data
4. JSON Data Handling
Most Android apps communicate using JSON format.
JSON Example:
{
"name": "Android",
"version": 14
}
Parsing JSON in Kotlin:
val jsonObject = JSONObject(response)
val name = [Link]("name")
5. Background Networking (Important)
Network operations cannot be performed on main UI thread.
Methods used:
• Thread
• AsyncTask (Deprecated)
• ExecutorService
• Coroutines (Recommended)
Coroutine Example:
[Link]([Link]) {
// Network code here
}
6. Popular Android Networking Libraries
a) Volley
• Easy to use
• Automatic caching
• Best for small requests
val queue = [Link](this)
Page 14 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
b) Retrofit (Most Popular)
• REST API client
• Uses annotations
• Works with JSON easily
@GET("users")
suspend fun getUsers(): List<User>
c) OkHttp
• Fast & efficient
• Handles caching and retries
7. REST API Concept
REST (Representational State Transfer) is a web service architecture.
Features:
• Uses HTTP
• Stateless
• JSON / XML response
8. Secure Networking (HTTPS)
• Android recommends HTTPS
• Prevents data theft
• Uses SSL/TLS encryption
Cleartext HTTP is blocked in newer Android versions.
9. Network Security Configuration
To allow HTTP:
<network-security-config>
<base-config cleartextTrafficPermitted="true"/>
</network-security-config>
10. Uploading Data to Server
Used for:
• Login
• Registration
• Forms
Example:
[Link] = "POST"
[Link]([Link]())
11. Downloading Data
• Images
• Files
• PDFs
Uses:
• DownloadManager
• HttpURLConnection
Page 15 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
12. Handling Network Errors
Common errors:
• No internet
• Timeout
• Server error
Best practice:
• Show user-friendly message
• Retry logic
13. Checking Network Type
if ([Link] == ConnectivityManager.TYPE_WIFI) {
// Wi-Fi connected
}
14. Android Networking Architecture
Application
↓
Networking API / Library
↓
HTTP / HTTPS
↓
Internet
↓
Server / Cloud
15. Advantages of Android Networking API
• Real-time data access
• Cloud integration
• Scalable applications
16. Limitations
• Requires internet
• Battery usage
• Network dependency
17. Exam-Important Points
• INTERNET permission is mandatory
• Network code must run in background
• Retrofit is preferred for REST APIs
• JSON is commonly used
• HTTPS is secure
18. Real-World Applications
• Social media apps
• Online shopping apps
• Weather apps
• Banking apps
Page 16 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
❖ Android Web API
Introduction
An Android Web API allows an Android application to communicate with a web server
using the internet. Through Web APIs, Android apps can send requests to a server and
receive responses in formats such as JSON or XML.
Web APIs are widely used in modern Android applications for data exchange,
authentication, cloud services, and real-time updates.
What is a Web API?
A Web API (Application Programming Interface) is a set of rules and endpoints
provided by a server that allows client applications (like Android apps) to access server-side
data or services over HTTP/HTTPS.
Role of Web API in Android Applications
Android Web APIs are used to:
• Fetch data from servers
• Send user input to backend systems
• Perform login and registration
• Access cloud databases
• Synchronize data across devices
Common Web API Data Formats
1. JSON (JavaScript Object Notation) – Most commonly used
2. XML (Extensible Markup Language) – Older systems
3. Plain Text – Simple responses
Example JSON Response:
{
"id": 101,
"name": "Android",
"version": "14"
}
Communication Protocols Used
Android Web APIs use:
• HTTP – Unsecured
• HTTPS – Secured (Recommended)
HTTP Request Methods
Method Purpose
GET Retrieve data from server
POST Send data to server
PUT Update existing data
DELETE Remove data
Page 17 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
Web API Architecture in Android
Android App
↓
Web API (HTTP/HTTPS)
↓
Web Server
↓
Database
Internet Permission Requirement
To access Web APIs, the following permission is mandatory:
<uses-permission android:name="[Link]"/>
Android Components Used with Web APIs
• Activities / Fragments (UI)
• Background Threads / Coroutines
• Networking Libraries
• JSON Parsers
Using Web API with HttpURLConnection
Steps:
1. Create URL
2. Open connection
3. Set request method
4. Read response
Example (GET request):
val url = URL("[Link]
val connection = [Link]() as HttpURLConnection
[Link] = "GET"
val response = [Link]().readText()
Using Web API with Retrofit (Recommended)
Retrofit is a popular Android library for consuming Web APIs easily.
API Interface:
interface ApiService {
@GET("users")
suspend fun getUsers(): List<User>
}
Advantages of Using Retrofit
• Simple annotations
• Automatic JSON conversion
• Error handling
• Clean architecture
Authentication in Web APIs
Common authentication methods:
• API Keys
• Username & Password
Page 18 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
• Tokens (JWT, OAuth)
Error Handling in Web APIs
Common errors:
• 400 – Bad Request
• 401 – Unauthorized
• 404 – Not Found
• 500 – Server Error
Security in Android Web API
• Use HTTPS only
• Avoid hard-coding API keys
• Use network security config
• Validate server responses
Background Execution Rule
Android does not allow network operations on the main thread.
Recommended approaches:
• Kotlin Coroutines
• Executor Service
Real-World Applications of Android Web API
• Social media apps
• Online banking
• Weather forecasting
• E-commerce apps
• Online education platforms
Advantages of Android Web API
• Real-time data
• Cloud connectivity
• Scalable applications
• Platform independence
Limitations
• Internet dependency
• Security risks if misused
• Server availability required
Exam-Important Points
• Web API connects Android app to server
• JSON is most commonly used format
• Retrofit is preferred library
• INTERNET permission is mandatory
• Network calls must be in background
Page 19 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
❖ Android Telephony API
Introduction
The Android Telephony API provides access to telephony services available on an Android
device. It allows applications to interact with mobile network information, SIM card
details, call state, signal strength, and SMS services.
This API is mainly used in applications related to phone calls, messaging, network
monitoring, and telecom-based services.
Purpose of Android Telephony API
The Telephony API is used to:
• Get information about the mobile network
• Detect call states (ringing, off-hook, idle)
• Access SIM card details
• Send and receive SMS
• Monitor signal strength and network type
Key Classes of Android Telephony API
1. TelephonyManager
Definition:
TelephonyManager is the main class used to access telephony services and network
information.
Functions provided:
• Network operator name
• SIM serial number
• Phone type (GSM/CDMA)
• Network type (2G/3G/4G/5G)
Example (Kotlin):
val telephonyManager =
getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
val networkOperator = [Link]
2. Phone State Listener
Definition:
PhoneStateListener is used to listen to changes in call state.
Call states:
• CALL_STATE_IDLE
• CALL_STATE_RINGING
• CALL_STATE_OFFHOOK
Example:
[Link](object : PhoneStateListener() {
override fun onCallStateChanged(state: Int, phoneNumber: String?) {
when (state) {
TelephonyManager.CALL_STATE_RINGING -> { }
TelephonyManager.CALL_STATE_OFFHOOK -> { }
TelephonyManager.CALL_STATE_IDLE -> { }
}
}
}, PhoneStateListener.LISTEN_CALL_STATE)
Page 20 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
3. SmsManager
Definition:
SmsManager allows applications to send SMS messages.
Example:
val smsManager = [Link]()
[Link](
"9876543210",
null,
"Hello from Android",
null,
null
)
Permissions Required
Telephony APIs require runtime permissions.
<uses-permission android:name="[Link].READ_PHONE_STATE"/>
<uses-permission android:name="[Link].SEND_SMS"/>
<uses-permission android:name="[Link].RECEIVE_SMS"/>
SIM Card Information
Using TelephonyManager:
• SIM operator
• SIM country
• SIM state
val simOperator = [Link]
Network Information
Telephony API provides:
• Network type (LTE, NR, HSPA)
• Roaming status
• Signal strength
SMS Receiving using Broadcast Receiver
To receive SMS, a BroadcastReceiver is used.
class SmsReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
// Handle incoming SMS
}
}
Telephony API Use Cases
• Caller ID apps
• SMS-based services
• Network signal monitor apps
• Telecom service apps
• Emergency alert systems
Security & Privacy Considerations
• Telephony data is sensitive
• Android restricts access in newer versions
Page 21 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
• Permissions must be justified
• Many APIs are limited to system apps
Limitations of Telephony API
• Restricted in newer Android versions
• Requires user permission
• Not supported on non-SIM devices
• SMS limitations apply
Exam-Important Points
• TelephonyManager is core class
• Runtime permission is mandatory
• Used for calls, SMS, network info
• BroadcastReceiver used for SMS receive
• Sensitive APIs have restrictions
Advantages
• Direct access to telecom services
• Useful for communication apps
• Provides real-time network info
❖ Notifying the User in Android
Introduction
In Android, notification mechanisms are used to inform the user about important events
such as new messages, updates, downloads, or background task completion. Notifications
help applications communicate with users without interrupting their current activity.
Android provides multiple ways to notify users:
• Toast Messages
• Snackbars
• Dialogs
• Status Bar Notifications (Most Important)
Purpose of User Notifications
User notifications are used to:
• Display important information
• Inform about background tasks
• Alert the user about system or app events
• Improve user interaction and experience
Types of User Notifications
1. Toast Notification
Definition:
A Toast is a small popup message that appears for a short duration and disappears
automatically.
Characteristics:
• Non-interactive
• Temporary
• Does not block user interaction
Page 22 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
Example (Kotlin):
[Link](
this,
"Data Saved Successfully",
Toast.LENGTH_SHORT
).show()
2. Snackbar Notification
Definition:
A Snackbar is similar to Toast but provides optional user action.
Characteristics:
• Appears at bottom of screen
• Can include an action button
• Used in modern apps
Example:
[Link](
findViewById([Link]),
"No Internet Connection",
Snackbar.LENGTH_LONG
).setAction("Retry") {
// Retry action
}.show()
3. Dialog Notification
Dialogs are used when user interaction is required.
Example:
[Link](this)
.setTitle("Warning")
.setMessage("Are you sure?")
.setPositiveButton("Yes", null)
.setNegativeButton("No", null)
.show()
Notifying with the Status Bar
Introduction
Status Bar Notifications are the most powerful and commonly used notification mechanism
in Android. These notifications appear in the status bar and can be expanded from the
notification drawer.
They allow apps to notify users even when the app is running in the background.
Features of Status Bar Notifications
• Appear at top of screen
• Support icons, text, and actions
• Can open activities when tapped
• Support priority levels
• Can be persistent or dismissible
Page 23 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
Notification Components
A status bar notification includes:
• Small icon
• Title
• Content text
• Timestamp
• Action buttons (optional)
Notification Channels (Android 8.0+)
Definition:
A Notification Channel is required for posting notifications on Android 8.0 (API 26) and
above.
Purpose:
• Allows users to control notification behavior
• Enables sound, vibration, and priority settings
Steps to Create Status Bar Notification
Step 1: Create Notification Channel
val channelId = "my_channel"
val channel = NotificationChannel(
channelId,
"General Notifications",
NotificationManager.IMPORTANCE_DEFAULT
)
val manager = getSystemService(NotificationManager::[Link])
[Link](channel)
Step 2: Build Notification
val notification = [Link](this, channelId)
.setSmallIcon([Link].ic_notification)
.setContentTitle("Download Complete")
.setContentText("Your file has been downloaded")
.setAutoCancel(true)
.build()
Step 3: Display Notification
[Link](1, notification)
PendingIntent in Notifications
Definition:
PendingIntent defines the action to perform when the user taps the notification.
val intent = Intent(this, MainActivity::[Link])
val pendingIntent = [Link](
this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT
)
Page 24 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
Notification Priority Levels
Level Description
IMPORTANCE_HIGH Urgent notifications
IMPORTANCE_DEFAULT Normal alerts
IMPORTANCE_LOW Background info
IMPORTANCE_MIN Silent notifications
Use Cases of Status Bar Notifications
• Messaging apps
• Email alerts
• Download progress
• Location tracking
• Music playback
Advantages
• Non-intrusive
• Works in background
• Highly customizable
• User-controlled settings
Limitations
• Overuse can annoy users
• Requires channel setup
• UI restrictions apply
Exam-Important Points
• Toast is temporary and non-interactive
• Snackbar supports action
• Status bar notification is most powerful
• NotificationChannel is mandatory (API 26+)
• PendingIntent handles notification clicks
❖ Vibrating the Phone in Android
Introduction
In Android, vibration is a form of haptic feedback used to notify or alert the user through
physical sensations. Vibrations are commonly used for incoming calls, messages,
notifications, alarms, and user interactions such as button presses.
Android provides vibration functionality through the Vibrator API.
Purpose of Vibration in Android Applications
Vibration is used to:
• Alert users silently
• Enhance user experience
• Provide feedback for actions
• Support accessibility features
Page 25 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
Vibrator API
Vibrator Class
Definition:
The Vibrator class is used to control the device vibration hardware.
Accessing Vibrator Service:
val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
Permission Required
Add the following permission in [Link]:
<uses-permission android:name="[Link]"/>
Simple Vibration Example
[Link](500)
(Vibrates the phone for 500 milliseconds)
Vibration with Pattern
Definition:
A vibration pattern defines on and off intervals.
val pattern = longArrayOf(0, 300, 200, 300)
[Link](pattern, -1)
Explanation:
• 0 → start immediately
• 300 → vibrate for 300 ms
• 200 → pause for 200 ms
• 300 → vibrate again
• -1 → no repeat
Vibration Using VibrationEffect (Android 8.0+)
For newer Android versions, VibrationEffect is recommended.
One-shot vibration
val effect = [Link](
500,
VibrationEffect.DEFAULT_AMPLITUDE
)
[Link](effect)
Waveform vibration
val effect = [Link](
longArrayOf(0, 200, 100, 300),
-1
)
[Link](effect)
Checking if Device Supports Vibration
if ([Link]()) {
[Link](300)
}
Stopping Vibration
[Link]()
Page 26 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
Use Cases of Phone Vibration
• Incoming call alerts
• Message notifications
• Alarm alerts
• Button click feedback
• Game interactions
Best Practices
• Use vibration sparingly
• Respect user notification settings
• Combine vibration with sound or visuals
• Avoid long or frequent vibrations
Limitations
• Some devices may not support vibration
• User may disable vibration
• Battery consumption
Exam-Important Points
• Vibrator class is used for vibration
• VIBRATE permission is mandatory
• VibrationEffect is recommended for Android 8+
• Pattern vibration allows multiple pulses
• Used for haptic feedback
❖ Blinking the Lights in Android
Introduction
Blinking the lights in Android refers to using the device’s notification LED to visually alert
the user about events such as new messages, missed calls, or app notifications. This feature
is part of the notification system and works mainly through status bar notifications.
Notification LED blinking is useful when:
• The phone is in silent mode
• The screen is off
• The user needs a visual alert without sound or vibration
What is Notification LED?
The Notification LED is a small light (usually near the front camera or speaker) that:
• Blinks in different colors
• Indicates pending notifications
• Works when the device screen is off
Note:
Many modern smartphones do not have a physical notification LED. In such devices, this
feature may not work.
Purpose of Blinking Lights
Blinking lights are used to:
• Notify users silently
• Indicate unread notifications
Page 27 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
• Improve accessibility
• Save battery compared to screen wake-up
Blinking Lights Using Notifications
Android controls LED blinking only through notifications, not directly.
Key Notification LED Properties
• setLights(color, onMs, offMs)
• LED color
• On duration
• Off duration
Creating LED Blinking Notification
Step 1: Create Notification Channel (Android 8.0+)
val channelId = "led_channel"
val channel = NotificationChannel(
channelId,
"LED Notifications",
NotificationManager.IMPORTANCE_DEFAULT
).apply {
enableLights(true)
lightColor = [Link]
}
Step 2: Register Channel
val manager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
[Link](channel)
Step 3: Build Notification with LED
val notification = [Link](this, channelId)
.setSmallIcon([Link].ic_notification)
.setContentTitle("New Message")
.setContentText("You have a new notification")
.setLights([Link], 500, 500)
.build()
Step 4: Show Notification
[Link](101, notification)
Explanation of setLights()
setLights(color, onMs, offMs)
Parameter Description
color LED color (RED, GREEN, BLUE)
onMs Light ON duration (milliseconds)
offMs Light OFF duration (milliseconds)
Page 28 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
Permissions Required
No special permission is required, but the user must enable notifications for the app.
Limitations of Blinking Lights
• Not supported on all devices
• LED color control is device-dependent
• User may disable LED notifications
• Android versions may restrict behavior
Alternative for Devices Without LED
• Always-On Display (AOD)
• Screen wake notifications
• Vibration
• Sound alerts
Use Cases
• Messaging applications
• Email notifications
• Missed call alerts
• Reminder apps
Exam-Important Points
• LED blinking is controlled via notifications
• setLights() method is used
• NotificationChannel must enable lights
• Works only on devices with LED
• No direct hardware access allowed
Advantages
• Silent visual alert
• Low battery consumption
• Works when screen is off
❖ Customizing Notifications using Services in Android
Introduction
In Android, customizing notifications using Services allows an application to show,
update, and manage notifications while running in the background. Services are
commonly used when notifications must remain active even if the application UI is not
visible, such as music playback, downloads, location tracking, or foreground tasks.
What is a Service in Android?
A Service is an Android component that:
• Runs in the background
• Has no user interface
• Performs long-running operations
• Can display notifications
Page 29 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
Why Use Services for Notifications?
Services are used with notifications to:
• Run tasks continuously
• Show persistent notifications
• Update notification content dynamically
• Prevent the system from stopping the app
Foreground Service and Notifications
Foreground Service
A Foreground Service is a service that:
• Runs with high priority
• Must display a notification
• Is less likely to be killed by the system
Example Use Cases:
• Music player
• Navigation apps
• Fitness tracking
• File download services
Creating a Notification for a Service
Step 1: Create Notification Channel
val channelId = "service_channel"
val channel = NotificationChannel(
channelId,
"Service Notifications",
NotificationManager.IMPORTANCE_LOW
)
val manager = getSystemService(NotificationManager::[Link])
[Link](channel)
Step 2: Build Custom Notification
val notification = [Link](this, channelId)
.setContentTitle("Service Running")
.setContentText("Music is playing")
.setSmallIcon([Link].ic_service)
.setOngoing(true)
.build()
Step 3: Start Foreground Service
startForeground(1, notification)
Customizing Notification Content
Notifications can be customized using:
• Title
• Text
• Icons
• Actions
• Progress bar
Page 30 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
Adding Action Buttons
val stopIntent = Intent(this, MyService::[Link])
val stopPendingIntent = [Link](
this, 0, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT
)
val notification = [Link](this, channelId)
.addAction([Link].ic_stop, "Stop", stopPendingIntent)
.build()
Updating Notifications from Service
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as
NotificationManager
[Link](1, updatedNotification)
Custom Notification Layout
Android allows custom notification layouts using RemoteViews.
val remoteViews = RemoteViews(packageName, [Link].custom_notification)
[Link](remoteViews)
Stopping Service and Notification
stopForeground(true)
stopSelf()
Permissions Required
<uses-permission android:name="[Link].FOREGROUND_SERVICE"/>
Advantages of Using Services with Notifications
• Continuous background operation
• Real-time notification updates
• Better user awareness
• System-friendly execution
Limitations
• Must show notification for foreground service
• Higher battery usage
• Android version restrictions
Exam-Important Points
• Services run in background
• Foreground services require notification
• Notifications can be updated dynamically
• Action buttons improve interactivity
• NotificationChannel is mandatory (API 26+)
Use Cases
• Music streaming apps
• Download manager
• Location tracking apps
• Fitness apps
Page 31 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
❖ Application Development using JSON in MySQL
Introduction
In modern application development, JSON (JavaScript Object Notation) is widely used for
data exchange between applications and databases. MySQL supports JSON data types,
allowing applications (such as Android apps) to store, retrieve, and process JSON data
efficiently.
Using JSON in MySQL helps developers build dynamic, scalable, and API-based
applications.
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data format used to store and
transmit structured data.
Example JSON Object
{
"id": 101,
"name": "Android",
"version": "14"
}
What is MySQL JSON Support?
MySQL provides a native JSON data type, which allows:
• Storing JSON documents
• Validating JSON automatically
• Querying JSON values
• Updating parts of JSON data
Introduced in MySQL 5.7 and above.
Why Use JSON in MySQL?
Using JSON in MySQL is useful because:
• It stores complex structured data
• Reduces table joins
• Supports API-based applications
• Works efficiently with Android and Web APIs
Architecture of Application using JSON and MySQL
Android Application
↓
Web API (PHP / Node / Java)
↓
JSON Data
↓
MySQL Database (JSON Column)
Creating JSON Column in MySQL
Table Creation Example
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
user_data JSON
);
Page 32 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
Inserting JSON Data into MySQL
INSERT INTO users (user_data)
VALUES ('{
"name": "Bhavesh",
"course": "BCA",
"mobile": "9876543210"
}');
Retrieving JSON Data
SELECT user_data FROM users;
Accessing JSON Values
SELECT user_data->'$.name' AS name
FROM users;
Updating JSON Data
UPDATE users
SET user_data = JSON_SET(user_data, '$.mobile', '9999999999')
WHERE id = 1;
JSON Functions in MySQL
Function Purpose
JSON_EXTRACT() Retrieve value
JSON_SET() Update value
JSON_REMOVE() Delete key
JSON_ARRAY() Create array
JSON_OBJECT() Create object
Using JSON with Web API
Web APIs commonly send and receive data in JSON format.
Sample API JSON Response
{
"status": "success",
"data": {
"id": 1,
"name": "Android"
}
}
This JSON is:
• Sent from MySQL
• Processed by backend
• Consumed by Android app
Android Application Use Case
In Android:
• JSON data is fetched via Web API
• Parsed using libraries like Gson
• Displayed in UI
Page 33 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
Example (Kotlin JSON Parsing)
val jsonObject = JSONObject(response)
val name = [Link]("name")
Advantages of Using JSON in MySQL
• Flexible schema
• Easy API integration
• Faster development
• Supports modern applications
Limitations
• Complex queries may be slower
• Not suitable for heavy relational data
• Requires MySQL 5.7+
Security Considerations
• Validate JSON input
• Prevent SQL injection
• Use prepared statements
• Secure API endpoints
Exam-Important Points
• JSON is a lightweight data format
• MySQL supports native JSON datatype
• Used in Android and Web APIs
• JSON functions allow querying and updating
• Ideal for API-based applications
Real-World Applications
• Android apps with REST APIs
• E-commerce platforms
• Student management systems
• Cloud-based applications
❖ Publishing an Android Application
Introduction
Publishing an Android application is the process of making an app available to users
through an app distribution platform, most commonly the Google Play Store. Before
publishing, the application must be tested, signed, packaged, and reviewed according to
Google’s policies.
Publishing allows developers to:
• Share applications with users worldwide
• Distribute updates
• Monetize applications
• Gain user feedback
Page 34 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
Ways to Publish Android Applications
Android applications can be published using:
1. Google Play Store (Official method)
2. Third-party app stores
3. Direct APK distribution (manual install)
(For academic and professional use, Google Play Store is recommended.)
Prerequisites for Publishing
Before publishing an Android app:
• A Google Developer Account
• A tested Android application
• A signed APK or AAB (Android App Bundle)
• App details such as name, description, and icon
Google Developer Account
To publish apps on Google Play Store:
• Create a Google Developer account
• One-time registration fee is required
• Account is linked to a Google email
Preparing the Android Application
1. App Versioning
Each app release must have:
• versionCode – internal version number
• versionName – user-visible version
versionCode 1
versionName "1.0"
2. App Icon and App Name
• App icon must follow Play Store guidelines
• App name should be unique and meaningful
3. Remove Debug Code
Before publishing:
• Disable logs
• Remove test data
• Optimize performance
Signing the Android Application
Android apps must be digitally signed.
Why Signing is Required
• Ensures app authenticity
• Prevents tampering
• Required for updates
Generating Signed App Bundle (AAB)
Steps in Android Studio:
1. Open Build → Generate Signed Bundle / APK
2. Select Android App Bundle
3. Create or select Keystore
Page 35 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
4. Enter key details
5. Generate signed file
Android App Bundle (AAB)
Definition:
An Android App Bundle (AAB) is the recommended publishing format by Google.
Advantages
• Smaller app size
• Optimized delivery
• Better performance
Creating Store Listing
Store listing includes:
• App title
• Short description
• Full description
• App icon
• Screenshots
• Feature graphic
App Content and Policy Compliance
Google Play requires:
• Privacy policy (mandatory for many apps)
• Declaration of permissions
• Content rating questionnaire
• Compliance with Play Store policies
Uploading the App
Steps:
1. Login to Google Play Console
2. Create new app
3. Upload AAB file
4. Fill app details
5. Submit for review
App Review Process
• Google reviews the app
• Checks policy compliance
• Tests security and permissions
• Review may take few hours to days
App Release Types
1. Internal testing
2. Closed testing
3. Open testing
4. Production release
Page 36 of 37 Study notes by : BHAVESH CHAVDA
CS-35: Mobile Application Development in Android using Kotlin UNIT - 5
After Publishing
Once approved:
• App becomes visible on Play Store
• Users can download and install
• Developers can monitor installs, ratings, and reviews
Updating an Android Application
To update:
• Increase versionCode
• Upload new signed AAB
• Submit update for review
Advantages of Publishing on Play Store
• Global reach
• Automatic updates
• Secure distribution
• User trust
Limitations
• Policy restrictions
• Approval delays
• Developer account rules
• Revenue sharing
Exam-Important Points
• Google Play Store is official platform
• App must be signed before publishing
• AAB is recommended format
• Version code must increase for updates
• Policy compliance is mandatory
Page 37 of 37 Study notes by : BHAVESH CHAVDA