0

In my android app, I would like to test if a user can access the internet. I know I able to test if he is connected to wifi or 3G/4G, etc... but maybe the user is connected to a local network and doesn't have access to the internet.

Should I try a "ping" to google to be sure that he can download anything or does it exist a function which ensure the phone has internet ?

Thanks.

psv
  • 2,789
  • 4
  • 27
  • 56

2 Answers2

0

If you want to check whether the user has access to internet while s/he has connection, try to reach a web site like google with some timeout.

    URL url = new URL("https://google.com");

    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
    urlc.setRequestProperty("Connection", "close");
    urlc.setConnectTimeout(1000 * 30);
    urlc.connect();
    if (urlc.getResponseCode() == 200) {
        return true;
    }

If you get timeout or an error code, you can assume your app is not connected to internet.

furkan3ayraktar
  • 533
  • 8
  • 17
0
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager 
      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();

}

AndroidManifest :

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

But it's already been answered here :

Here

Community
  • 1
  • 1
Tsunaze
  • 3,048
  • 7
  • 41
  • 80
  • See http://stackoverflow.com/questions/12442893/android-networkinfo-always-returns-true-even-if-internet-is-not-available. isConnected() return true even if the user is connected to a local network only. This is the problem I wanna avoid. – psv Oct 20 '14 at 09:42