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:
  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
 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.
 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 

7 comments:

  1. This actually doesn't check if device is really connected to internet but just checks if it is connected to a network. To check internet connection, look into my answer here:
    http://stackoverflow.com/questions/9570237/android-check-internet-connection/9570292#9570292

    ReplyDelete
  2. Thank You !! Awesome Blog.
    Great knowledge with good concept about Android Development.
    Keep sharing your knowledge with us.
    Android Interview Questions
    Android Tutorial
    Android Training in Noida

    ReplyDelete
  3. It's really useful for the network connectivity. Security Solutions

    ReplyDelete

Debug Database in Android

In my last tutorial, we have learned how we can use persistence database in android. We also understood which database wrapper we can use...

Contact Me

Name

Email *

Message *