How to programmatically check availibilty of inter

2019-01-17 15:57发布

问题:

I want to check programmatically whether there is an internet connection in Android phone/emulator. So that once I am sure that an internet connection is present then I'll make a call to the internet.

So its like "Hey emulator! If you have an internet connection, then please open this page, else doSomeThingElse();"

回答1:

The method I implemented for myself:

/*
 * isOnline - Check if there is a NetworkConnection
 * @return boolean
 */
protected boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnected()) {
        return true;
    } else {
        return false;
    }
}

Be aware of that this is a NetworkConnection-Check. If there is a NetworkConnection it doesn't have to be a InternetConnection.



回答2:

Being connected to a network does not guarantee internet connectivity.

You might be connected to your home's wifi, but you might not have internet connection. Or, you might be in a restaurant, where you can be connected to the wifi, but still need password for the hotspot in order to use the internet. In such cases the above methods will return true, yet the device wont have internet, and if not surrounded with the right try and catches, the app might crash.

Bottom line, network connectivity, does not mean internet connectivity, it merely means that your device's wireless hardware can connect to another host and both can make a connection.

Below is a method that can check if the device can connect to a website and returns an answer accordingly.

if (networkConnectivity())
{
    try
    {
        HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.anywebsiteyouthinkwillnotbedown.com").openConnection());
        urlc.setRequestProperty("User-Agent", "Test");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(3000); //choose your own timeframe
        urlc.setReadTimeout(4000); //choose your own timeframe
        urlc.connect();
        networkcode2 = urlc.getResponseCode();
        return (urlc.getResponseCode() == 200);
    } catch (IOException e)
    {
        return (false);  //connectivity exists, but no internet.
    }
} else
{
    return false;  //no connectivity
}


回答3:

as for the question title , you want to check the internet access ,

so the fastest way and it is efficient at least for now ,

thnx to levit based on his answer https://stackoverflow.com/a/27312494/3818437

If you just want to check for a connection to any network - not caring if internet is available - then most of the answers here (including the accepted), implementing isConnectedOrConnecting() will work well. If you want to know if you have an internet connection (as the question title indicates) please read on Ping for the main name servers

 public boolean isOnline() {

     Runtime runtime = Runtime.getRuntime();
     try {

         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(); }

     return false; }

That's it! Yes that short, yes it is fast, no it does not need to run in background, no you don't need root privileges.

Possible Questions

Is this really fast enough?

Yes, very fast!

Is there really no reliable way to check if internet is available, other than testing something on the internet?

Not as far as I know, but let me know, and I will edit my answer.

Couldn't I just ping my own page, which I want to request anyways?

Sure! You could even check both, if you want to differentiate between "internet connection available" and your own servers beeing reachable

What if the DNS is down?

Google DNS (e.g. 8.8.8.8) is the largest public DNS service in the world. As of 2013 it serves 130 billion requests a day. Let 's just say, your app not responding would probably not be the talk of the day.

Which permissions are required?

Just internet access - what surprise ^^ (Btw have you ever thought about, how some of the methods suggested here could even have a remote glue about the availablility of internet, without this permission?)



回答4:

i have been using these two methods to check internet status sometimes https protocol doesn't work try http protocol

// Check if network is available
public static boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager)
            AppGlobals.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.isConnected();
}

// ping the google server to check if internet is really working or not
public static boolean isInternetWorking() {
    boolean success = false;
    try {
        URL url = new URL("https://google.com");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(10000);
        connection.connect();
        success = connection.getResponseCode() == 200;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return success;
}


回答5:

Try this:

ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

if(connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED || connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING  ) {
   text.setText("hey your online!!!")     ;               
   //Do something in here when we are connected   
} else if(connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||  connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED   ) {
   text.setText("Look your not online");           
}


回答6:

Because you are connected to a network does not guaruntee that you have internet, I have gone to just making my calls to the internet inside of a try catch block. Then catch the UnknownHostException to handle no internet.



回答7:

From my OLD Answer here

Just try this

I have applied the solution provided by @Levit and created function that will not call the extra Http Request.

It will solve the error Unable to Resolve Host

public static boolean isInternetAvailable(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork == null) return false;

    switch (activeNetwork.getType()) {
        case ConnectivityManager.TYPE_WIFI:
            if ((activeNetwork.getState() == NetworkInfo.State.CONNECTED ||
                    activeNetwork.getState() == NetworkInfo.State.CONNECTING) &&
                    isInternet())
                return true;
            break;
        case ConnectivityManager.TYPE_MOBILE:
            if ((activeNetwork.getState() == NetworkInfo.State.CONNECTED ||
                    activeNetwork.getState() == NetworkInfo.State.CONNECTING) &&
                    isInternet())
                return true;
            break;
        default:
            return false;
    }
    return false;
}

private static boolean isInternet() {

    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int exitValue = ipProcess.waitFor();
        Debug.i(exitValue + "");
        return (exitValue == 0);
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }

    return false;
}

Now call it like,

if (!isInternetAvailable(getActivity())) {
     //Show message
} else {
     //Perfoem the api request
}