Home > Net >  How to check the connection status in Android avoiding StrictMode
How to check the connection status in Android avoiding StrictMode

Time:01-25

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

CodePudding user response:

It is possible that his 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:

  • Don't ever call this method on the main (UI) thread. Always perform your Internet connectivity checks on background threads
  • Make the method asynchronous and provide a callback interface. The caller would then call the method (which will return immediately after launching the connectivity check on a background thread) and then the callback would be triggered when the connectivity check is completed. If this must be done on the main (UI) thread, you should show a progress dialog or similar while you are executing the connectivity check so that the user doesn't think the app is stuck.

CodePudding user response:

Your question is a bit unclear.

Here is how internet connection is checked in my app:


    private fun isConnected(): Boolean {
        val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo: NetworkInfo? = connMgr.activeNetworkInfo
        return networkInfo?.isConnected == true
    }

It still should be tested on the latest Android APIs as there are known changes, e.g. lack of options to emulate network on\off programmatically from tests since some specific version of Android API.

On another hand StrictMode is used to force you and all the rest software developers to write correct programs. Your code which operates with network and data storages should not be executed in the main thread (which is done by default), it should be run in the separate thread. StrictMode tracks this and notify you about violation of this practice either by warning message in logs or by crashing your app (I prefer second one as it is more obvious). However sometimes you depend on 3rd party library which violates this good practices and keeping yourStrictMode enabled prevents you from using this library.

In any cases StrictMode is usually enabled only for development stage like this:

if (BuildConfig.DEBUG) {
  // TODO enable StrictMode policies
}   
  • Related