Tuesday, August 4, 2015

[Android] Check Internet Connection

Below code checks Internet connection in an Android device. This is helpful when you want to ensure the Internet connection is available before sending any request to server, e.g. Web server to call Servlet or HTML page.


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;


final public class InternetConnectionChecker {


    public static boolean isOnline(Context c) {
        ConnectivityManager cm =  (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            Log.i(InternetConnectionChecker.class.getName(),">>Connected to network." + netInfo.isConnectedOrConnecting());
            return true;
        }
        else        {
            Log.i(InternetConnectionChecker.class.getName(),">> Not connected to network.");
            return false;
        }
    }//end method

}//end class



Add below lines to AndroidManifest.xml.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

No comments:

Post a Comment