Instrumentation Hook

3, Instrumentation  Hook

其实, Instrumentation的Hook应该放在PMS和AMS之前论述的,那么,Instrumentation是什么呢?

Instrumentation,每一个应用程序只有一个Instrumentation对象,每个Activity内都有一个对该对象的引用。

Instrumentation可以理解为应用进程的管家,ActivityThread要创建或暂停某个Activity时,都需要通过Instrumentation

来进行具体的操作。

mInstrumentation是ActivityThread的一个变量,

Instrumentation mInstrumentation;

因此,直接Hook这个变量就可以。

3.1 Instrumentation Hook

HookFactory的installHook方法有关Instrumentation的代码如下,

installHook(new InstrumentationHook (context), classLoader);

InstrumentationHook有关的结构图如下,


InstrumentationHook的createHookHandle返回null,

protected BaseHookHandle createHookHandle() {
     return null;
}

InstrumentationHook的onInstall方法主要逻辑如下,

1,获取ActivityThread的mInstrumentation变量,

Object target = ActivityThreadCompat.currentActivityThread();
Class ActivityThreadClass = ActivityThreadCompat.activityThreadClass();
/*替换ActivityThread.mInstrumentation,拦截组件调度消息*/
Field mInstrumentationField = FieldUtils.getField(ActivityThreadClass, "mInstrumentation");
Instrumentation mInstrumentation = (Instrumentation) FieldUtils.readField(mInstrumentationField, target);

2,构造PluginInstrumentation对象,

if (!PluginInstrumentation.class.isInstance(mInstrumentation)) {
    PluginInstrumentation pit = new PluginInstrumentation(mHostContext, mInstrumentation);
    pit.setEnable(isEnable());

3,Hook 原来的Instrumentation对象

mPluginInstrumentations.add(pit);
FieldUtils.writeField(mInstrumentationField, target, pit);

mPluginInstrumentations是一个list,有多少个插件就有多少个PluginInstrumentation对象,定义如下,

private List<PluginInstrumentation> mPluginInstrumentations = new ArrayList<PluginInstrumentation>();

3.2 PluginInstrumentation

PluginInstrumentation的构造方法如下,

public PluginInstrumentation(Context hostContext, Instrumentation target) {
      mTarget = target;
      mHostContext = hostContext;
 }

mTarget变量指Hook 之前的ActivityThread的mInstrumentation变量,是PluginInstrumentation的父类。

mHostContext 当然是宿主的进程上下文。

protected Instrumentation mTarget;
private final Context mHostContext;

里面有一些重要的方法,后面会逐个论述。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值