I know this question has been asked a couple of times, example here and here but I`m still not getting the desired results by doing something similar to this when checking for network connectivity
The isAvailable() and isConnected() methods from Network Info both give a result of boolean true when i`m connected to a Wi-Fi router which currently has no internet connectivity .
Here is a screenshot of my phone which can detect the situation in hand.
Is the only way to make sure that the phone/application is actually connected to the internet is actually poll/ping a resource to check for connectivity or handle an exception when trying to make a request?
As stated by @Levit, Showing two way of checking Network connection / Internet access
-- Ping a Server
// ICMP
public boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
}
catch (IOException e) { e.printStackTrace(); }
catch (InterruptedException e) { e.printStackTrace(); }
return false;
}
-- Connect to a Socket on the Internet (advanced)
// TCP/HTTP/DNS (depending on the port, 53=DNS, 80=HTTP, etc.)
public boolean isOnline() {
try {
int timeoutMs = 1500;
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);
sock.connect(sockaddr, timeoutMs);
sock.close();
return true;
} catch (IOException e) { return false; }
}
second method very fast (either way), works on all devices, very reliable. But can't run on the UI thread.
Details here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With