set Strict Mode Policy via reflection - Android java.lang.reflect

Android examples for java.lang.reflect:Class

Description

set Strict Mode Policy via reflection

Demo Code


import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main{
    public final static String POLICY_NAMES[] = {
            "android.os.StrictMode$ThreadPolicy",
            "android.os.StrictMode$VmPolicy" };
    public final static String SET_POLICY_NAMES[] = { "setThreadPolicy",
            "setVmPolicy" };
    public static void setStrictModePolicy(int type) {
        try {//from  ww  w. ja  v  a2s . c  o m
            Class<?> clsStrictMode = Class.forName("android.os.StrictMode");
            Class<?> clsPolicy = Class.forName(POLICY_NAMES[type]);
            Class<?> clsBuilder = Class.forName(POLICY_NAMES[type]
                    + "$Builder");

            Method mtdSetPolicy = clsStrictMode.getDeclaredMethod(
                    SET_POLICY_NAMES[type], new Class[] { clsPolicy });
            Method mtdDetectAll = clsBuilder.getDeclaredMethod("detectAll");
            Method mtdPenaltyLog = clsBuilder
                    .getDeclaredMethod("penaltyLog");
            Method mtdBuild = clsBuilder.getDeclaredMethod("build");

            Object objBuilder = mtdDetectAll.invoke(clsBuilder
                    .newInstance());
            objBuilder = mtdPenaltyLog.invoke(objBuilder);
            Object objThreadPolicy = mtdBuild.invoke(objBuilder);

            mtdSetPolicy.invoke(null, objThreadPolicy);
        } catch (InstantiationException e) {
            //ExceptionHandler.processFatalException(e);
        }
    }
}

Related Tutorials