Check internet connection in android (not network connection)

前端 未结 7 914
孤城傲影
孤城傲影 2020-12-20 03:44

I have a problem with checking internet connection in android at runtime. I use some different methods to check internet connection but i don\'t know which one is better . b

7条回答
  •  旧巷少年郎
    2020-12-20 04:06

    To check if internet connection is available or not, you can use the below code snippet

        public static boolean hasActiveInternetConnection(Context context) {
        if (isNetworkAvailable(context)) {
            try {
                HttpURLConnection urlc = (HttpURLConnection) 
                        (new URL("http://clients3.google.com/generate_204")
                        .openConnection());
                urlc.setRequestProperty("User-Agent", "Android");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(1500); 
                urlc.connect();
                return (urlc.getResponseCode() == 204 && urlc.getContentLength() == 0);
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error checking internet connection", e);
            }
        } else {
            Log.d(LOG_TAG, "No network available!");
        }
        return false;
    }
    

    This code snippet will also help you to identify whether you device is having internet connection even if you are connected through wifi network.

    Note: make sure to call this method in background thread ,because this can take time depending on your network speed, and should not be called in Main thread

提交回复
热议问题