Check your internet connection - Android

I know that this question has been asked a couple of times, for example here and here , but I still do not get the desired results, doing something similar to this when checking the network connection

The isAvailable () and isConnected () methods from Network Info give the result of a logical truth when I am connected to a Wi-Fi router that currently does not have an Internet connection.

Here is a screenshot of my phone that can detect the situation in my hand. My phone dose detects this possibility and shows a warning for this

The only way to make sure that the phone / application is really connected to the Internet is to poll / ping the resource to check connectivity or to handle the exception when trying to make a request?

+6
source share
1 answer

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

0
source

Source: https://habr.com/ru/post/1239242/


All Articles