Android Hook Instrumentation

 

要替换的Instrumentation类:

public class MyInstrumentation extends Instrumentation {

    private static final String TAG = MyInstrumentation.class.getSimpleName();

    private Instrumentation base;

    public MyInstrumentation(Instrumentation base) {
        super();
        this.base = base;
    }

   // 返回值改成true, 重写异常处理方法,在遇到异常时,程序不崩溃, @Override
public boolean onException(Object obj, Throwable e){ e.printStackTrace(); return true; } @Override public Activity newActivity(ClassLoader cl, String className, Intent intent) throws InstantiationException, IllegalAccessException, ClassNotFoundException { try { intent.setExtrasClassLoader(cl); intent.getBooleanExtra("a",false); }catch (Exception e){ e.printStackTrace(); } Log.e(TAG,"className " + className);return super.newActivity(cl,className, intent); } }

 

Hook工具类:

public class Hooker {
    public static final String TAG = "Hooker";

    public static void hookInstrmentation(){
        Class<?> activityThread;
        try{
            activityThread = Class.forName("android.app.ActivityThread");
            Method sCurrentActivityThread = activityThread.getDeclaredMethod("currentActivityThread");
            sCurrentActivityThread.setAccessible(true);
            //获取ActivityThread 对象
            Object activityThreadObject = sCurrentActivityThread.invoke(activityThread);

            //获取 Instrumentation 对象
            Field mInstrumentation = activityThread.getDeclaredField("mInstrumentation");
            mInstrumentation.setAccessible(true);
            Instrumentation instrumentation = (Instrumentation) mInstrumentation.get(activityThreadObject);
            MyInstrumentation customInstrumentation = new MyInstrumentation(instrumentation);
            //将我们的 customInstrumentation 设置进去
            mInstrumentation.set(activityThreadObject, customInstrumentation);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

 

替换:

public class GlobalApplication extends android.app.Application {

    @Override
    protected void attachBaseContext(Context base) {
        Hooker.hookInstrmentation();   //替换操作
        super.attachBaseContext(base);
    }

}

 

Android Hook Instrumentation

上一篇:Appium环境搭建_win 7 x64


下一篇:Nuxt引入axios,并模块化请求