HOW TO CHECK INTERNET CONNECTION IN ANDROID PROGRAMMATICALLY

Sabin Khanal
2 min readFeb 3, 2019

Nowadays internet is the backbone of almost all mobile applications. Internet connectivity is essential for some of the common functionalities in Android such as geo-location, update, resource synchronization, and content sharing. Checking for internet connectivity in android could be challenging for beginners. The purpose of this article is to provide you a reusable solution for checking internet connectivity in android.2 different implementation was provided here based on INetAddress and Socket API.

  • Create CheckOnlineStatus class which extends AsyncTask.
public class CheckOnlineStatus extends AsyncTask {2
@Override
protected Boolean doInBackground(Void... params) {
//This is a background thread, when it finishes executing will return the result from your function.
Boolean _online= isOnline();//
return _online;
}
protected void onPostExecute(Boolean result) {
//Here you will receive your result from doInBackground
//This is on the UI Thread
}
}
  • Create another static method that implements internet connection checking.
public static boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com.np");
if (ipAddr.equals("")) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
}

or you can use the implementation using Socket.

public static boolean isOnline() {
try {
int timeoutMs = 1500;
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);
sock.connect(sockaddr, timeoutMs);
sock.close();
return true;
} catch (IOException e) {
return false;
}
}

Now use the AsyncTask as,

Boolean isOnline=new CheckOnlineStatus().exec();
if(isOnline)
{
//yes connected
}
else
{
//not connected
}

Thanks for reading this article. Please don't forgot to add your comments below.

--

--