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.
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 −
1 |
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); |
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 –
1 2 3 |
NetworkInfo[] info = check.getAllNetworkInfo();//All network info NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();//Active network info |
The last thing you need to do is to check Connected State of the network. Its syntax is given below −
1 2 3 4 5 6 7 8 9 10 11 12 13 |
//All network info for (int i = 0; i<info.length; i++){ if (info!= null && info[i].getState() == NetworkInfo.State.CONNECTED){ Toast.makeText(context, "Internet is connected Toast.LENGTH_SHORT).show(); } } //Active network info if (networkInfo != null && networkInfo.isConnected()) { Toast.makeText(context, "Internet is connected Toast.LENGTH_SHORT).show(); } |
Apart from this connected states, there are other states a network can achieve. They are listed below:
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.
In this tutorial, we are going to learn how to detect Internet connection in whole app using Broadcast Receiver.
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.
1 2 3 |
<!-- This permissions are neccessary for broadcast receiver --> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_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.
1 2 3 4 5 6 7 8 9 10 11 12 |
<!-- Broadcast receiver declaration in manifest file and make sure to enable it --> <receiver android:name="com.internetconnection_demo.InternetConnector_Receiver" android:enabled="true" > <intent-filter> <!-- Intent filters for broadcast receiver --> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> <action android:name="android.net.wifi.WIFI_STATE_CHANGED" /> <action android:name="android.net.wifi.STATE_CHANGE" /> </intent-filter> </receiver> |
4. Now, you manifest file would be like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.internetconnection_demo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="22" /> <!-- This permissions are neccessary for broadcast receiver --> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- Put your MyApplication inside application tag --> <application android:name="com.internetconnection_demo.MyApplication" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".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> <!-- Broadcast receiver declaration in manifest file and make sure to enable it --> <receiver android:name="com.internetconnection_demo.InternetConnector_Receiver" android:enabled="true" > <intent-filter> <!-- Intent filters for broadcast receiver --> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> <action android:name="android.net.wifi.WIFI_STATE_CHANGED" /> <action android:name="android.net.wifi.STATE_CHANGE" /> </intent-filter> </receiver> </application> </manifest> |
5. Now, create a simple layout naming activity_main.xml and this layout contain only one TextView to display Internet Status.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" > <!-- This text will display the status of internet --> <TextView android:id="@+id/internet_status" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:textSize="20sp" android:textStyle="bold" /> </RelativeLayout> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package com.internetconnection_demo; import android.app.Application; public class MyApplication extends Application { // Gloabl declaration of variable to use in whole app public static boolean activityVisible; // Variable that will check the // current activity state public static boolean isActivityVisible() { return activityVisible; // return true or false } public static void activityResumed() { activityVisible = true;// this will set true when activity resumed } public static void activityPaused() { activityVisible = false;// this will set false when activity paused } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
package com.internetconnection_demo; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; public class InternetConnector_Receiver extends BroadcastReceiver { public InternetConnector_Receiver() { } @Override public void onReceive(Context context, Intent intent) { try { boolean isVisible = MyApplication.isActivityVisible();// Check if // activity // is // visible // or not Log.i("Activity is Visible ", "Is activity visible : " + isVisible); // If it is visible then trigger the task else do nothing if (isVisible == true) { ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager .getActiveNetworkInfo(); // Check internet connection and accrding to state change the // text of activity by calling method if (networkInfo != null && networkInfo.isConnected()) { new MainActivity().changeTextStatus(true); } else { new MainActivity().changeTextStatus(false); } } } catch (Exception e) { e.printStackTrace(); } } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
// Method to change the text status public void changeTextStatus(boolean isConnected) { // Change status according to boolean value if (isConnected) { internetStatus.setText("Internet Connected."); internetStatus.setTextColor(Color.parseColor("#00ff00")); } else { internetStatus.setText("Internet Disconnected."); internetStatus.setTextColor(Color.parseColor("#ff0000")); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@Override protected void onPause() { super.onPause(); MyApplication.activityPaused();// On Pause notify the Application } @Override protected void onResume() { super.onResume(); MyApplication.activityResumed();// On Resume notify the Application } |
Full Source code of MainActivity.java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
package com.internetconnection_demo; import android.content.Context; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private static TextView internetStatus; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); internetStatus = (TextView) findViewById(R.id.internet_status); // At activity startup we manually check the internet status and change // the text status ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { changeTextStatus(true); } else { changeTextStatus(false); } } // Method to change the text status public void changeTextStatus(boolean isConnected) { // Change status according to boolean value if (isConnected) { internetStatus.setText("Internet Connected."); internetStatus.setTextColor(Color.parseColor("#00ff00")); } else { internetStatus.setText("Internet Disconnected."); internetStatus.setTextColor(Color.parseColor("#ff0000")); } } @Override protected void onPause() { super.onPause(); MyApplication.activityPaused();// On Pause notify the Application } @Override protected void onResume() { super.onResume(); MyApplication.activityResumed();// On Resume notify the Application } } |
9. Now, you can check internet connection at a particular point or in whole app according to your need.
Thanks.
Subscribe to us and get the latest news.
15 Comments
Carlos Botero
Saturday, October 28th, 2017Hello. 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, 2017Hi 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, 2017Dr. 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, 2017Hi 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, 2017it 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, 2017Never mind. My app works fine on devices now. I use manually registration in the code.
Thank you
Ming
Pradeep
Friday, February 2nd, 2018How to implement same in a fragment
Dr. Droid
Friday, February 2nd, 2018Hi 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, 2018sourecode not soures android
Dr. Droid
Friday, December 28th, 2018Hi 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, 2018where soure code android ?
Dr. Droid
Saturday, December 29th, 2018Hi
You can find source code link at the end of the article.
Thanks
zoro
Monday, December 31st, 2018thank 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, 2019This checks only wifi, 4G is not checked which makes it useless to use in other applications.
rehaman
Friday, July 12th, 2019can u please how to use this in fragment,i was having view in fragment ,ineed to update value in fragment