0% found this document useful (0 votes)
13 views10 pages

Unit4 - Network API

The document provides an overview of Network APIs in Android, detailing key concepts such as HTTP/HTTPS networking, connectivity management, and Wi-Fi management. It also covers working with RESTful APIs and JSON, highlighting the use of Retrofit for efficient API communication, and includes examples of Android notifications and device functionalities like vibration and flashlight control. Additionally, it discusses the basics of testing in Android, including unit tests, instrumented tests, and performance tests.

Uploaded by

solankiparth9825
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)
13 views10 pages

Unit4 - Network API

The document provides an overview of Network APIs in Android, detailing key concepts such as HTTP/HTTPS networking, connectivity management, and Wi-Fi management. It also covers working with RESTful APIs and JSON, highlighting the use of Retrofit for efficient API communication, and includes examples of Android notifications and device functionalities like vibration and flashlight control. Additionally, it discusses the basics of testing in Android, including unit tests, instrumented tests, and performance tests.

Uploaded by

solankiparth9825
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

UNIT 4: Network API

Explain Network API in Android:


Android offers various network APIs to enable applications to interact with
the internet and other devices.
Key Network APIs and Concepts in Android:
HTTP/HTTPS Networking:
✓ Android applications commonly use HTTP/HTTPS for client-server
communication.
✓ While Android provides basic HttpURLConnection, popular third-
party libraries like OkHttp and Retrofit are widely used for more
robust and convenient network requests, handling aspects like
caching, error handling, and asynchronous operations.
Connectivity Management:
The ConnectivityManager API allows applications to monitor network
connectivity status, determine network type (Wi-Fi, mobile data), and
request specific network capabilities.

Wi-Fi Management:
✓ Wi-Fi Suggestion API: Allows apps to suggest Wi-Fi networks for the
device to connect to, providing credentials and network details.
✓ Wi-Fi Network Request API: Enables apps to request connection to
specific Wi-Fi networks for peer-to-peer scenarios, like
bootstrapping secondary
devices.

Example Network API:


Permission:
<uses-permission
android:name="[Link].ACCESS_WIFI_STATE" />
<uses-permission
android:name="[Link].CHANGE_WIFI_STATE" />
Example:
private lateinit var wifiManager: WifiManager
private lateinit var wifiStatusTextView: TextView
private lateinit var toggleWifiButton: Button
override fun onCreate(savedInstanceState: Bundle?) {
[Link](savedInstanceState)
setContentView([Link].activity_main)

wifiManager =
[Link](Context.WIFI_SERVICE) as
WifiManager
wifiStatusTextView = findViewById([Link])
toggleWifiButton = findViewById([Link])

updateWifiStatus()

[Link] {
if ([Link]) {
[Link] = false // Disable Wi-Fi
} else {
[Link] = true // Enable Wi-Fi
}
updateWifiStatus()
}
}

private fun updateWifiStatus() {


if ([Link]) {
[Link] = "Wi-Fi Status: ON"
[Link] = "Turn Wi-Fi OFF"
} else {
[Link] = "Wi-Fi Status: OFF"
[Link] = "Turn Wi-Fi ON"
}
}

WORKING WITH RESTFUL APIS AND JSON


Working with RESTful APIs and JSON involves understanding how to send
requests to and receive responses from web services using the HTTP
protocol, with data typically formatted as JSON.
Understanding RESTful APIs:
• Resources:
REST APIs are built around resources, which are essentially named entities
(e.g., users, products, orders).
• HTTP Methods:
Standard HTTP methods are used to interact with these resources:
• GET: Retrieve data from a resource.
• POST: Create a new resource.
• PUT: Update an existing resource (replace the entire resource).
• PATCH: Update part of an existing resource.
• DELETE: Remove a resource.
• Statelessness:
Each request from a client to a server must contain all the information
needed to understand the request; the server should not store any client
context between requests.

Understanding JSON (JavaScript Object Notation):


• Data Format:
JSON is a lightweight, human-readable data interchange format,
widely used in web development for sending and receiving data.
• Structure:
JSON data is represented as key-value pairs, similar to JavaScript
objects, and supports various data types (strings, numbers, booleans,
arrays, objects).

Interacting with RESTful APIs using JSON:


• Sending Requests:
• HTTP Client: Use an HTTP client library or built-in functions in your
programming language (e.g., fetch in JavaScript, requests in Python)
to send HTTP requests.
• Headers: Include appropriate headers, especially Content-Type:
application/json when sending JSON data in the request body,
and Accept: application/json to indicate you prefer JSON responses.
• Request Body: For POST, PUT, and PATCH requests, the data you're
sending is typically formatted as a JSON string and included in the
request body.
Example (JavaScript fetch for a POST request):

fetch('[Link] {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: [Link]({ name: 'John Doe', email: 'john@[Link]'
}),
})
.then(response => [Link]())
.then(data => [Link](data))
.catch(error => [Link]('Error:', error));

Retrofit Library for Efficient API Communication


Retrofit is a type-safe HTTP client library for Android and Java, developed
by Square, that simplifies the process of consuming RESTful web services.

Features and Benefits:


Declarative API Definition:
Retrofit allows defining API endpoints as simple interfaces using
annotations (e.g., @GET, @POST, @Path, @Query).
Type-Safe Requests and Responses:
It supports defining data models for requests and responses, automatically
handling serialization and deserialization (e.g., JSON to Kotlin/Java objects
using converters like Gson).

Integration with OkHttp:


Retrofit is built on top of OkHttp, inheriting its benefits like connection
pooling, request/response caching, and efficient network communication.

Interceptor Support:
Interceptors can be used to modify requests and responses, enabling
functionalities like logging, adding authentication headers, or caching.
Reduced Boilerplate:
By abstracting away the complexities of network communication,
serialization, and threading, Retrofit minimizes the amount of code
developers need to write for API interactions.

Android Web View or Web API:


Android WebView API in Kotlin allows the embedding and display of web
content directly within an Android application. This functionality enables
developers to integrate web pages, interactive content, and even entire web
applications into their native Android experience.

Permission:
<uses-permission android:name="[Link]"/>

Example:
Activity_main.xml
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
[Link]
val myWebView: WebView = findViewById([Link])
[Link]("[Link]

Android Telephony API:


android Telephony API provides access to the underlying telephone
hardware functionalities, enabling applications to interact with phone
features like calls, SMS, MMS, network information, and device details.

TelephonyManager: such as IMEI number, subscriber ID, SIM serial


number, network country, roaming status, and network type

PhoneStateListener: phone's state, such as call state (idle, ringing, off-


hook), service state (in service, out of service), and data connection state.

Intents for Call Handling:


Applications can initiate phone calls using Intent objects with actions
like ACTION_CALL or ACTION_DIAL.
Example:
<uses-permission
android:name="[Link].READ_PHONE_STATE"/>

val telephonyManager =
[Link](Context.TELEPHONY_SERVICE) as
TelephonyManager

return if ([Link].SDK_INT >= Build.VERSION_CODES.O) {


// For Android Oreo (API 26) and above, use getImei()
[Link]
} else {
// For older versions, use getDeviceId()
@Suppress("DEPRECATION")
[Link]
}

Creating and Customizing Android Notifications


What is Notification in android:
Android development with Kotlin, a notification is a message or alert that
appears outside of an application's normal user interface. Notifications
serve to provide timely, relevant updates or information to the user, even
when the app is not actively in the foreground.

Types of Notification in Android:


Basic Notifications:
These are the most common type, displaying an icon, title, and a small
amount of text content. They can be configured to launch an activity when
tapped.

Notifications with Actions:


Notifications can include interactive buttons (actions) that allow users to
perform specific tasks directly from the notification shade, such as "Reply,"
"Archive," or "Mark as Read.

Notifications with Direct Reply:


This type, often used in messaging apps, allows users to directly type and
send a reply within the notification itself, without opening the full
application.

Big Content Notifications:


These notifications provide expanded views to display more information,
such as:
Big Text Style: Displays a longer block of text.
Big Picture Style: Includes a large image.
Inbox Style: Presents multiple lines of text, often for a list of new
messages.
Grouped Notifications:
Multiple notifications from the same app can be grouped together into a
single summary notification, which can then be expanded to reveal
individual notifications.

Heads-up Notifications:
These are high-priority notifications that appear as a small floating window
at the top of the screen, momentarily interrupting the user's current
activity, often for urgent or time-sensitive information.

Example:
val pendingIntent: PendingIntent = [Link](context, 0,
intent, PendingIntent.FLAG_IMMUTABLE)

val builder = [Link](context, channelId)


.setSmallIcon([Link].ic_dialog_info) // Replace with your
own small icon
.setContentTitle("My Simple Notification")
.setContentText("This is a basic notification example.")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent) // Set the intent that will fire when
the user taps the notification
.setAutoCancel(true) // Automatically removes the notification when the
user taps it

with([Link](context)) {
// notificationId is a unique int for each notification that you must define
notify(1, [Link]())
}

Vibrate Application Program in Android Kotlin:


Permission:
<uses-permission android:name="[Link]" />

[Link]
val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator

// Check if the device has a vibrator


if ([Link]()) {
// Vibrate for a duration (e.g., 500 milliseconds)
if ([Link].SDK_INT >= Build.VERSION_CODES.O) {
[Link]([Link](500,
VibrationEffect.DEFAULT_AMPLITUDE))
} else {
// Deprecated in API 26, but still works for older versions
@Suppress("DEPRECATION")
[Link](500)
}

Flash Light ON OFF Example in android kotlin:


Permission:
<uses-permission android:name="[Link]" />
<uses-feature android:name="[Link]" />
<uses-feature android:name="[Link]" />

[Link]
cameraManager = getSystemService(Context.CAMERA_SERVICE) as
CameraManager

try {
// Find the camera with a flash unit
for (id in [Link]) {
val characteristics = [Link](id)
val flashAvailable =
[Link](CameraCharacteristics.FLASH_INFO_AVAILABLE)
if (flashAvailable == true) {
cameraId = id
break
}
}
} catch (e: CameraAccessException) {
[Link]()
}

val toggleButton = findViewById<ToggleButton>([Link].toggle_flashlight)


[Link] { _, isChecked ->
if (cameraId != null) {
try {
[Link](cameraId!!, isChecked)
} catch (e: CameraAccessException) {
[Link]()
}
}
}
}

override fun onStop() {


[Link]()
// Turn off flashlight when the activity is stopped
if (cameraId != null) {
try {
[Link](cameraId!!, false)
} catch (e: CameraAccessException) {
[Link]()
}
}

Basics of Testing in Android :


Android testing involve evaluating an app's quality and functionality
through various methods like unit tests (verifying individual code
components), instrumented tests (running on a device to check integration
and UI), and functional/performance testing (ensuring the app meets
requirements and runs efficiently).
Types of tests
• Unit Tests: These test the smallest parts of your code in isolation, like a
single method or function. They are fast and run on a JVM (Java Virtual
Machine) without needing an actual device or emulator.

• Instrumented Tests: These run on an Android device or emulator,


allowing you to test UI interactions and how different parts of the app work
together. Frameworks like Espresso are used for UI testing.

• Integration Tests: These focus on verifying that different components of


your app work correctly when combined.

• Functional Tests: These ensure the app's features work as expected and
meet the initial requirements.

• Performance Tests: These measure how well the app performs, such as its
speed and memory usage.

You might also like