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("your.domain.com", 80); } catch (IOException e) { throw e; } finally { if (socket != null) try { socket.close(); } 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...
No comments:
Post a Comment