Monday 7 January 2013

Check Internet connectivity in Android

hello friends here is function that check your device is corrected to internet or not


       public boolean isOnline() {
              ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
              NetworkInfo netInfo = cm.getActiveNetworkInfo();

              if (netInfo != null && netInfo.isConnectedOrConnecting()
                           && cm.getActiveNetworkInfo().isAvailable()
                           && cm.getActiveNetworkInfo().isConnected()) {
                     return true;
              }
              return false;
       }


there another method you want to use 


       public static boolean haveNetworkConnection(final Context context) {
              boolean haveConnectedWifi = false;
              boolean haveConnectedMobile = false;

              final ConnectivityManager cm = (ConnectivityManager) context
                           .getSystemService(Context.CONNECTIVITY_SERVICE);
              if (cm != null) {
                     final NetworkInfo[] netInfo = cm.getAllNetworkInfo();
                     for (final NetworkInfo netInfoCheck : netInfo) {
                           if (netInfoCheck.getTypeName().equalsIgnoreCase("WIFI")) {
                                  if (netInfoCheck.isConnected()) {
                                         haveConnectedWifi = true;
                                  }
                           }
                           if (netInfoCheck.getTypeName().equalsIgnoreCase("MOBILE")) {
                                  if (netInfoCheck.isConnected()) {
                                         haveConnectedMobile = true;
                                  }
                           }
                     }
              }

              return haveConnectedWifi || haveConnectedMobile;
       }


=============================================================


         if (haveNetworkConnection(Activity.this))
           {
                //Conneced
           }
       else
           {
                //No Connected
           }





Note:- you also give User Permission
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

2 comments: