Tuesday, September 24, 2013

Check internet connection using broadcast receiver

In android device basically 2 types of internet connectivity.

1. Mobile internet (GPRS)
2. Wifi internet connectivity

If we need to perform some operation on internet connectivity change,Here is the full code for it.It is very useful to sync application data in offline and online mode also.


Let's Start 


  • First of all give below permission just above <application> tag.

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


  • We are using broadcast receiver for notification. Broadcast receiver provides the functionality of background process.
  • It is running in back end continuously and will give notification.For this purpose we need to register our broadcast receiver in AndroidMenifest.xml file.  
  • Write down below code before completion of </application> tag(In <Application> tag).
<receiver
            android:name="<package_name>.NetworkChangeReceiver"
            android:label="NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>


  • Full AndroidMenifest.xml is given below:

AndroidMenifest.xml


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

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

    <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.example.broadcast_internetcheck.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>

        <receiver
            android:name="com.example.broadcast_internetcheck.NetworkChangeReceiver"
            android:label="NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>
    </application>

</manifest>


  • Now Create on global file for check internet connectivity.It will return the result of which internet connectivity is currently active.
  • Create new java class file and named it, NetworkUtil.java

NetworkUtil.java


public class NetworkUtil {

public static int TYPE_WIFI = 1;
   public static int TYPE_MOBILE = 2;
   public static int TYPE_NOT_CONNECTED = 0;
    
    
   public static int getConnectivityStatus(Context context) {
       ConnectivityManager cm = (ConnectivityManager) context
               .getSystemService(Context.CONNECTIVITY_SERVICE);
 
       NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
       if (null != activeNetwork) {
           if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
               return TYPE_WIFI;
            
           if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
               return TYPE_MOBILE;
       } 
       return TYPE_NOT_CONNECTED;
   }
    
   public static String getConnectivityStatusString(Context context) {
       int conn = NetworkUtil.getConnectivityStatus(context);
       String status = null;
       if (conn == NetworkUtil.TYPE_WIFI) {
           status = "Wifi enabled";
       } else if (conn == NetworkUtil.TYPE_MOBILE) {
           status = "Mobile data enabled";
       } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
           status = "Not connected to Internet";
       }
       return status;
   }
}


  • If you get some error,than press Ctrl + Shift + O. It will import missing inbuilt library.
  • Create new java class file and named it, NetworkChangeReceiver.java and write down below code. It extends BroadcastReceiver. We have already registered it on AndroidMenifest.xml file.

NetworkChangeReceiver.java



import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class NetworkChangeReceiver extends BroadcastReceiver{

@Override
   public void onReceive(final Context context, final Intent intent) {
 
       String status = NetworkUtil.getConnectivityStatusString(context);
 
       Toast.makeText(context, status, Toast.LENGTH_LONG).show();
   }
}

  • Now run this project and get output. Remember that for Wifi result run it on real device. It may not give the gesult of WIFI Connectivity.

5 comments:

  1. it runs only on avd 2.3.3. i've tryied it on s4 4.3 and nexus 7 4.4.2 but nothing!! pls reply!

    ReplyDelete
  2. how to Call broadcast in Login Screen whether Checking connection available or not

    ReplyDelete
    Replies
    1. You can check in LoginActivity Class by creating object of NetworkUtil and then call method "getConnectivityStatus" while login button pressed.

      Like,
      NetworkUtil utils = new NetworkUtil();
      int status = utils. getConnectivityStatus(getApplicationContext);

      if(status != 0){
      // Do login process
      }else{
      // Print error message that no internet connectivity
      }


      This code will help you to fulfill your requirement

      Delete
  3. how to use the above classes througtout application and in every class i need to check and monitor internet connection so how can i use the above single class throught application

    ReplyDelete