Home > DeveloperSection > Articles > Networking in Android

Networking in Android


Android Android 
Ratings:
0 Comment(s)
 1112  View(s)
Rate this:

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 (including connection changes), and giving users control over an app's network usage. It also describes how to parse and consume XML data.

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 you should follow in creating even the simplest network-connected app.

If you are perform any action in your application related to networking, before you must be allow permission from 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 application performs a lot of network operations, you should provide user settings that allow users to control your app’s data habits, such as how often your app 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 thread.

Within an Android application 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

 

 

If Network is not available then

 


Don't want to miss updates? Please click the below button!

Follow MindStick