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
Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • Ashish Mishra

    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

    thanks

  • neel

    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

      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

    thanks, this tutorial is very helpful…

  • Meghna

    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

    very helpful, thanks

  • padi

    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

  • Naresh Sharma

    Very nice and Simple tutorial. Thanks

  • Thet Paing

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

  • Trollzito

    ok men!! ok excelent! yeah

    • BruStack

      nice english, hihi

  • rajesh

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

  • Apex

    Excellent tutorial…Thanks ravi..

  • Mohd

    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

    Thanks!

  • B. Clay Shannon

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

  • A

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

  • James Carter

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

  • Rafael Ruiz

    Great!

  • Mayur

    nice

  • Edgar

    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

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

  • Runesh

    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

    Thanks a lot ..

  • AyaM Sakata

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

  • prasad Vdv

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

  • Theo Viset

    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

    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Γͺ

    tutorial is very good. Thank for share.

  • Allay Khalil

    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

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

  • terGmas

    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

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

  • Sahitya Kumar Suman

    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

    @ravi8x:disqus

    • Sahitya Kumar Suman

      help me please

  • John Morocco

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

  • thebbk .

    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

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

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

        • Anh Nguyen

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

        • anas nain

          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

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

  • Janet Shikami

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

  • jatin

    working as it should.
    thank you

  • Jasson Faerron

    Great!!!!

  • Chandrahasan Subbaiyan

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

    • Pat

      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

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

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

    • manjunath hiremath

      Sollution :Register your MyApplication in manifest
      before:

      after:

      —————————–

    • Arunkumar Andanshetti

      Please u have to add this line manifest file

  • Badal Nagi

    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

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

  • Breh

    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

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

    • manjunath hiremath

      Sollution :Register your MyApplication in manifest
      before:

      after:

  • Vigraman Padmanaban

    Thanks Ravi

  • Fesco

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

  • Aditya

    How to unregistered Activity from Brod-cast receiver

  • $|R_MYK3

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

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

      • Nsamba Isaac

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

        • Check the LogCat for exact error.

          • Nsamba Isaac

            Thanx was able to fix it…it magicaly worked…

          • Cool

  • pgdroid

    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

      you don’t

  • Alisson Cortes

    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.

  • Simon Bostock

    Thanks, this tutorial was perfect, just what I needed, once I’d read it properly and added MyApplication to the manifest.

  • Mounika

    How can i get a code for download and upload Internet speed for a particular mobile?

  • Amin Najafi

    How do I display a certain activity when the Internet was cut off?

    • Launch the activity in onNetworkConnectionChanged() depending on status.

      • Amin Najafi

        please help me sample code

        • Fakher Hakim

          Just add an intent to the desired activity in the implementation of the onNetworkConnectionChanged() method.

  • Udit Varshney

    How can I unregistered the connectivity status listener

  • Afiq Angel

    is deprecated. Can you show tutorial on latest way?

  • aditya mahajan

    n how to check weather the wifi connection is limited. how to check that status please rply?

  • George Franklin

    This does NOT tell you if you are connected to the INTERNET! It tells you if you are connected to a network. You can connect to a wifi, or other, network that does not have internet connectivity and it will still say you are connected. You should revise your header to reflect the true nature of this receiver.

  • Shubhansh Jaiswal

    i have a lot many activities, is there a way to check connection from all activities just when the application starts until it is closed. Maybe only from the main activity or if we could override the base class. can we? if yes how?

    I dont want to repeat those 3 steps again and again…

    • ȜAmer Elsayed

      you can make parent Activity and inerit from it
      make it contain all things that are comon between all activities

  • Himanshu Dubey

    hello ravi i am using your tutorial but i have face one problem . first time is working good but now i am off wifi then not open snackbar plese help me.

  • Aswin P Ashok

    Working like a charm upto android M, but not on android N. Broadcast receiver is not getting fired. Is there a way i can check internet connection even when my application is not active?

    • I’ll check in N.

    • Daan Dawud

      I think you need to use JobScheduler for Nougat

  • Alejandro Solis

    How can I do that, but in fragments? :/

  • jeeva

    Dear Ravi,

    Is it possible to check the internet connection, while exit the application(after destroy the app) ?

  • Zohaib Arshad

    It Says Good Connected to internet when there is no actual internet access such when connected to a hotspot who has no internet access

  • Mallika

    How to check Internet connectivity in android continuously for every 5 sec. without crash/hang an app?

  • abdullah

    Not working Android N or higher. Because, CONNECTIVITY_CHANGE depreciated use JobScheduler or GCMNetworkManager

  • Ziigic

    Hello Sir Ravi,
    I wanna ask, the better way to check internet connection on our application we must implements ConnectivityReceiver.ConnectivityReceiverListener in every activity ? or any other better and good solutions ?

    Best Regards,
    Ziigic

    • Swastik Devs

      just make a listener class and use instance of it wherever u want

  • kavie

    Hi,
    If i switch off and On WiFi,it is not working in Android N.Please update the code for latest version of android.

  • Hari Babu Koduri

    MyApplication.getInstance() methosd is given me null value. can you please help me with that

    • Muthu S

      If your mobile is in flight mode it returns null..Please check that too

  • prasanth s

    Hi Ravi,
    I have implemented on main activity so when onresume called it will throw two times. one for activity and another for fragment life cycle. How can we implement only one time. snackbar appeared2 times for open and close.

  • Zeeshan Ahmad

    Hi Ravi ,
    This code does not work for android 25 can you please check ?

  • Karan galgat

    please update the code…

  • Achal Badgujar

    ravi please update this tutorial for android N plzzzzz

    • Piyush Agrawal

      Ravi yes please update the tutorial so it will help more

  • Igor Skryl

    From Documentation:

    **Apps targeting Android 7.0 (API level 24) and higher do not receive CONNECTIVITY_ACTION broadcasts if they declare the broadcast receiver in their manifest. Apps will still receive CONNECTIVITY_ACTION broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid.**

    – > Register your broadcast in the activity

  • Antonio Rosario

    This is the code you want in you’re onCreate of your fragment or activity

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    context.registerReceiver(new ConnectivityReceiver(),
    new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }

  • Kaseem Khan

    i want’s to when our app is not runable and also not in the background then app check internet connection and show toast msg can you create that type code.

  • Sahil Malhotra

    Sir really nice tutorial
    learnt a new thing
    Wanted to know that how can we detect the speed of the internet connection?
    Like if the speed is slow we can do modifications in our network hits.
    Do respond
    Thanks πŸ™‚

  • Deepak Kapoor

    How to show no internet connection dialog on webview or show a offline page in a webview app when there is no internet connection. Please tell me a simple and good solution for my problem

  • Tiara Gizka Septi

    thank you for your helpful article…

  • Sushil Kumar

    It is not useful with the slow internet. Application is crashing again and again.

  • Suresh Parmar

    Hi Ravi,
    It isn’t working with Nougat. Can you suggest me solution?