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;
里面有一些重要的方法,后面会逐个论述。