Search code examples
androidandroid-strictmode

StrictModeBuilder permitAll not working


I do have an old app that refuses to work on Android 4.1 devices. It's the NetworkOnMainThreadException that jumps in here.

So I tried to permit this with the following steps - but these don't work. I tested that with the 4.1 emulator. What is really needed to come around that error - app rewrite is no option. Currently I exclude 4.1 devices from my apps.

A class file ...

public class StrictModeWrapper {

    static {
        try {
            Class.forName("android.os.StrictMode");
        } catch (Exception exception) {
            throw new RuntimeException(exception);
        }
    }

    public static void checkAvailable() {
    }

    @SuppressLint("NewApi")
    public static void setThreadPolicy() {
        StrictMode.ThreadPolicy strictModeThreadPolicy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(strictModeThreadPolicy);
    }
}

... called in an extended Application class:

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        try {
            StrictModeWrapper.checkAvailable();
            StrictModeWrapper.setThreadPolicy();
            } catch (Throwable throwable) {
        }
    }
}

The extended Application class is registered in the Manifest and working.


Solution

  • StrictMode behaves different on Android version >= 16 than prior releases. The docs suggest to issue StrictMode calls in onCreate() of an extended Application, Activity, etc.. At least onCreate() in an extended Application works different now and proofes the docs wrong (as of today).

    Here's the StrictMode doc that describes how to add StrictMode calls to an extended application for example (that's wrong as of today):

    StrictMode

    Here's a Google Code issue that describes the problem and gives a workaround:

    Google Code Issue 35298