How to check for Network Availability in android app

Checking for network availability in your android app can be a life saver for your app user. Imagine if your app needs to execute some functions that require internet and you did not check beforehand if there is an internet connection on the user device, your app will end up crashing on your users. This is one of the many reasons why some apps get negative reviews and comments in Google Play store.

For android app to execute any network operation there is need to check for availability of internet network. The android OS provides a system service that can be used to get an instance of the android connectivity manager. The android connectivity manager contains all the necessary information about a device network connection.

In this simple tutorial, we will demonstrate how to check internet connection then we will go ahead to develop a simple application that will use this method to check for internet connection from a remote website.

The first thing I will do is to list the environment and tools I will use in this tutorial but you are free to use whatever tools you are familiar with.

Windows XP

Eclipse (ADT)

Samsung Galaxy Fame Lite

Min SDK 8

Target SDK 19

There is no better time to start creating our application than now. To create a new android application project, following the steps as stipulated below.

How to create Android Application Project

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: NetworkAvailability

Package: com.tutorial.networkAvailability

Keep other default selections.

Continue to click on next button until Finish button is active

Then click on Finish Button

If you haven’t written any code in android before, you can check out one of posts that uses visual images to illustrate how to create a new android application project here.

Go ahead and open your MainActivity.java file. Delete all the codes in the file. Copy and paste this code. Please make sure the package name conforms to the package name of your project.

package com.tutorial.networkavailability;

import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

     @Override
     protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          if(isNetworkAvailable()){
               // do network operation here                   
           }else{
               Toast.makeText(this, "No Available Network. Please try again later", Toast.LENGTH_LONG).show();
               return;
           }
     } 
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
     }

     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
         // Handle action bar item clicks here. The action bar will
         // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
             return true;
        }
        return super.onOptionsItemSelected(item);
     }

     public boolean isNetworkAvailable() {
         ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
         NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
         return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}

There is nothing much happening in the code above. We have just created a method called isNetworkAvailable. Inside this method, we use the android System Service to get an instance of the ConnectivityManager. We used the getActiveNetworkInfo() of the ConnectivityManager class to get the current Network information. Finally, we check if it is not null and the state of the network with isConnected() method. If the conditions are true the method will return true else it will return false.

There is other network information state you can use. They include – (Connecting, Disconnected, Disconnecting, Suspended, Unknown)

Next, we will try and see how we can use android AsynTask class to do some network operation. We are going to create a java class called NetworkCalls.java. After you have done with creating the class, copy and paste the code below.

package com.tutorial.networkavailability;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.os.AsyncTask;

public class NetworkCalls extends AsyncTask<String, Void, String>{
  private String jsonResult;          

  @Override
  protected String doInBackground(String... params) {
      // TODO Auto-generated method stub
      System.out.println("The url parameter passed is " + params[0]);
      HttpParams httpParameters = new BasicHttpParams();
      // set the connection timeout and socket timeout parameters in (milliseconds)

      HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
      HttpConnectionParams.setSoTimeout(httpParameters, 5000);

      HttpClient httpClient = new DefaultHttpClient(httpParameters);
      HttpPost httpPost = new HttpPost(params[0]);
      
      try {
          HttpResponse response = httpClient.execute(httpPost);
          jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
      } catch (ClientProtocolException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
       } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
     }
     return null;
}
   @Override
   protected void onPreExecute() {
     // TODO Auto-generated method stub
     super.onPreExecute();
   }
   
   @Override
   protected void onPostExecute(String result) {
      super.onPostExecute(result);
      System.out.println("Output " + jsonResult);
   }

   private StringBuilder inputStreamToString(InputStream is) {
     
      String rLine = "";
      StringBuilder answer = new StringBuilder();
      BufferedReader br = new BufferedReader(new InputStreamReader(is));
    
      try {
          while ((rLine = br.readLine()) != null) {
              answer.append(rLine);
          }
      } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
      return answer;
   }
}

The code above is use to extract the content of a website. The NetworkCalls class is instantiated in the MainActivity.java file and the Async method execute is called with a string parameter that denote the website to connect to. The modified code in the MainActivity.java is shown below.

package com.tutorial.networkavailability;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

       private String url = "Path to your url";

      @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);

              if(isNetworkAvailable()){
                 // do network operation here     
                 NetworkCalls myAsync = new NetworkCalls();
                 myAsync.execute(new String[]{url});
              }else{
                 Toast.makeText(this, "No Available Network. Please try again later", Toast.LENGTH_LONG).show();
                 return;
              }
       }

       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
           // Inflate the menu; this adds items to the action bar if it is present.
           getMenuInflater().inflate(R.menu.main, menu);
           return true;
       }

       @Override
       public boolean onOptionsItemSelected(MenuItem item) {
          // Handle action bar item clicks here. The action bar will
         // automatically handle clicks on the Home/Up button, so long
         // as you specify a parent activity in AndroidManifest.xml.
         int id = item.getItemId();
         if (id == R.id.action_settings) {
            return true;
         }
         return super.onOptionsItemSelected(item);
       }

       public boolean isNetworkAvailable() {
           ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
           NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
           return activeNetworkInfo != null && activeNetworkInfo.isConnected();
       }
}

Before you test for network availability, remember to add this permission in your android project manifest file.

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

If you have any question or suggestion kindly use our comment box below. You can also download the sources code for this tutorial below

Add a Comment