Detecting internet connection status in your app is very easy and won’t take more than 5mins. In this article you will learn how to detect internet connection status manually and automatically. Using broadcast receiver, your app will be automatically notified when there is a change in network connection.

This provides easy way do any changes in the app like hiding few button (like WhatsApp hides send, upload icon when there is not internet), navigation user to another screen, or just show a Snackbar message.


Creating New Project

1. Create a new project in Android Studio from File โ‡’ New Project. When it prompts you to select the default activity, select Blank Activity and proceed.

2. Create a class named ConnectivityReceiver.java and extend it from BroadcastReceiver. This is a receiver class which will be notified whenever there is change in network / internet connection.

package info.androidhive.checkinternet;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ConnectivityReceiver
        extends BroadcastReceiver {

    public static ConnectivityReceiverListener connectivityReceiverListener;

    public ConnectivityReceiver() {
        super();
    }

    @Override
    public void onReceive(Context context, Intent arg1) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null
                && activeNetwork.isConnectedOrConnecting();

        if (connectivityReceiverListener != null) {
            connectivityReceiverListener.onNetworkConnectionChanged(isConnected);
        }
    }

    public static boolean isConnected() {
        ConnectivityManager
                cm = (ConnectivityManager) MyApplication.getInstance().getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null
                && activeNetwork.isConnectedOrConnecting();
    }


    public interface ConnectivityReceiverListener {
        void onNetworkConnectionChanged(boolean isConnected);
    }
}

3. Create another class named MyApplication.java and extend it from Application. This class will be called whenever app is launched. Here setConnectivityListener() method is used to initiate the connectivity listener.

package info.androidhive.checkinternet;

import android.app.Application;

public class MyApplication extends Application {

    private static MyApplication mInstance;

    @Override
    public void onCreate() {
        super.onCreate();

        mInstance = this;
    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }

    public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) {
        ConnectivityReceiver.connectivityReceiverListener = listener;
    }
}

4. Open AndroidManifest.xml and do the below changes.

> Add MyApplication to <application> tag.

> Add ConnectivityReceiver as <receiver>.

> Declare INTERNET and ACCESS_NETWORK_STATE permissions.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.checkinternet">

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

    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <receiver
            android:name=".ConnectivityReceiver"
            android:enabled="true">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>

    </application>

</manifest>

Broadcasting Internet Status to All Activities

Now we have all the setup ready. Let’s see how to notify an activity when the device is connected or disconnected from internet.

5. Open layout file main activity activity_main.xml add the below layout.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="info.androidhive.checkinternet.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="@dimen/activity_vertical_margin"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Turn on/off wifi to notify the app about connection status." />

        <Button
            android:id="@+id/btn_check"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="Check Connection" />
    </LinearLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@drawable/ic_add_white_24dp" />

</android.support.design.widget.CoordinatorLayout>

6. Open your MainActivity.java and do the below changes to receive the internet status.

> Register the connection change listener in onResume() method by calling MyApplication.getInstance().setConnectivityListener(this).

> Implement the activity from ConnectivityReceiver.ConnectivityReceiverListener which will override onNetworkConnectionChanged() method.

> onNetworkConnectionChanged() method will be triggered whenever device is connected / disconnected from internet. You need to take appropriate action here.

Follow the above same three steps in all other activities in which in you want to notify the internet status.

package info.androidhive.checkinternet;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity
        implements ConnectivityReceiver.ConnectivityReceiverListener {

    private Button btnCheck;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        btnCheck = (Button) findViewById(R.id.btn_check);

        // Manually checking internet connection
        checkConnection();

        btnCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Manually checking internet connection
                checkConnection();
            }
        });
    }

    // Method to manually check connection status
    private void checkConnection() {
        boolean isConnected = ConnectivityReceiver.isConnected();
        showSnack(isConnected);
    }

    // Showing the status in Snackbar
    private void showSnack(boolean isConnected) {
        String message;
        int color;
        if (isConnected) {
            message = "Good! Connected to Internet";
            color = Color.WHITE;
        } else {
            message = "Sorry! Not connected to internet";
            color = Color.RED;
        }

        Snackbar snackbar = Snackbar
                .make(findViewById(R.id.fab), message, Snackbar.LENGTH_LONG);

        View sbView = snackbar.getView();
        TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
        textView.setTextColor(color);
        snackbar.show();
    }

    @Override
    protected void onResume() {
        super.onResume();

        // register connection status listener
        MyApplication.getInstance().setConnectivityListener(this);
    }

    /**
     * Callback will be triggered when there is change in
     * network connection
     */
    @Override
    public void onNetworkConnectionChanged(boolean isConnected) {
        showSnack(isConnected);
    }
}

Run the project and try turning off / on wifi or mobile data. You can notice a Snackbar is shown with network connection status.

android-detecting-internet-connection-status
Subscribe
Notify of
guest
222 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ashish Mishra
Ashish Mishra
7 years ago

Due non-availability of Internet, I get fail message , need to store the data locally it as soon as valid internet connectivity is available then send data.How will i do it?

Satish
Satish
7 years ago

thanks

neel
neel
7 years ago

Hi Ravi,

I tried your connectiondetector code but its returning true always and not going to else loop.could u please sort out the problem.i used your code as it is.

neel
neel
7 years ago
Reply to  neel

its done now.actully the problem was from my side.i did not disabled my device internet connection instead it i was disabling it in my system.thanks a lot for such a nice tutorial

phiko
phiko
7 years ago

thanks, this tutorial is very helpful…

Meghna
Meghna
7 years ago

Thanks for the nice tutorial man… Even this http://www.compiletimeerror.com/2013/06/check-internet-connection-in-android.html might help, have a look…

Dickson Owuor
Dickson Owuor
7 years ago

very helpful, thanks

padi
padi
7 years ago

hi ravi
i have aquestion, if u can help me im so thankful. i have an app that need access to internet in some activity but when the net speed is low all my activities run slowly .when i delete permission it works fine .what can i do :(( help me

dovin
dovin
7 years ago
Reply to  padi
Naresh Sharma
Naresh Sharma
7 years ago

Very nice and Simple tutorial. Thanks

Thet Paing
Thet Paing
7 years ago

I want to know i want to use without refreshing , how to validate internet connection meaning auto check internet connection.

Trollzito
Trollzito
7 years ago

ok men!! ok excelent! yeah

BruStack
BruStack
6 years ago
Reply to  Trollzito

nice english, hihi

rajesh
rajesh
7 years ago

This is not giving correct response when im connected to the wifi which is not connected to the internet.

Apex
Apex
6 years ago

Excellent tutorial…Thanks ravi..

Mohd
Mohd
6 years ago

Nice tutorials. but it check only data enable or not in internal setting only,, not externally. that means when i transfer the data in host side it check the network status in that time

Henrique Kalil
Henrique Kalil
6 years ago

Thanks!

B. Clay Shannon
B. Clay Shannon
6 years ago

ConnectionDetector needs a return type to compile (I inserted “void”).

A
A
6 years ago

No, It doesn’t show. It only checks ON or OFF not for active state.

James Carter
James Carter
6 years ago

Thanks, this was a nice little tutorial and added a much needed notification to my app ๐Ÿ™‚

Rafael Ruiz
Rafael Ruiz
6 years ago

Great!

Mayur
Mayur
6 years ago

nice

Edgar
Edgar
6 years ago

this only works when you are connected to any network, but doesn’t work when you want to know if that network has internet connection

Vishal gupta
Vishal gupta
6 years ago

dude,Its check status only… but some time internet connected but no internet access…

Runesh
Runesh
6 years ago

Dude when ever i check it only returns true value.When i dont have internet then also it returns you have internet !!!!

Amit Kumar kashyap
Amit Kumar kashyap
6 years ago

Thanks a lot ..

AyaM Sakata
AyaM Sakata
6 years ago

this is the best android tutorial website I’ve ever visited.. THANKS..

prasad Vdv
prasad Vdv
6 years ago

when we connected wifi even there is limited network. it shows internet is connected

Theo Viset
Theo Viset
5 years ago

Hi all,

I have a question regarding the process Android uses to determine internet connection. The case is this.

We have an Android USB stick that does not set the correct date/time when it starts. When we connect it to internet and set auto date/time, it is correctly synced at startup, and the network connection states that there is internet, and the name of the wifi or wired network.

Now, when we place a router in the wifi network configuration, the Android player states that there is no internet connection and the date/time is not set. However, browsing pages through a browser (Chrome) works fine, and so do RSS feeds. Syncing date/time does not work, although all NTP ports in the router have been opened. When we drop all access lists in the router, syncing works fine, so it must be one of these access rules, but there are too many to find the correct one.

Since Android states that there is no internet connection but browsing pages works fine, I assume that at startup, Android signals some (Google) URL to determine whether there is internet connection (most likely some functionality in the isConnectingToInternet() functionality in this tutorial), and that this particular signal is blocked for security reasons. Am I correct that if at startup Android determines that there is no internet connection, it stops any other functionality to attempt to work, since it flagged no internet to be available?

Does anyone here know what steps Android takes exactly to determine internet availability? What URL or port or combination of these that may be blocked by some routers?

Thanks a million,

regards, Theo

Allay Khalil
Allay Khalil
5 years ago

I have a question regarding the process Android uses to determine internet connection. The case is this:
When i have implemented this tutorial,If Device is Connected to WiFi device and net is not coming on the device then this tutorial implementation showing that there is net present>How i can fix this

Ngแปc Anh Lรช
Ngแปc Anh Lรช
5 years ago

tutorial is very good. Thank for share.

Allay Khalil
Allay Khalil
5 years ago

Hy to All,i have implemented this tutorial but i have some confusion in this,when i implement this tutorial,it tells me that either my device is connected to WiFi or not,but it not make sure that internet is coming on my device,i Any guess?

Rida Noor
Rida Noor
5 years ago

V nice… your coding and description is always very helpful.. Thanks

Ravi Tamada
5 years ago
Reply to  Rida Noor

You are welcome ๐Ÿ™‚

terGmas
terGmas
5 years ago

Nice solution but it does not tell you whether or not you are connected to the Internet. Instead it checks that at least one of the connections you can have setted up is connected to __SOME__ network, be it a public wifi with access to the Internet or private, corporate intranet without access to the Internet.

anandh
anandh
5 years ago

v nice using alert how to use intent can anyone help me pls….

Sahitya Kumar Suman
Sahitya Kumar Suman
5 years ago

Sir this is very much crucial reply me as soon as possible ………………….. my app shows white screen when ever i try to change the internet state and try to connect it again …… so please help me

Sahitya Kumar Suman
Sahitya Kumar Suman
5 years ago

:disqus

Sahitya Kumar Suman
Sahitya Kumar Suman
5 years ago

help me please

John Morocco
John Morocco
5 years ago

Improvement : AlertDialogs should be dismissed in onPause() method to avoid problems : for instance when you press home button while an AlertDialog is showing.

thebbk .
thebbk .
5 years ago

This isn’t sufficient. The device might be connected to a router via wifi that doesn’t have internet access – or the 4g connection might be having issues and getting to something over the internet won’t work. The code above will return true – simply because the device is connected to a network. It doesn’t guarantee that the device can actually access something over the internet. You need to have code that will check connectivity to a site.

Anh Nguyen
Anh Nguyen
4 years ago
Reply to  thebbk .

I’ve been ran into the same problem. How can we resolve that?

Ravi Tamada
4 years ago
Reply to  Anh Nguyen

The updated article really checks whether there is internet or not.

Anh Nguyen
Anh Nguyen
4 years ago
Reply to  Ravi Tamada

Thanks man! Keep up your excellent work ๐Ÿ™‚

Ravi Tamada
4 years ago
Reply to  Anh Nguyen

I’ll ๐Ÿ™‚

anas nain
anas nain
4 years ago
Reply to  Ravi Tamada

Hi Ravi, problem is still there when device is connected to wifi that doesn’t have internet access. For this case, it is showing “Good! Connected to internet”

Could you please help me to figure out the solution for this problem?

Wilson Jocol
Wilson Jocol
3 years ago
Reply to  anas nain

Hi, I have the same problem, can you help me!!

Janet Shikami
Janet Shikami
4 years ago

Nice application Ravi, but can we get for how long the connection has been on?

jatin
jatin
4 years ago

working as it should.
thank you

Jasson Faerron
Jasson Faerron
4 years ago

Great!!!!

Chandrahasan Subbaiyan
Chandrahasan Subbaiyan
4 years ago

Simply great! Thanks , onNetworkConnectionChanged method called Twice When Network is disconnected why?

Pat
Pat
4 years ago

Because the button makes the call to check connectivity, which updates the receiver, and the receiver also makes a call to check. If you exclude the button and just let this run in the background, it should only call once. (Correct me if I’m wrong someone)

Rahul Yadav
Rahul Yadav
4 years ago

Hii Actually I am getting null pointer exception at the following line…
ConnectivityManager cm = (ConnectivityManager) MotoMojoApp.getInstance().getApplicationContext() please help..

Ravi Tamada
4 years ago
Reply to  Rahul Yadav

Have you add MotoMojoApp in AndroidManifest.xml? (to application tag)

manjunath hiremath
manjunath hiremath
4 years ago
Reply to  Rahul Yadav

Sollution :Register your MyApplication in manifest
before:

after:

—————————–

Arunkumar Andanshetti
Arunkumar Andanshetti
3 years ago
Reply to  Rahul Yadav

Please u have to add this line manifest file

Badal Nagi
Badal Nagi
4 years ago

I have generated a value of a variable and want to send it on a pre-specified number (the number is integrated inside the source code) , i am able to send the value through the normal messaging app used in android, but i need to send the message through whatsapp.

Whatsapp should automatically get the predefined mobile number no matter it is in the contact list or not.

Your help would be of great use.

porkodi
porkodi
4 years ago

onNetworkConnectionChanged method called Thrice When Network is disconnected why? Please Help me

Breh
Breh
4 years ago

In MainActivity in onResume, when I put MyApplication.getInstance().setConnectivityListener(this); Android Studio underlines “this” in red and says … in MyApplication cannot be applied to net.myapp.MainActivity . Any idea on how to fix that? That’s my only problem so far.

SammyX
SammyX
4 years ago
Reply to  Breh

I think you forgot to, implements ConnectivityReceiver.ConnectivityReceiverListener in that Activity. ๐Ÿ™‚

manjunath hiremath
manjunath hiremath
4 years ago
Reply to  Breh

Sollution :Register your MyApplication in manifest
before:

after:

Vigraman Padmanaban
Vigraman Padmanaban
4 years ago

Thanks Ravi

Fesco
Fesco
4 years ago

Thanks. Could you show how to check real connection via ping in the same way?

Aditya
Aditya
4 years ago

How to unregistered Activity from Brod-cast receiver

$|R_MYK3
$|R_MYK3
4 years ago

how do i get this code in eclipse version am a v=fan of eclipse not in good relationship with android studion

Ravi Tamada
4 years ago
Reply to  $|R_MYK3

Even I am fan of Eclipse, but you have to move to Android Studio ASAP.

Nsamba Isaac
Nsamba Isaac
4 years ago
Reply to  Ravi Tamada

Ravi I need Help with my app Can you help i have internet issues when i run it crushes on no connection…..

Ravi Tamada
4 years ago
Reply to  Nsamba Isaac

Check the LogCat for exact error.

Nsamba Isaac
Nsamba Isaac
4 years ago
Reply to  Ravi Tamada

Thanx was able to fix it…it magicaly worked…

Ravi Tamada
4 years ago
Reply to  Nsamba Isaac

Cool

pgdroid
pgdroid
4 years ago

I like this tuts its cool so i wanna force it into my app but…
PLEASE HELP… am kinda confused caused i already have ? .AppController as my app application name
this my app Manifest..

pls how do i fix the MyApplication.class in the app name?

ip
ip
3 years ago
Reply to  pgdroid

you don’t

Alisson Cortes
Alisson Cortes
3 years ago

Hello, good application, I would like to know if there is way that you update the project to the latest version of Android Studio, because I did not open the project.

222
0
Would love your thoughts, please comment.x
()
x