Check Network Connectivity


I am sharing the code for check the internet connectivity of your device either mobile or wifi connectivity.
More detail Here 
Java Code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private void checkNetworkConnection() {
    ConnectivityManager connMgr =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
    if (activeInfo != null && activeInfo.isConnected()) {
        wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
        mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
        if(wifiConnected) {
            Log.i(TAG, "WIFI connected");
        } else if (mobileConnected){
            Log.i(TAG, "Mobile Connected");
        }
    } else {
        Log.i(TAG,"Neither Mobile nor WIFi connected.");
    }
  }
or second way
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static boolean isInternetOn(Context context) {
 ConnectivityManager cm = (ConnectivityManager) context
   .getSystemService(Context.CONNECTIVITY_SERVICE);
 // test for connection
 if (cm.getActiveNetworkInfo() != null
   && cm.getActiveNetworkInfo().isAvailable()
   && cm.getActiveNetworkInfo().isConnected()) {
  Log.v("Util", "Internet is working");
  // txt_status.setText("Internet is working");
  return true;
 } else {
  // txt_status.setText("Internet Connection Not Present");
  Log.v("Util", "Internet Connection Not Present");
  return false;
 }
}
Please do not forget to add the permission in AndroidMenifest file.
?
1
2
3
4
<uses-permission android:name="android.permission.INTERNET">
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE">
  
</uses-permission></uses-permission>

Comments

Popular posts from this blog