Wednesday, May 6, 2015

check internet in android

Check this link:
http://www.androidhive.info/2012/07/android-detect-internet-connection-status/
 
It is the simplest and it is just a boolean. by asking if(isOnline()){
You get if there is a connection and if it can connect to a page the status code 200 (stable connection).
Make sure to add the correct INTERNET and ACCESS_NETWORK_STATE permissions.
 
public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnected()) {
        try {
            URL url = new URL("http://www.google.com");//Your site to check connection
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setConnectTimeout(3000);
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                return new Boolean(true);
            }
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return false;
 
 
 
<!-- Internet Permissions -->
    <uses-permission android:name="android.permission.INTERNET" />
 
    <!-- Network State Permissions -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 
}
 
 
 
 
 

No comments:

Post a Comment