Android Detect Internet Connection - Androhub

Internet Connection

Android Detect Internet Connection Using Broadcast Receiver

Android lets your application connect to the internet or any other local network and allows you to perform network operations.

A device can have various types of network connections. If your app needs internet connection to make HTTP Requests and or you need internet connection in your whole app then it is better to check internet connectivity status before making any HTTP Requests to avoid http exceptions.

Checking Network Connection

Before you perform any network operations, you must first check that are you connected to that network or internet. For this android provides ConnectivityManager class. You need to instantiate an object of this class by calling getSystemService() method. Its syntax is given below −

Once you instantiate the object of ConnectivityManager class, you can use getAllNetworkInfo()  or getActiveNetworkInfo() method to get the information of all or active networks respectively. First method returns an array of NetworkInfo and second method return active network info. So you have to receive it like this –

The last thing you need to do is to check Connected State of the network. Its syntax is given below −

Apart from this connected states, there are other states a network can achieve. They are listed below:

  1. Connecting.
  2. Disconnected.
  3. Disconnecting.
  4. Suspended.
  5. Unknown.

Now, since we are using Broadcast Receiver to detect the internet connection then we should know about Broadcast Receiver.

Broadcast Receivers simply respond to broadcast messages from other applications or from the system itself. These messages are sometime called events or intents. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this communication and will initiate appropriate action.

Example

In this tutorial, we are going to learn how to detect Internet connection in whole app using Broadcast Receiver.

Video Demo

1. Create a new project in Eclipse by navigating to File ⇒ New Android ⇒ Application Project and fill required details. By default my activity is MainActivity.java.

2. After creating first step the second thing we have to do is adding certain permissions to Manifest file for accessing Network State.

3. After putting permissions we have to put our receiver also in manifest file with some intent filters and make sure to enable it.

4. Now, you manifest file would be like this.

5. Now, create a simple layout naming activity_main.xml and this layout contain only one TextView to display Internet Status.

6. When we are using Broadcast Receiver it will always trigger when internet is not there if your activity is closed. So for this we have to make an java class naming MyApplication.java extended by Application. This class is used to check if activity is visible or not and trigger receiver if activity is visible.

7. Now create a another class for broadcast receiver naming InternetConnection_Receiver.java extended by BroadcastReceiver. In this class we get the boolean value from the MyApplication class to check whether the activity is visible or not and check network status if activity is visible else do nothing.

If activity is visible then change the status of TextView that we created in activity_main.xml layout.

8. Finally come to your MainActivity.java and add the following code. As you are seeing that i had added network connection code at starting to check internet status at starting and change TextView text according to that. And we had created a method that is used to change the TextView status according to boolean value it received.

Also we have to set activity visibility by calling MyApplication on onPause() and onResume() method. This will set true and false value to MyApplication boolean variable.

Full Source code of MainActivity.java.

9. Now, you can check internet connection at a particular point or in whole app according to your need.

Thanks. :)

 

15 Comments

Carlos Botero
Saturday, October 28th, 2017

Hello. I am getting an error: “leaked broadcast receiver”. I know I need to implement “unregisterReceiver”, but exactly how and where in the code?

Dr. Droid
Saturday, October 28th, 2017

Hi Carlos,

You need to unregister broadcast receiver in onDestroy() method of your activity like below:

@Override
protected void onDestroy() {
super.onDestroy();
//unregister receiver here
}

Thanks

Ming
Tuesday, December 19th, 2017

Dr. Droid,

I found the code you provide works perfectly on API 23 and up. But does not work on API 21 and API 22. When I disconnect the network, it still shows “Internet Connected”. Is this behavior expected?

Thank you

Dr. Droid
Tuesday, December 19th, 2017

Hi Ming,

Actually this is very old article and i had tested the code in I think Kitkat or Lollipop device. So can you please check whether the code is running only in API 23 or it is not working in API 21 and API 22 but it is working in other API levels.

Thanks

Ming
Tuesday, December 19th, 2017

it works perfectly in API 23 and up. But not working in API 21 and 22. I did not test the lower level because I don’t have emulators for those levels.

I looked at the android documentation on broadcastreceiver and connectivitymanager, does not find any clue there.

I need this feature in my app and hope it can work in API 21 and 22. Could you please take a quick test on your code if possible? Maybe I made some silly mistake. But I don’t change any code in your app. The only thing I updated is distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip in gradle-wrapper.properties in order to build it in android studio 3.0.

Thank you

Ming
Tuesday, December 19th, 2017

Never mind. My app works fine on devices now. I use manually registration in the code.

Thank you

Ming

Pradeep
Friday, February 2nd, 2018

How to implement same in a fragment

Dr. Droid
Friday, February 2nd, 2018

Hi Pradeep,

You can implement same like Activity in Fragment as Fragment Lifecycle depends upon Activity only. So whenever onPause and onResume method calls then notify the fragment via Interface.

Thanks

salwa
Friday, December 28th, 2018

sourecode not soures android

Dr. Droid
Friday, December 28th, 2018

Hi Salwa,

This code is very old when Android Studio just came in picture. Still you can covert this project in studio.
Check this link : https://stackoverflow.com/questions/22791150/how-do-you-import-an-eclipse-project-into-android-studio-now

Thanks

zoro
Friday, December 28th, 2018

where soure code android ?

Dr. Droid
Saturday, December 29th, 2018

Hi

You can find source code link at the end of the article.

Thanks

zoro
Monday, December 31st, 2018

thank you but I tried it but it does not work out when I go out and go back to the application again

Dev
Monday, March 25th, 2019

This checks only wifi, 4G is not checked which makes it useless to use in other applications.

rehaman
Friday, July 12th, 2019

can u please how to use this in fragment,i was having view in fragment ,ineed to update value in fragment

Post comment

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