-1

i'm having a problem with the connection for my app (Android). I'm using the following code to check if i have internet connection.

    ConnectivityManager cm = (ConnectivityManager)context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
        try {
            URL url = new URL("http://www.google.com/");
            HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
            urlc.setRequestProperty("User-Agent", "test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(5000); // mTimeout is in seconds
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                return true;
            } else {
            return false;
        }
    } catch (IOException e) {
            Log.i("warning", "Error checking internet connection", e);
            return false;
        }
    }

After trying several times, i encounter that the problem is that im doing ping to "www.google.com.". I dont understand why is this happening. This code was woking fine for the last 2 years in my project.

lzn202
  • 1
  • 7
  • Try these things: 1- removing http://, 2- put https://, 3: Set port explicitly (80). I mean not the three at the same time, just test the first and if it didn't work try the second, and so on – Lenin Jun 01 '20 at 20:33
  • Thanks for the answer, i was reading documentation an i found the root of the problem. Google has shutdown the autentication for some services and i'm struggling to fix this. My greatest issue is that i can modify the code to the devices and i can update because of this connectivity problem. There will be some way to "Trick" the device to response and dont failed this test without changing the code? – lzn202 Jun 02 '20 at 15:15

1 Answers1

0

If you are testing this on a latest version of android, then you need to verify that you have whitelisted domains. You should read below: https://developer.android.com/training/articles/security-config

As a quick fix you can add below property to application tag:

android:usesCleartextTraffic="true"
Omar
  • 463
  • 3
  • 11