Rectangle 27 1

networking Android check internet connection?


<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
private boolean isNetworkConnected() {
  ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

  return cm.getActiveNetworkInfo() != null;
 }
public boolean isInternetAvailable() {
        try {
            InetAddress ipAddr = InetAddress.getByName("google.com"); //You can replace it with your name
            return !ipAddr.equals("");

        } catch (Exception e) {
            return false;
        }

    }

Edit: This method actually checks if device is connected to internet(There is a possibility it's connected to a network but not to internet).

The first part works in the main thread, the second part (the edit) only works if not on the main thread.

This answer is incorrect. If you're connected to a network that does not route to the internet this method will incorrectly return true. Note that getActiveNetworkInfo's javadoc says you should check NetworkInfo.isConnected(), but that is also not sufficient to check that you're on the internet. I'm looking into it further but you might have to ping a server on the internet to make sure you're actually on the internet.

be wary of isInternetAvailable() as it can fail on "network on main thread" exceptions and thus return false even when you have a connection.

in manifest,

isInternetAvailable() always return false for me. Even when bypassing the catch. I'm on 3G.

this method checks whether mobile is connected to internet and returns true if connected:

Note
Rectangle 27 1

networking Android check internet connection?


<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
private boolean isNetworkConnected() {
  ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

  return cm.getActiveNetworkInfo() != null;
 }
public boolean isInternetAvailable() {
        try {
            InetAddress ipAddr = InetAddress.getByName("google.com"); //You can replace it with your name
            return !ipAddr.equals("");

        } catch (Exception e) {
            return false;
        }

    }

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Edit: This method actually checks if device is connected to internet(There is a possibility it's connected to a network but not to internet).

The first part works in the main thread, the second part (the edit) only works if not on the main thread.

This answer is incorrect. If you're connected to a network that does not route to the internet this method will incorrectly return true. Note that getActiveNetworkInfo's javadoc says you should check NetworkInfo.isConnected(), but that is also not sufficient to check that you're on the internet. I'm looking into it further but you might have to ping a server on the internet to make sure you're actually on the internet.

be wary of isInternetAvailable() as it can fail on "network on main thread" exceptions and thus return false even when you have a connection.

in manifest,

isInternetAvailable() always return false for me. Even when bypassing the catch. I'm on 3G.

this method checks whether mobile is connected to internet and returns true if connected:

Note
Rectangle 27 1

networking Android check internet connection?


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

I think it's the smartest solution

If your app relys on a remote server (for authentication, fetching data, communication with database.... etc) then you can use that server address instead of google, this way you can check for internet connectivity and the server availability at the same time. If your server is down and there is still an internet connection the app wont function properly anyways. In this case you might also want to set timeout interval for ping command using -i option like this ping -i 5 -c 1 www.myserver.com.

Well @ZeeshanShabbir is right , a solar flare to the part of the country of google's main operation would take your application right out of the ball park , in such a scenario you could propably ping to a few addresses to check the same . Also , i think google wont be down if one center is down , a majority of them must be taken down for this to work also provided that your network operator survives the worldwide blackout :D

You can simply ping an online website like google:

Note
Rectangle 27 1

networking Android check internet connection?


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

I think it's the smartest solution

If your app relys on a remote server (for authentication, fetching data, communication with database.... etc) then you can use that server address instead of google, this way you can check for internet connectivity and the server availability at the same time. If your server is down and there is still an internet connection the app wont function properly anyways. In this case you might also want to set timeout interval for ping command using -i option like this ping -i 5 -c 1 www.myserver.com.

Well @ZeeshanShabbir is right , a solar flare to the part of the country of google's main operation would take your application right out of the ball park , in such a scenario you could propably ping to a few addresses to check the same . Also , i think google wont be down if one center is down , a majority of them must be taken down for this to work also provided that your network operator survives the worldwide blackout :D

You can simply ping an online website like google:

Note
Rectangle 27 1

networking Android check internet connection?


private boolean internetConnectionAvailable(int timeOut) {
    InetAddress inetAddress = null;
    try {
        Future<InetAddress> future = Executors.newSingleThreadExecutor().submit(new Callable<InetAddress>() {
            @Override
            public InetAddress call() {
                try {
                    return InetAddress.getByName("google.com");
                } catch (UnknownHostException e) {
                    return null;
                }
            }
        });
        inetAddress = future.get(timeOut, TimeUnit.MILLISECONDS);
        future.cancel(true);
    } catch (InterruptedException e) {
    } catch (ExecutionException e) {
    } catch (TimeoutException e) {
    } 
    return inetAddress!=null && !inetAddress.equals("");
}

The accepted answer's EDIT shows how to check if something on the internet can be reached. I had to wait too long for an answer when this was not the case (with a wifi that does NOT have an internet connection). Unfortunately InetAddress.getByName does not have a timeout parameter, so the next code works around that:

Note
Rectangle 27 1

networking Android check internet connection?


new CheckNetworkConnection(this, new CheckNetworkConnection.OnConnectionCallback() {

            @Override
            public void onConnectionSuccess() {
   Toast.makeText(context, "onSuccess()", toast.LENGTH_SHORT).show();
            }

            @Override
            public void onConnectionFail(String msg) {
   Toast.makeText(context, "onFail()", toast.LENGTH_SHORT).show();
            }
        }).execute();
class NetWorkInfoUtility {

public boolean isWifiEnable() {
    return isWifiEnable;
}

public void setIsWifiEnable(boolean isWifiEnable) {
    this.isWifiEnable = isWifiEnable;
}

public boolean isMobileNetworkAvailable() {
    return isMobileNetworkAvailable;
}

public void setIsMobileNetworkAvailable(boolean isMobileNetworkAvailable) {
    this.isMobileNetworkAvailable = isMobileNetworkAvailable;
}

private boolean isWifiEnable = false;
private boolean isMobileNetworkAvailable = false;

public boolean isNetWorkAvailableNow(Context context) {
    boolean isNetworkAvailable = false;

    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    setIsWifiEnable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected());
    setIsMobileNetworkAvailable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected());

    if (isWifiEnable() || isMobileNetworkAvailable()) {
        /*Sometime wifi is connected but service provider never connected to internet
        so cross check one more time*/
        if (isOnline())
            isNetworkAvailable = true;
    }

    return isNetworkAvailable;
}

public boolean isOnline() {
    /*Just to check Time delay*/
    long t = Calendar.getInstance().getTimeInMillis();

    Runtime runtime = Runtime.getRuntime();
    try {
        /*Pinging to Google server*/
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        long t2 = Calendar.getInstance().getTimeInMillis();
        Log.i("NetWork check Time", (t2 - t) + "");
    }
    return false;
 }
}
public class CheckNetworkConnection extends AsyncTask<Void, Void, Boolean> {
private OnConnectionCallback onConnectionCallback;
private Context context;

public CheckNetworkConnection(Context con, OnConnectionCallback onConnectionCallback) {
     super();
     this.onConnectionCallback = onConnectionCallback;
    this.context = con;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected Boolean doInBackground(Void... params) {
    if (context == null)
        return false;

    boolean isConnected = new NetWorkInfoUtility().isNetWorkAvailableNow(context);
    return isConnected;
}

@Override
protected void onPostExecute(Boolean b) {
    super.onPostExecute(b);

    if (b) {
        onConnectionCallback.onConnectionSuccess();
    } else {
        String msg = "No Internet Connection";
        if (context == null)
            msg = "Context is null";
        onConnectionCallback.onConnectionFail(msg);
    }

}

public interface OnConnectionCallback {
    void onConnectionSuccess();

    void onConnectionFail(String errorMsg);
}
}

All official methods only tells weather device is open for network or not, If your device is connected to Wifi but Wifi is not connected to internet then these method will fail (Which happen many time), No inbuilt netwrok detection method will tell about this scenario, so created Async Callback class which will return in onConnectionSuccess and onConnectionFail

Note
Rectangle 27 1

networking Android check internet connection?


public static boolean isConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager)context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
        try {
            URL url = new URL("http://www.google.com/");
            HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
            urlc.setRequestProperty("User-Agent", "test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1000); // mTimeout is in seconds
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            Log.i("warning", "Error checking internet connection", e);
            return false;
        }
    }

    return false;

}

And also do not put this method inside onCreate or any other method. Put it inside a class and access it.

Please use this in a separate thread from the main thread as it makes a network call and will throw NetwrokOnMainThreadException if not followed.

The above methods work when you are connected to a Wi-Fi source or via cell phone data packs. But in case of Wi-Fi connection there are cases when you are further asked to Sign-In like in Cafe. So in that case your application will fail as you are connected to Wi-Fi source but not with the Internet.

This is a good approach to the problem. But probably a ping is enough

Note
Rectangle 27 1

networking Android check internet connection?


private boolean internetConnectionAvailable(int timeOut) {
    InetAddress inetAddress = null;
    try {
        Future<InetAddress> future = Executors.newSingleThreadExecutor().submit(new Callable<InetAddress>() {
            @Override
            public InetAddress call() {
                try {
                    return InetAddress.getByName("google.com");
                } catch (UnknownHostException e) {
                    return null;
                }
            }
        });
        inetAddress = future.get(timeOut, TimeUnit.MILLISECONDS);
        future.cancel(true);
    } catch (InterruptedException e) {
    } catch (ExecutionException e) {
    } catch (TimeoutException e) {
    } 
    return inetAddress!=null && !inetAddress.equals("");
}

The accepted answer's EDIT shows how to check if something on the internet can be reached. I had to wait too long for an answer when this was not the case (with a wifi that does NOT have an internet connection). Unfortunately InetAddress.getByName does not have a timeout parameter, so the next code works around that:

Note
Rectangle 27 1

networking Android check internet connection?


I had issues with the IsInternetAvailable answer not testing for cellular networks, rather only if wifi was connected. This answer works for both wifi and mobile data:

Note
Rectangle 27 1

networking Android check internet connection?


<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
public boolean isInternetAvailable() {
    try {
        final InetAddress address = InetAddress.getByName("www.google.com");
        return !address.equals("");
    } catch (UnknownHostException e) {
        // Log error
    }
    return false;
}
public boolean isNetworkAvailable(Context context) {
    final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
    return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}

@Jared you ruined introducing the hell context

How is this different from the accepted answer?

How to find, connected to wifi but not actually active data on wifi.

Only tells you if you are connect to a network, and not the internet. If you want crashes (for internet safe code) then use this.

Note