3

I want to check that WiFi or Mobile Data Connection is(able to check) on but able to access internet or not

   public static boolean isNetworkAvailable(Context context) {
            ConnectivityManager connectivityManager
                    = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null && activeNetworkInfo.isConnected();
        }



  public static boolean isInternetAccessible(Context context) {
        if (isNetworkAvailable(context)) {
            try {
                HttpURLConnection urlc = (HttpURLConnection) (new URL("http://aapapps.com").openConnection());
                urlc.setRequestProperty("User-Agent", "Test");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(1500);
                urlc.connect();
                return (urlc.getResponseCode() == 200);
            } catch (IOException e) {
                Log.e("LOG_TAG", "Couldn't check internet connection", e);
            }
        } else {
            Log.d("LOG_TAG", "Internet not available!");
        }
        return false;
    }
Pankaj K Sharma
  • 240
  • 1
  • 12

3 Answers3

3

try its working code

public boolean isConnectingToInternet(){
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;
}
Amit Basliyal
  • 840
  • 1
  • 10
  • 28
0

check the following code and you have to add internet access permission in your manifest file. If isInternetConnectionAvailable() return true then your device can access internet otherwise it is not connect to internet.

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

public boolean isInternetConnectionAvailable() {
    ConnectivityManager connectivity = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {
        NetworkInfo networkInfo = connectivity.getActiveNetworkInfo();//active network information
        if (networkInfo != null) {
            return networkInfo.isConnected();
        }
    }
    return false;
}

if you require all network information, then use following code.

NetworkInfo[] info = connectivity.getAllNetworkInfo();
Prathap Badavath
  • 1,621
  • 2
  • 20
  • 24
0

After checking if the device is connected via WiFi or Mobile Data, why not just ping Google or any other web app which has maximum chances for being consistently available?

If you get a valid response, there is access to internet.

Gaurav Manchanda
  • 544
  • 5
  • 22