androidhttpurlconnectionandroid-connectivitymanagerandroid-strictmodenetworkinfo

How to check the connection status in Android avoiding StrictMode


I created a function that returns a boolean based on the presence of an internet connection, this function it is called different times from different java classes.

The only way that I find to use it is to use the StrictMode.setThreadPolicy (i know that it's not a good practice).

How I can solve my problem ?

public boolean checkConnection() {
    boolean response = false;
    try {
        //StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isConnected()) {
                URL url = new URL(databaseManagement.getSettingValue("urlCheckConnection", context));
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setConnectTimeout(3000);
                httpURLConnection.setReadTimeout(3000);
                httpURLConnection.connect();
                response = httpURLConnection.getResponseCode() == 200;
                httpURLConnection.disconnect();
                httpURLConnection.getInputStream().close();
            }
        }
    } catch (Exception e) {
        response = false;
        wil.WriteFile("checkConnection - Exception: " + e.getMessage(), context);
    }
    return response;
}

Solution

  • It is possible that this method will block the calling thread for up to 3 seconds. Generally speaking you should not do network or file I/O on the main (UI) thread because that can cause the app to appear non-responsive (and Android will generate an ANR exception in that case). There are various alternatives you could use, depending on your situation. Here are two: