---
title: "Networking  in Android"  
description: "Hi everyone, here we will see how to implement Networking  in Android"  
author: "Manoj Pandey"  
published: 2015-02-20  
updated: 2019-09-07  
canonical: https://www.mindstick.com/articles/1595/networking-in-android  
category: "android"  
tags: ["android"]  
reading_time: 5 minutes  

---

# Networking  in Android

Previously, we learn about Action Bar with menu in Android. Now we see how to use Networking in Android.\

In Android networking, basic task involved in connecting to the network, monitoring the [network connection](https://answers.mindstick.com/qa/94984/how-do-you-change-the-network-connection-priority-in-windows-10) (including connection changes), and giving users control over an app's network usage. It also describes how to parse and consume [XML data](https://www.mindstick.com/forum/131/problem-in-showing-the-xml-data-in-well-formed).

In this article we learn basic settings of network

1. Connecting to the Network

This Concepts shows you how to implement a simple application that connects to the network. It explains some of the [best practices](https://www.mindstick.com/articles/337564/building-a-microservices-architecture-with-laravel-best-practices) you should follow in creating even the simplest network-connected app.

If you are perform any action in [your application](https://answers.mindstick.com/qa/95487/how-do-you-troubleshoot-when-your-application-link-is-not-responding) related to networking, before you must be allow permission from [AndroidManifest.xml](https://www.mindstick.com/interview/12768/what-is-the-androidmanifest-xml) as following code

```
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"   />
   <uses-permission android:name="android.permission.INTERNET"   />
   <uses-permission android:name="android.permission.WRITE_SETTINGS" />
```

2. Managing Network Usage

In this concepts describes how to write applications that have fine-grained control over their usage of network resources. [If your](https://yourviews.mindstick.com/view/83528/what-to-do-if-your-eye-glasses-don-t-fit) application performs a lot of network operations, you should provide user settings that allow users to [control your](https://yourviews.mindstick.com/story/4103/10-foods-that-can-control-your-blood-pressure) app’s data habits, such as how often [your app](https://answers.mindstick.com/qa/33368/how-will-you-design-a-listview-which-downloads-a-lot-of-images-and-displays-in-it-without-getting-your-app-hanged-whats-the-best-possible-way) syncs data, whether to perform uploads/downloads only when on Wi-Fi, whether to use data while roaming, and so on

\
As of Android 3.0 (Honeycomb) the system is configured to crash with a NetworkOnMainThreadException exception, if network is accessed in the [user interface](https://www.mindstick.com/blog/302016/what-is-user-interface-and-what-are-its-benefits) thread.Within an [Android application](https://www.mindstick.com/articles/1653/creating-libraries-for-android-applications) you should avoid performing long running operations on the user interface thread. This includes file and network.

\
For Good practice of access network under android and handle NetworkOnMainThreadExcetion use following code on beginning of your onCreate() method

```
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
```

Now I creating a sample for learn concepts of Networking

1. Create an Android project

2. Add permission in AndroidManifest.xml file

```
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"   />    <uses-permission android:name="android.permission.INTERNET"   /> 
```

3. My activity_main.xml

```
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/text"
          android:layout_width="wrap_content"
          android:textSize="22sp"
          android:layout_height="wrap_content"
          android:text="@string/hello_world"   />

</ScrollView>
```

4. Add following code in MainActivity.class

```
package com.example.androidnetworking;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import  android.net.ConnectivityManager;import android.net.NetworkInfo;import android.os.Bundle;import android.os.StrictMode;import android.app.Activity;import android.content.Context;import android.view.Menu;import android.view.View;import  android.view.View.OnClickListener;import android.widget.TextView;import android.widget.Toast;
public class MainActivity extends Activity {
 TextView textView; String data  = "";
 @Override protected void onCreate(Bundle  savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.activity_main);  textView = (TextView) findViewById(R.id.text);  textView.setOnClickListener(new OnClickListener() {
      @Override      public void onClick(View v) {       // TODO Auto-generated method stub
      }
   });
  StrictMode.ThreadPolicy policy = new  StrictMode.ThreadPolicy.Builder()  .permitAll().build();
  StrictMode.setThreadPolicy(policy);
  try {
   if (isNetworkAvailable()) {     URL url = new URL("http://www.mindstick.com.com");     // An URLConnection for HTTP used to send and receive     // data over the web    HttpURLConnection con = (HttpURLConnection)  url.openConnection();    // getInputStream() Response headers typically include metadata    // such as the response body's content type and length,  modified    // dates and session cookies.    readStream(con.getInputStream());
    } else
    Toast.makeText(getApplicationContext(),"Network is UnAvailable",      Toast.LENGTH_LONG).show();
   } catch (Exception ex) {
  }
 }
 @Override public boolean onCreateOptionsMenu(Menu menu)  {  // Inflate the menu; this adds items to the action bar if it  is pre  sent.  getMenuInflater().inflate(R.menu.main, menu);      return true;
 }
 public boolean isNetworkAvailable() {
 ConnectivityManager cm = (ConnectivityManager)  getSystemService(Context.CONNECTIVITY_SERVICE);
 NetworkInfo networkInfo = cm.getActiveNetworkInfo(); // if no network is available networkInfo will be null // otherwise check if we are connected if (networkInfo != null && networkInfo.isConnected()) {       return true;
  } else
      return false;
  }
 private void readStream(InputStream in) {
 // BufferedReader wraps an existing Reader and buffers the  input. BufferedReader  reader = null;
  try {
     reader = new BufferedReader(new InputStreamReader(in));
      String line = "";
     while ((line = reader.readLine()) != null) {
           data  += line;
     }
     textView.setText(data);
    } catch (IOException e) {
           } finally {
                if (reader != null) {
                     try {
                           reader.close();
                     } catch (IOException e) {
                      }}
                }
           }
     }
```

Now run your application

\
![Networking  in Android](https://www.mindstick.com/mindstickarticle/5bf5a2c1-2cf2-41aa-840f-43c62c291c57/images/424f1993-71d3-40ae-9086-43f22dda2ece.png)

\
***If Network is not available then***

\
![Networking  in Android](https://www.mindstick.com/mindstickarticle/5bf5a2c1-2cf2-41aa-840f-43c62c291c57/images/9ad06c3f-c30e-49d0-be9b-389fa724f9bd.png)

---

Original Source: https://www.mindstick.com/articles/1595/networking-in-android

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
