CH 5
CH 5
Chapter Five
Communications Via Network
and the Web
1
Chapter Objectives
At the end the chapter students should able to know:
2
Networking in Android
Android provides robust networking capabilities that
allow developers to communicate with remote servers
using various protocols like HTTP, HTTPS, and
WebSocket.
Networking operations are typically performed
asynchronously to avoid blocking the main UI thread and
ensure a responsive user interface.
This blog post will focus on some of them, which are
widely used for data exchange in Android apps.
3
Require permission
In order to perform network operations in your
application, your manifest must include the following
permissions
4
1. HTTP
First your application needs the INTERNET permission;
we first add the permission in the AndroidManifest.xml
file.
5
1. HTTP
6
1. HTTP
After trying to establish a connection with the server, the
HTTP response code is returned.
If the connection is established (via the response code
HTTP_OK), then you proceed to get an InputStream
object from the connection:
7
Problem
Android doesn’t allow you to make call networks on UI
thread.
To be specific, if you set the android:minSdkVersion
attribute in your AndroidManifest.xml file to a value of 9
or less; your synchronous code will still work in a UI thread
(though not recommended) an Android 3.0 or later
device,.
8
Android AsyncTask
AsyncTask is an abstract class in Android that offers us the freedom to
execute demanding tasks in the background while keeping the UI thread light
and the application responsive.
An asynchronous task is defined by 3 generic types:
1. Params, the type of the parameters sent to the task upon execution.
Note: all types are always used by an asynchronous task. To mark a type as
unused, simply use the type Void:
9
Android AsyncTask
10
Demo
11
3. consume JSON web services
JSON (JavaScript Object Notation) is a lightweight data-
interchange format that is easy for humans to read and
write.
12
Example
13
Demo
14
4. Using Socket Server
Sockets programming is a technique through which you
use to establish a connection between a client and a
server .
15
Demo
16
17