Check for Active internet connection Android

前端 未结 7 1648
不知归路
不知归路 2020-11-27 05:26

I am trying to write a part in my app that will differentiate between an Active Wifi connection and an actual connection to the internet. Finding out if there is an active

7条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 05:31

    To check if the android device is having an active connection, I use this hasActiveInternetConnection() method below that (1) tries to detect if network is available and (2) then connect to google.com to determine whether the network is active.

    public static boolean hasActiveInternetConnection(Context context) {
        if (isNetworkAvailable(context)) {
            if (connectGoogle()) {
                return true;
            } else { //one more try
                return connectGoogle();
            }   
        } else {
            log("No network available! (in hasActiveInternetConnection())");
            return false;
        }
    }
    
    
    public static boolean isNetworkAvailable(Context ct) {
        ConnectivityManager connectivityManager = (ConnectivityManager) ct.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }
    
    
    public static boolean connectGoogle() {
        try {
            HttpURLConnection urlc = (HttpURLConnection)(new URL("http://www.google.com").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(10000); 
            urlc.connect();
            return (urlc.getResponseCode() == 200);     
        } catch (IOException e) {
            log("IOException in connectGoogle())");
            return false;
        }
    }
    

提交回复
热议问题