Error in Networkinfo

Asked

Viewed 22 times

1

I have the following problem, I have a method that checks 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 has no internet, it returns true. That is, the method returns true if there is a connection and not specifically with the internet. Someone has already been there?

1 answer

1


Connectivitymanager really can’t check the internet connection. The simplest solution is to ping some URL.

Based in this solution you can check the internet connection by ping Google’s 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();
    }
}
  • I had seen this solution, only it does not work for older devices, but even for my reality works very well.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.