Mobile Café #002 — Android: How to check internet connection

Robson Ribeiro
2 min readApr 2, 2018

--

Android Sip #002

Hello guys! Today I’m going to show you how to check internet connection by pinging a website. It is important to mention that this method is good because sometimes you actually do have a NETWORK connection, but not an INTERNET connection, like when you are at Starbucks and have no code to use their wifi. That being said, get your poison and come along!

1- Paste the following code in your Activity:

public boolean isConnected() throws InterruptedException, IOException {String command = "ping -c 1 google.com";return (Runtime.getRuntime().exec (command).waitFor() == 0);}

The chunk of code above executes a command to ping Google’s website. Of course you get false to your internet connection if Google is down, but we don’t REALLY believe they’ll be down right? Alternatively, you can ping your own domain or the API you get your data from.

2- Paste the code below within any method from your Activity where you want to check the connection:

try {if(isConnected()){//YEY! There is internet connection!}else{//No internet connection, deal with it.}} catch (InterruptedException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}

And that’s all! Of course I mentioned an Activity but the place where you are going to use it is actually up to you!

Thanks for reading, see you next coffee break!

--

--