Check WiFi and mobile data is active or not

1.1k views Asked by At

In a android studio project I want to check active internet, for that I use this class. Its working but. problem is it only work when connection not available. But i want only return true when connection is active and workable. Because the app working with webview, and if connection is week or not active then its showing not reachable error. Its happening most with WiFi. Please help

public boolean isConnected(Context context) {

  ConnectivityManager cm = (ConnectivityManager) 
  context.getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo netinfo = cm.getActiveNetworkInfo();

  if (netinfo != null && netinfo.isConnectedOrConnecting()) {
  android.net.NetworkInfo wifi = 
  cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  android.net.NetworkInfo mobile = 
  cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

  if((mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && 
  wifi.isConnectedOrConnecting()))
  {
    return true;
  }
  else {
    return false;
  }
  } else{
   return false;
  }
}
1

There are 1 answers

3
Pier Giorgio Misley On

This is what I am using in my working code:

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

Remember to add in your manifest the network state permission

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

and, if you need to use internet in your application, consider adding also this:

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

you can also refer to this link for the official documentation about network permissions hope this helps