HOW TO CHECK INTERNET CONNECTION IN ANDROID PROGRAMMATICALLY

HOW TO CHECK INTERNET CONNECTION IN ANDROID PROGRAMMATICALLY

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 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 the another static method which 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 do’not forgot to add your comments below.

One Reply to “HOW TO CHECK INTERNET CONNECTION IN ANDROID PROGRAMMATICALLY”

Leave a Reply

Your email address will not be published. Required fields are marked *