According to @Levit, there are two ways to test your network connection / Internet access.
- Ping 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 (optional)
// 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; } }
The second method is very fast (in any case), works on all devices, very reliable. But it cannot work in the user interface thread.
Details here
source share