You can do something like this
InternetChecker.canReachServer(URL_SERVER, 10000, 10000, reachable -> {
if(reachable){
//connected
}
else{
//no connected
}
});
public class InternetChecker {
public static void canReachServer(String Url, int dnsTimeout, int requestTimeout, Callback<Boolean> result) {
httpThread.run(() -> {
InetAddress ip = ResolveHost(Url, dnsTimeout);
if (ip == null) {
Log.d("INTERNET STEP 1", "FAILED");
result.callback(false);
} else {
Log.d("INTERNET STEP 1", "SUCCESS: " + ip.getHostAddress());
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(requestTimeout, TimeUnit.MILLISECONDS)
.writeTimeout(requestTimeout, TimeUnit.MILLISECONDS)
.readTimeout(requestTimeout, TimeUnit.MILLISECONDS)
.build();
Request request = new Request.Builder()
.url(Url)
.head()
.build();
try {
client.newCall(request).execute();
} catch (IOException e) {
Log.d("INTERNET STEP 2", "FAILED: " + e.getMessage());
result.callback(false);
return;
}
Log.d("INTERNET STEP 2", "SUCCESS");
result.callback(true);
}
});
}
public static InetAddress ResolveHost(String sUrl, int timeout) {
//Run the DNS resolve method manually to be able to time it out.
URL url;
try {
url = new URL(sUrl);
} catch (MalformedURLException e) {
return null;
}
//Resolve the host IP
DNSResolver dnsRes = new DNSResolver(url.getHost());
Thread t = new Thread(dnsRes);
t.start();
try {
t.join((long) (timeout));
} catch (InterruptedException e) {
//DNS interrupted
return null;
}
InetAddress inetAddr = dnsRes.get();
if (inetAddr == null) {
//DNS timed out.
return null;
}
//DNS resolved.
return dnsRes.inetAddr;
}
public static class DNSResolver implements Runnable {
private String domain;
private InetAddress inetAddr;
public DNSResolver(String domain) {
this.domain = domain;
}
public void run() {
try {
InetAddress addr = InetAddress.getByName(domain);
set(addr);
} catch (UnknownHostException e) {
}
}
public synchronized void set(InetAddress inetAddr) {
this.inetAddr = inetAddr;
}
public synchronized InetAddress get() {
return inetAddr;
}
}
}