I am trying to write a part in my app that will differentiate between an Active Wifi connection and an actual connection to the internet. Finding out if there is an active Wifi connection is pretty simple using the connection manager however every time I try to test if I can connect to a website when the Wifi is connected but there is no internet connection I end up in an infinite loop.
I have tried to ping google however this ends up the same way:
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = 5;
try {
returnVal = p1.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean reachable = (returnVal==0);
return reachable;
I also tried this code:
if (InetAddress.getByName("www.xy.com").isReachable(timeout))
{ }
else
{ }
but I could not get isReachable to work.
Here is some modern code that uses an
AsynTask
to get around an issue where android crashes when you try and connect on the main thread and introduces an alert with a rinse and repeat option for the user....
I did use this method. It worked for me! For people who want to get the real Internet!
For doing this method every time! Just use a receiver and
=>
This means the Internet is connected!
Query a website like this:
Make your class implement
AsyncTaskCompleteListenere<Boolean>
by adding the following method to your class:Add a simple
testConnection
method to your class to be called when you want to check for your connectivity:And finally the
URLExistAsyncTask
class which perform the connectivity test as an asynchronous (background) task and calls back youronTaskComplete
method once done:It does works for me:
To verify network availability:
To verify internet access:
I use this:
It comes from an other stackoverflow answer but I can't find it.
EDIT:
Finally I found it: https://stackoverflow.com/a/1565243/2198638
To check if the android device is having an active connection, I use this hasActiveInternetConnection() method below that (1) tries to detect if network is available and (2) then connect to google.com to determine whether the network is active.