You are on page 1of 9

ANDROID NETWORK PROGRAMMING

Android lets your application connect to the internet or any other local network and allows you
to perform network operations.

A device can have various types of network connections. This chapter focuses on using either a
Wi-Fi or a mobile network connection.

Checking Network Connection


Before you perform any network operations, you must first check that are you connected
to that network or internet e.t.c. For this android provides ConnectivityManager class. You need
to instantiate an object of this class by calling getSystemService() method. Its syntax is given
below −

ConnectivityManager check = (ConnectivityManager)


this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
Once you instantiate the object of ConnectivityManager class, you can use
getAllNetworkInfo method to get the information of all the networks. This method returns an
array of NetworkInfo. So you have to receive it like this.

NetworkInfo[] info = check.getAllNetworkInfo();


The last thing you need to do is to check Connected State of the network. Its syntax is
given below −

for (int i = 0; i<info.length; i++){


if (info[i].getState() == NetworkInfo.State.CONNECTED){
Toast.makeText(context, "Internet is connected
Toast.LENGTH_SHORT).show();
}
}
Apart from this connected states, there are other states a network can achieve. They are listed
below −

Sr.No State
1 Connecting
2 Disconnected
3 Disconnecting
4 Suspended
5 Unknown

Performing Network Operations


After checking that you are connected to the internet, you can perform any network
operation. Here we are fetching the html of a website from a url.
HttpURLConnection
Android provides HttpURLConnection and URL class to handle these operations. You
need to instantiate an object of URL class by providing the link of website. Its syntax is as
follows −

String link = "http://www.google.com";


URL url = new URL(link);
After that you need to call openConnection method of url class and receive it in a
HttpURLConnection object. After that you need to call the connect method of
HttpURLConnection class.

HttpURLConnection conn = (HttpURLConnection) url.openConnection();


conn.connect();
And the last thing you need to do is to fetch the HTML from the website. For this you
will use InputStream and BufferedReader class. Its syntax is given below −

InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String webPage = "",data="";

while ((data = reader.readLine()) != null){


webPage += data + "\n";
}
there are other methods available in HttpURLConnection class. They are listed below −

Sr.No Method & description

1
disconnect()
This method releases this connection so that its resources may be either reused
or closed

2
getRequestMethod()
This method returns the request method which will be used to make the request
to the remote HTTP server

3
getResponseCode()
This method returns response code returned by the remote HTTP server

4
setRequestMethod(String method)
This method Sets the request command which will be sent to the remote HTTP
server

5
usingProxy()
This method returns whether this connection uses a proxy server or not

CONNECTING TO REST

REST stands for REpresentational State Transfer. Restful Web Service, expose
API from your application in a secure, uniform, stateless manner to the calling
client.
REST architecture will be useful to build client/server network applications. REST
represents Representational State Transfer. Implementing REST is very simple compared to
other methods like SOAP, CORBA, WSDL etc., It basically works on HTTP protocol.
Following are the list of things should be considered while building a REST api.

» HTTP Methods
A well-designed RESTful API should support most commonly used HTTP methods (GET,
POST, PUT and DELETE). There are other HTTP methods like OPTIONS, HEAD but these are
used most often. Each method should be used depending on the type of operation you are
performing.

GET

To fetch a resource

POST

To create a new resource

PUT

To update existing resource


DELETE

To delete a resource

SOAP BASED WEB SERVICES

SOAP refers to the Simple Object Access Protocol and is an XML-based web service
protocol for exchanging data or documents over HTTP (Hypertext transfer protocol) or SMTP
(Simple Message Transfer Protocol). It allows separate processes on different platforms to
communicate with one another.

Advantages of SOAP
SOAP is the protocol used for data interchange between applications. Below are some of
the reasons as to why SOAP is used.
 When developing SOAP based Web services, you need to have some of language which
can be used for web services to talk with client applications.
 SOAP is a light-weight protocol that is used for data interchange between applications.
Note the keyword ‘light.’
 SOAP is designed to be platform independent and is also designed to be operating system
independent. So the SOAP protocol can work any programming language based
applications on both Windows and Linux platform.
 It works on the HTTP protocol –SOAP works on the HTTP protocol, which is the default
protocol used by all web applications. SOAP Building Blocks

The SOAP specification defines something known as a “SOAP message” which is what is sent
to the web service and the client application.

SOAP architecture
SOAP Message Building Blocks

The SOAP message is nothing but a mere XML document which has the below components.
 An Envelope element that identifies the XML document as a SOAP message – This is the
containing part of the SOAP message and is used to encapsulate all the details in the
SOAP message. This is the root element in the SOAP message.
 A Header element that contains header information – The header element can contain
information such as authentication credentials which can be used by the calling
application.
 It can also contain the definition of complex types which could be used in the SOAP
message. By default, the SOAP message can contain parameters which could be of
simple types such as strings and numbers, but can also be a complex object type.
BROADCAST RECEIVER
Broadcast in android is the system-wide events that can occur when the device starts,
when a message is received on the device or when incoming calls are received, or when a
device goes to airplane mode, etc.
Broadcast Receivers are used to respond to these system-wide events.
Broadcast Receivers allow us to register for the system and application events, and
when that event happens, then the register receivers get notified. There are mainly two types of
Broadcast Receivers:
 Static Broadcast Receivers: These types of Receivers are declared in the manifest file and
works even if the app is closed.
 Dynamic Broadcast Receivers: These types of receivers work only if the app is active or
minimized.

LOCAL BROADCAST MANAGER

Local Broadcast Manager is used to register and send a broadcast of intents to local
objects in your process. It has lots of advantages:
1. You broadcasting data will not leave your app. So, if there is some leakage in your app
then you need not worry about that.
2. Another thing that can be noted here is that other applications can’t send any kind of
broadcasts to your app. So, you need not worry about security holes.
To use LocalBroadcastReceiver, all you need to do is create an instance of
LocalBroadcastManager, then send the broadcast and finally receive the broadcast. So, firstly,
create an instance of the LocalBroadcastManager:
var localBroadcastManager = LocalBroadcastManager.getInstance(context)

Now, by using the sendBroadcast() method, you can send the broadcast as below:
val localIntent = Intent("YOUR_ACTION")
.putExtra("DATA", "MindOrks")
localBroadcastManager.sendBroadcast(localIntent)

Our final task is to receive the broadcast using the onReceive() method on
MyBroadCastReceiver. You can perform the desired action after receiving the broadcast in
the onReceive() method as below:
private val listener = MyBroadcastReceiver()

inner class MyBroadcastReceiver : BroadcastReceiver() {


override fun onReceive(context: Context, intent: Intent){
when (intent.action) {
"YOUR_ACTION" -> {
val data = intent.getStringExtra("DATA")
Log.d("Your Received data : ", data)
}
else -> Toast.makeText(context, "Action Not Found", Toast.LENGTH_LONG).show()
}

}
}
DYNAMIC BROADCAST RECEIVER IN ANDROID

A broadcast receiver (receiver) is an Android component which allows you to register


for system or application events. All registered receivers for an event are notified by the Android
runtime once this event happens.
There are two different methods to register a broadcast receiver. Statically (manifest-
declared) - This receiver can be registered via the AndroidManifest. xml file. Dynamically
(context-registered) - This registers a receiver dynamically via the Context.
To declare a broadcast receiver in the manifest, perform the following steps:
 Specify the <receiver> element in your app's manifest. <!--
 Subclass BroadcastReceiver and implement onReceive(Context, Intent) . The broadcast
receiver in the following example logs and displays the contents of the broadcast.
ANDROID TELEPHONY MANAGER
The android.telephony.TelephonyManager class provides information about the
telephony services such as subscriber id, sim serial number, phone network type etc. Moreover,
you can determine the phone state etc.
Architecture of Android Telephony

Report this ad

Android Telephony architecture works in 4 layers that are :

1. Communication Processor
2. Radio Interface Layer (RIL)
3. Framework Services
4. Applications
Let us try to understand them briefly one by one :
1. Communication Processor
It is an input/output processor to distribute and collect data from a number of remote terminals. It
is a specialized processor designed to communicate with the data communication network.

2. Radio Interface Layer


It is a bridge between the hardware and Android phone framework services. Rather we say, it is a
protocol stack for Telephone. It has two main components that are:

 RIL Daemon– It starts when the android system starts. It reads the system properties to find
a library that is to be used for Vendor RIL.
 Vendor RIL– It is also known as RIL Driver. It can be understood as a library that is
specific to each modem.
3. Framework Services
The telephony Framework starts and initializes along with the system. All the queries by
Application API are directed to RIL using these services.

4. Application
These are the Application UI related to telephony such as Dialer, SMS, MMS, Call tracker, etc.
These applications start with the android system boot up. These are tied with framework services
of telephony.

You might also like