Detect if Android device has Internet connection

后端 未结 15 2490
野性不改
野性不改 2020-11-22 08:54

I need to tell if my device has Internet connection or not. I found many answers like:

private boolean isNetworkAvailable() {
    ConnectivityManager connect         


        
15条回答
  •  心在旅途
    2020-11-22 09:46

    I have modified THelper's answer slightly, to use a known hack that Android already uses to check if the connected WiFi network has Internet access. This is a lot more efficient over grabbing the entire Google home page. See here and here for more info.

    public static boolean hasInternetAccess(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(TAG, "Error checking internet connection", e);
            }
        } else {
            Log.d(TAG, "No network available!");
        }
        return false;
    }
    

提交回复
热议问题