Android automatically detect internet connection status

If you have an android application that needs to sync data with a backend server but doesn't need the internet to be available all the time for it to work then you must know at all times whether your app has access to internet or not. As soon as you have internet connection you can get latest data from the server or post any changes saved in your app using HTTP service. In this example we extend the BroadcastReceiver to listen for any changes in network status and then find out whether the app has internet at that time. Please note that you have to specify the ACCESS_NETWORK_STATE in your android manifest permissions for this to work otherwise you will get java.lang.SecurityException: ConnectivityService: Neither user XXXXX nor current process has android.permission.ACCESS_NETWORK_STATE.

Android automatically detect internet connection status Android Internet connection status

Android Application Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.as400samplecode"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.as400samplecode.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Android Application Layout

<RelativeLayout 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"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/networkStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="false"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />
   
</RelativeLayout>

Android Application Main Activity

package com.as400samplecode;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

 private static final String LOG_TAG = "CheckNetworkStatus";
 private NetworkChangeReceiver receiver;
 private boolean isConnected = false;
 private TextView networkStatus;

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

  IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
  receiver = new NetworkChangeReceiver();
  registerReceiver(receiver, filter);
  
  networkStatus = (TextView) findViewById(R.id.networkStatus);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }
 
 @Override
 protected void onDestroy() {
  Log.v(LOG_TAG, "onDestory");
  super.onDestroy();
  
  unregisterReceiver(receiver);

 }


 public class NetworkChangeReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(final Context context, final Intent intent) {

   Log.v(LOG_TAG, "Receieved notification about network status");
   isNetworkAvailable(context);

  }


  private boolean isNetworkAvailable(Context context) {
   ConnectivityManager connectivity = (ConnectivityManager) 
     context.getSystemService(Context.CONNECTIVITY_SERVICE);
   if (connectivity != null) {
    NetworkInfo[] info = connectivity.getAllNetworkInfo();
    if (info != null) {
     for (int i = 0; i < info.length; i++) {
      if (info[i].getState() == NetworkInfo.State.CONNECTED) {
       if(!isConnected){
        Log.v(LOG_TAG, "Now you are connected to Internet!");
        networkStatus.setText("Now you are connected to Internet!");
        isConnected = true;
        //do your processing here ---
        //if you need to post any data to the server or get status
        //update from the server
       }
       return true;
      }
     }
    }
   }
   Log.v(LOG_TAG, "You are not connected to Internet!");
   networkStatus.setText("You are not connected to Internet!");
   isConnected = false;
   return false;
  }
 }


}


3 comments :

  1. thanks for post. but there is a one point i don't understand.

    if(info[i].getState()==NetworkInfo.State.CONNECTED) {
    if(!isConnected){

    Why !isConnected.

    Thanx
    Best Regards

    ReplyDelete
    Replies
    1. Yeah I know that's confusing but the NetworkChangeReceiver was getting called multiple times. May be its fixed in the current version. So all I do is if we already have an internet then ignore the next request, basically if you want to kickoff a process as soon as get internet then you don't want that action done more than once.

      Delete
  2. Insipid now looking at life fifa 14 coins, I always hope that when the President so as romantic love, then warm. Every time I go to his business trip to the capital of poetry, he made a number of text cheap fifa 14 coins messages, hoping to use text messages as in the past to convey love and always have to ignore the rationale for each gas in their own death. Since some of his daughter, he and cold weather to give her daughter fifa 14 coins more than the clothes to wear; daughter learning to walk, and she let fall a good;

    ReplyDelete