Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StrictMode for lower platform versions

I have started using the Android StrictMode and find that it would be great to have it always running during development and not just on a special branch I created in git. The reason I did this is my apps requirement to run with 1.6 and up.

I read on the android developer blog that you can set it up so that you activate it via reflection. I was just wondering how that would actually look like and if it might be possible to have this documented here (or somewhere else) rather than having everybody that wants to use it work out themselves.

like image 753
Manfred Moser Avatar asked Jan 06 '11 00:01

Manfred Moser


2 Answers

I've read Manfred's blog post but it doesn't work if you set target platform version lower than 2.3 because StrictMode.enableDefaults(); method is unavailable.

Here is my solution that relies fully on reflection and doesn't generate compilation errors:

    try {
        Class<?> strictModeClass = Class.forName("android.os.StrictMode", true, Thread.currentThread()
                .getContextClassLoader());

        Class<?> threadPolicyClass = Class.forName("android.os.StrictMode$ThreadPolicy", true, Thread
                .currentThread().getContextClassLoader());

        Class<?> threadPolicyBuilderClass = Class.forName("android.os.StrictMode$ThreadPolicy$Builder", true,
                Thread.currentThread().getContextClassLoader());

        Method setThreadPolicyMethod = strictModeClass.getMethod("setThreadPolicy", threadPolicyClass);

        Method detectAllMethod = threadPolicyBuilderClass.getMethod("detectAll");
        Method penaltyMethod = threadPolicyBuilderClass.getMethod("penaltyLog");
        Method buildMethod = threadPolicyBuilderClass.getMethod("build");

        Constructor<?> threadPolicyBuilderConstructor = threadPolicyBuilderClass.getConstructor();
        Object threadPolicyBuilderObject = threadPolicyBuilderConstructor.newInstance();

        Object obj = detectAllMethod.invoke(threadPolicyBuilderObject);

        obj = penaltyMethod.invoke(obj);
        Object threadPolicyObject = buildMethod.invoke(obj);
        setThreadPolicyMethod.invoke(strictModeClass, threadPolicyObject);

    } catch (Exception ex) {
        Log.w(TAG, ex);
    }
like image 173
pixel Avatar answered Sep 18 '22 15:09

pixel


So I did not want to wait and decided to make the effort and implement this myself. It basically boils down to wrapping StrictMode in a wrapper class and deciding at runtime via reflection if we can activate it.

I have documented it in detail in a blog post and made it available in github.

like image 26
Manfred Moser Avatar answered Sep 19 '22 15:09

Manfred Moser