Android Internet Connection Status & Network Change Receiver example

If you are developing an Android app you may already fetching information from internet. While doing so there is a chance that internet connection is not available on users handset. Hence its always a good idea to check the network state before performing any task that requires internet connection. You might also want to check what kind of internet connection is available in handset. For example is wifi currently enabled? or is mobile data network is connected.

Check Internet Connection

Here is a simple code snippet that will help you identify what kind of internet connection a user has on her device. First we need following permission in order to access network state. Add following permission to your AndroidManifest.xml file. Permissions required to access network state:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Code language: HTML, XML (xml)

Now check following utility class NetworkUtil. It has method getConnectivityStatus which returns an int constant depending on current network connection. If wifi is enabled, this method will return TYPE_WIFI. Similarly for mobile data network is returns TYPE_MOBILE. You got the idea!! There is also method getConnectivityStatusString which returns current network state as a more readable string.NetworkUtil.java

package net.viralpatel.network; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; 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; } }
Code language: Java (java)

You can use this utility class in your android app to check the network state of the device at any moment. Now this code will return you the current network state whenever the utility method is called. What if you want to do something in your android app when network state changes? Lets say when Wifi is disabled, you need to put your android app service to sleep so that it does not perform certain task. Now this is just one usecase. The idea is to create a hook which gets called whenever network state changes. And you can write your custom code in this hook to handle the change in network state.

Broadcast Receiver to handle changes in Network state

You can easily handle the changes in network state by creating your own Broadcast Receiver. Following is a broadcast receiver class where we handle the changes in network. Check onReceive() method. This method will be called when state of network changes. Here we are just creating a Toast message and displaying current network state. You can write your custom code in here to handle changes in connection state.NetworkChangeReceiver.java

package net.viralpatel.network; 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(); } }
Code language: Java (java)

Once we define our BroadcastReceiver, we need to define the same in AndroidMenifest.xml file. Add following to your menifest file.

<application ...> ... <receiver android:name="net.viralpatel.network.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>
Code language: HTML, XML (xml)

We defined our broadcast receiver class in menifest file. Also we defined two intent CONNECTIVITY_CHANGE and WIFI_STATE_CHANGED. Thus this will register our receiver for given intents. Whenever there is change in network state, android will fire these intents and our broadcast receiver will be called. Below is complete AndroidMenifest.xml file. AndroidMenifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.viralpatel.network" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <receiver android:name="net.viralpatel.network.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>
Code language: HTML, XML (xml)

Run this demo in android emulator or actual device. When Wifi is enabled, you’ll see a Toast message with message.

android-network-change-broadcast-wifi-enabled

Now disable Wifi. The toast message will show you message that internet connection is not available.

android-network-change-broadcast-receiver-not-connected

Now enable mobile data network. The same will be show in toast message as soon as you enable mobile data connection.

android-data-connection-broadcast-receiver

Download Source Code

Browse through the source code in following Git repository: 

GitHub: https://github.com/viralpatel/android-network-change-detect-example 

Download complete source code: 

Download: android-network-change-detect-example.zip (376 KB)

Get our Articles via Email. Enter your email address.

You may also like...

36 Comments

  1. Rachita says:

    Thanks a lot for the post !! It saved my day and lot of time :)

  2. Afsane says:

    Thanks a lot
    please repair Download link

  3. Dickson says:

    very helpful, thanks.

  4. Harendra singh says:

    thanks a lot.please post more other topic in android

  5. sesan says:

    Thanks a lot for your tutorial but I have an issue I have developed an app that can send my basic form information to google drive spreadsheet but I want to add a code where by if the user network is down it would pen the information and the moment network comes up it would send the information to the spreadsheet what can I do thanks.

  6. Seshu Vinay says:

    What if the device is connected to a network and no internet access?

  7. Dirk Munk says:

    The first example on this page is a very bad piece of programming in my opinion. First you should check if you have a connection, then you should check what kind of connection it is. There are about a dozen different types of connections possible, and in this example only two are checked, and if it is neither one of them then it is concluded that there is no connection. Not so, what if you have a wired connection (ethernet) for instance? And you should only check what kind of connection you have after you concluded that there is a connection, which means that concluding that there is no connection because it is not mobile or wifi or what ever is wrong anyway.

    • Nirmal says:

      Wired connection on a mobile device?

  8. Mauma says:

    Thanks for all!!

  9. Nik says:

    Could you please explain? What ll happen, if i connect the device with ethernet?….

  10. logesh says:

    can u give .apk for this

  11. Andre gomes says:

    How would I do this in my activity? would have to use the RegisterReceiver?

  12. birdman says:

    Hi this was really a cool tutorial but ive been thinking its not working when i try to run it from eclipse using the full source code thanks for the help

  13. Leandro says:

    How to show a Dialog instead toast ?

  14. Stuti says:

    Hey this code is not working I guess there is some prob can u help and cand u mail a fresh copy of it and its .apk

    • Akshit says:

      This wont work anymore, as of Kitkat! So, you need to explore other options :)
      I am also currently working on it. Best of luck!

  15. Dado says:

    Hi!
    I’ve tryied it on my samsung galagy s2 with android 4.1.2 and do not works. I’ve tryied it on avd with android 4.1.2 and do not works. I’ve tryied it on avd with android 4.4.2 and do not works. It works only with avd with android 2.3.3! Do you know why?

    TNX
    D!

    • Divya says:

      Hi

      Please replace your manifest file with below code

      ?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
      &lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
          package=&quot;com.xyz.networkutility&quot;
          android:versionCode=&quot;1&quot;
          android:versionName=&quot;1.0&quot; &gt;
      
          &lt;uses-sdk
              android:minSdkVersion=&quot;8&quot;
              android:targetSdkVersion=&quot;17&quot; /&gt;
          
          &lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt; 
      
          &lt;application
              android:allowBackup=&quot;true&quot;
              android:icon=&quot;@drawable/ic_launcher&quot;
              android:label=&quot;@string/app_name&quot;
              android:theme=&quot;@style/AppTheme&quot; &gt;
              
              &lt;activity
                  android:name=&quot;com.xyz.networkutility.MainActivity&quot;
                  android:label=&quot;@string/app_name&quot; &gt;
                  &lt;intent-filter&gt;
                      &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
      
      
                      &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
                  &lt;/intent-filter&gt;
              &lt;/activity&gt;
              
              &lt;receiver            
                  android:name=&quot;com.xyz.networkutility.NetworkChangeReceiver&quot;           
                  android:label=&quot;NetworkChangeReceiver&quot; &gt;            
                   &lt;intent-filter&gt;                 
                       &lt;action android:name=&quot;android.net.conn.CONNECTIVITY_CHANGE&quot; /&gt;                
                       &lt;action android:name=&quot;android.net.wifi.WIFI_STATE_CHANGED&quot; /&gt;            
                   &lt;/intent-filter&gt;        
                &lt;/receiver&gt; 
          &lt;/application&gt;
      
      &lt;/manifest&gt;
      

      Then try it with version above 2.3, it will work

    • Divya says:

      Hi

      Try adding your MainActivity launcher code in your manifest file.
      for example


      Then try with version above 2.3

  16. Divya says:

    Hi
    Please replace your manifest file with below code

    ?xml version=”1.0″ encoding=”utf-8″?>

    Then try it with version above 2.3, it will work

  17. Waheed says:

    Thanks for the tutorial.. I need a little help, I want different activities to be started as network status changes. To make it more simple, I want a specific activity to be started as long as the device is connected to internet but as it gets disconnected, it starts a new activity. Pls guide.

  18. Pradip says:

    Thanks for this post! I have one question,could you please answer it?

    Once wifi is connected I want to download file from server e.g tomcat , how can i do this?
    I have file downloading code with me, I have tried this code on button click where it works properly i.e on button click i am able to download file from server, but how can i do this with broadcast receiver i.e when wi-fi is connected it should automatically download file from server?

  19. maxy says:

    it will only tell if u are connected to a network or not.It’ll not tell anything about the active internet connection.

  20. Lakshman says:

    Thank you very much…

  21. Hi,
    This tutorail is great to detect network connection enable/disable state and also for wifi to mobiledata switch event.
    But i need to detect wifi to wifi switch event.is that possilbe and how.?
    With thanks,
    tanvir

  22. Jay says:

    I can’t run the project because there is no activity found.

  23. Douglas says:

    Thank you very much…

  24. Aviroop Sanyal says:

    Thanks for this tutorial, but I have a question.Will the toasts be shown when a user has changed wifi state of his/her mobile

  25. satish says:

    sir it is displaying msg two time.
    exmpl= connected date ,connected data

    what should i do to it display msg only once.

    thnks

  26. Deepak says:

    smart coding…great tutorial…Thanks

  27. rash says:

    hello how can i display retry and cancel message in Web View if internet connection lost ,and when connected to internet it should reload my page in same Web View app?

  28. Alvin says:

    Hi.
    This works fine. How can I make the application run this service from boot time?

  29. active92 says:

    These two lines gives me errors. Kindly assist me on this.

  30. Hariharan says:

    Works fine. Thanks for the info.

  31. Allan says:

    Hello, thanks a lot. Is there a way to detect background data restricted status for android?

  32. instasaver says:

    A big thank you for this great article. it saved a lot of time.

Leave a Reply

Your email address will not be published. Required fields are marked *