Detect if Android device has Internet connection

后端 未结 15 2713
野性不改
野性不改 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:38

    public 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;
    }
    

    return true if internet is actually available

    Make sure you have these two permission

    
    
    

    if http does not work its because of the new android security they donot allow plain text communication now. for now just to by pass it.

    android:usesCleartextTraffic="true"

提交回复
热议问题