Sunday, July 28, 2013

Check if the device has Internet

On many platform, and specifically on mobile devices, there is a constant need to know if there is a connection to the internet (or the outer world).

I've seen countless Android implementations, trying to figure and configure the network states, attempting to understand if the underline network can access the outer world or not, I've also wrote one... :(

Thing about all these implementations, they all fail the scenario where the device is connected to a network, which is not connected to the outer world, for example a router which is not connected to the wall...

Today, I bring you a very simple very easy way to perform this check:

private void checkWebConnectiity()
  throws IOException {
 Socket socket = null;
 try {
  socket = new Socket("", 80);
 } catch (IOException e) {
  throw e;
 } finally {
  if (socket != null)
   try {
   } catch (IOException e) {
    logWarning("Ignoring...", e);

This covers most of the cases you would need, and is an absolute check, to whether or not you have access to the internet.

You can also return a boolean for your satisfaction, I required an exception to determine the cause of error...