-5

What are the ways to check your Internet connection in Android.

And what is the difference between them?

TheCodeArtist
  • 21,479
  • 4
  • 69
  • 130

1 Answers1

1

Create method like below.

public static boolean isConnectingToInternet(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }

        }
        return false;
    }

and call it wherever you want. Put it in IF - ELSE condition so you can check for connection.

Or if you want to call this method through out your project then you can create one static class like below.

public class ConnectivityDetector {

    public static boolean isConnectingToInternet(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }

        }
        return false;
    }
}

and call it like below shown code in every class wherever you want.

if (ConnectivityDetector.isConnectingToInternet(Test.this)) {
         // do your stuff
} else {
         // Alert dialog that says, No Internet connection 
}

Also make sure that you have the required permission to monitor the network state. You need to add this permission to your AndroidManifest.xml:

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

Hope this will help you.

InnocentKiller
  • 5,234
  • 7
  • 36
  • 84