Thursday, 2 May 2013

Check Internet Connection in Android


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 is another method for Internet connection

   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;
       }

Call Method


if (haveNetworkConnection(context.this))
       {
              //Connection available....
       }
       else
       {
              //No Connection available....
       }

Permission:

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

No comments:

Post a Comment