夜雨JC

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

 

要替换的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);
    }

}

 

posted on 2020-04-09 15:33  夜雨JC  阅读(636)  评论(0编辑  收藏  举报