Error in NetworkInfo [duplicate]

1

I have the following problem, I have a method that verifies whether the device is connected to the internet or not

public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

    assert cm != null;
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting() && activeNetwork.getState() ==  NetworkInfo.State.CONNECTED;
    return  isConnected;
}

Only, when I am connected to a wifi, where it does not have internet, it returns true. That is, the method returns true if there is a connection and not specifically with the internet. Has anyone gone through this?

    
asked by anonymous 03.04.2018 / 19:49

1 answer

1

ConnectivityManager can not really verify your internet connection. The simplest solution is to ping some URLs.

Based in this solution you can check your internet connection by pinging Google DNS as follows:

public boolean isInternetAvailable(int timeoutMs) {
    Socket sock = new Socket();
    try {

      SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);
      sock.connect(sockaddr, timeoutMs); // This will block no more than timeoutMs

      return true;
    } catch (IOException e) {
      return false; 
    }finally{
      sock.close();
    }
}
    
03.04.2018 / 20:57