How to programmatically check availibilty of internet connection in Android?

后端 未结 8 1917
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 04:02

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

相关标签:
8条回答
  • 2020-12-09 04:43

    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
    }
    
    0 讨论(0)
  • 2020-12-09 04:44

    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
    }
    
    0 讨论(0)
提交回复
热议问题