How to programmatically check availibilty of internet connection in Android?

后端 未结 8 1952
隐瞒了意图╮
隐瞒了意图╮ 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:42

    i have been using these two methods to check internet status sometimes https protocol doesn't work try http protocol

    // Check if network is available
    public static boolean isNetworkAvailable() {
        ConnectivityManager cm = (ConnectivityManager)
                AppGlobals.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isConnected();
    }
    
    // ping the google server to check if internet is really working or not
    public static 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;
    }
    

    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"

提交回复
热议问题