0

I'm trying to find the way to know when an user has Internet connection, since now I've got this method :

public boolean isNetworkOnline() {
    boolean status=false;
    try{
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getNetworkInfo(1);
        if (netInfo != null && netInfo.getState()==NetworkInfo.State.CONNECTED) {
            status= true;
        }
    }catch(Exception e){
        e.printStackTrace();
        return false;
    }
    return status;
}

This method returns true if user is CONNECTED but not if user has INTERNET CONNECTION, so I thought to if this method returns true, call another method to check if the user has connection to internet. For example someone can be connected to a router but without internet connection so I want to know when the user has internet connection or not.

I've read this answer and this other but all of them is returning me false when I've got Internet connection.... I thought that make a method that makes a ping to www.google.com it's a good approach to know if someone has internet connection so I tried to get this way but it didn't work for me...

Any idea or good approach (if it's better than my thoughts is better) to know when the user has internet connection?

Community
  • 1
  • 1
Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
  • possible duplicate of [Android check internet connection](http://stackoverflow.com/questions/9570237/android-check-internet-connection) –  Jul 28 '15 at 13:28

4 Answers4

3

The Simple Way To Check Internet Connectivity

public boolean isConnectingToInternet() {
        if (networkConnectivity()) {
            try {
                Process p1 = Runtime.getRuntime().exec(
                        "ping -c 1 www.google.com");
                int returnVal = p1.waitFor();
                boolean reachable = (returnVal == 0);
                if (reachable) {
                    System.out.println("Internet access");
                    return reachable;
                } else {
                    return false;
                }
            } catch (Exception e) {
                return false;
            }
        } else
            return false;

    }

    private boolean networkConnectivity() {
        ConnectivityManager cm = (ConnectivityManager) _context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isConnected();
    }

How To Call it

  if (isConnectingToInternet()) {

       // internet is connected and work properly...
    }
else {

    // something  went wrong internet not working properly...
}

So simply copy and past the above two methods where you want to check the Internet connectivity. After that check the condition if (isConnectingToInternet()) { }

Pierre.Vriens
  • 2,117
  • 75
  • 29
  • 42
Mushtaq Rahim
  • 129
  • 1
  • 13
2

Can you try this method?

public boolean checkInternectConnection() {
        try {
            InetAddress inAddress= InetAddress.getByName("http://google.com");
            if (inAddress.equals("")) {
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
    }
Aruna Tebel
  • 1,436
  • 1
  • 12
  • 24
  • Let me check... hold on – Skizo-ozᴉʞS ツ Jul 28 '15 at 14:12
  • Shall I put this method on a Thread? Cause it doesn't give time to return true or not.... how should I do this? – Skizo-ozᴉʞS ツ Jul 28 '15 at 14:18
  • 1
    Yes, better if you can use `AsyncTask` to perform this check. Because `NetworkOnMainThreadException` will occur if you try to do it inside your main activity thread. You can refer to [here](http://stackoverflow.com/questions/10662805/inetaddress-in-android) for information about doing it. – Aruna Tebel Jul 28 '15 at 14:28
  • This solution yields UnknownHostException: Unable to resolve host "http://google.com": No address associated with hostname for me – matdev Jun 12 '19 at 09:50
1

Please check this answer out and see if its helpful or not

You can try out this code

try {
    URL url = new URL("http://"+params[0]);

    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
    urlc.setRequestProperty("User-Agent", "Android Application:"+Z.APP_VERSION);
    urlc.setRequestProperty("Connection", "close");
    urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds
    urlc.connect();

    if (urlc.getResponseCode() == 200) {
        Main.Log("getResponseCode == 200");
        return new Boolean(true);
    }
} catch (MalformedURLException e1) {
    e1.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
Community
  • 1
  • 1
1

this is how i fixed this and i use it as a Utility method which can be called from any activity/fragment etc...:

public static boolean isNetworkAvailable(Context context) {
            ConnectivityManager connectivityManager
                    = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null && activeNetworkInfo.isConnected();
        }//check if Wifi or Mobile data is enabled


private static class NetworkAsync extends AsyncTask<Void, Void, Boolean> {
    @Override
    protected Boolean doInBackground(Void... voids) {
        try {
            HttpURLConnection urlConnection = (HttpURLConnection)
                    (new URL("http://clients3.google.com/generate_204")
                            .openConnection());
            urlConnection.setRequestProperty("User-Agent", "Android");
            urlConnection.setRequestProperty("Connection", "close");
            urlConnection.setConnectTimeout(1500);
            urlConnection.connect();
            return (urlConnection.getResponseCode() == 204 &&
                    urlConnection.getContentLength() == 0);
        } catch (IOException e) {
            // Error checking internet connection
        }
        return false;
    }
}//network calls shouldn't be called from main thread otherwise it will throw //NetworkOnMainThreadException

and now you simply need to call this method from anywhere you want:

public static boolean checkInternetConnection(Context context) {
        if (isNetworkAvailable(context)) {
            try {
                //used execute().get(); so that it gets awaited and returns the result 
                //after i receive a response
                return new NetworkAsync().execute().get();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
Bilal Awwad
  • 114
  • 6