PluginManager分析

1, PluginManager

PluginManager框架的初始化以及插件的加载都在PluginManager中, PluginManager的getInstance方法调用

流程图如下,


PluginManager的getInstance方法如下,

public static PluginManager getInstance(Context base) {
     if (sInstance == null) {
         synchronized (PluginManager.class) {
            if (sInstance == null)
               sInstance = new PluginManager(base);
        }
    }
return sInstance;
}

PluginManager是单例,整个框架中仅有一个PluginManager对象。

PluginManager的构造方法如下,

private PluginManager(Context context) {
     Context app = context.getApplicationContext();
     if (app == null) {
         this.mContext = context;
     } else {
         this.mContext = ((Application)app).getBaseContext();
    }
    prepare();
}

直接看prepare方法,

private void prepare() {
    Systems.sHostContext = getHostContext();
    this.hookInstrumentationAndHandler();
    this.hookSystemServices();
}

其实,整个PluginManager的构造方法中除了进程上下文,主要就是完成Instrumentation和ActivityManager的Hook。

1.1 Instrumentation Hook

hookInstrumentationAndHandler的主要逻辑如下,

1,利用反射获取android系统的Instrumentation对象,

Instrumentation baseInstrumentation = ReflectUtil.getInstrumentation(this.mContext);
2,构造VAInstrumentation对象,
final VAInstrumentation instrumentation = new VAInstrumentation(this, baseInstrumentation);

3,利用反射Hook Instrumentation对象,

Object activityThread = ReflectUtil.getActivityThread(this.mContext);
ReflectUtil.setInstrumentation(activityThread, instrumentation);

4,利用反射Hook Instrumentation对象的mCallback变量,

ReflectUtil.setHandlerCallback(this.mContext, instrumentation);

其中,步骤3和步骤4真是一箭双雕!利用一个对象Hook两个变量,完全2部分功能。

详细的工具类ReflectUtil的方法在此就不论述了。

1.2 ActivityManager Hook

hookSystemServices方法如下,

private void hookSystemServices() {
    try {
        Singleton<IActivityManager> defaultSingleton = (Singleton<IActivityManager>) ReflectUtil.getField(ActivityManagerNative.class, null, "gDefault");
        IActivityManager activityManagerProxy = ActivityManagerProxy.newInstance(this, defaultSingleton.get());

       // Hook IActivityManager from ActivityManagerNative
      ReflectUtil.setField(defaultSingleton.getClass().getSuperclass(), defaultSingleton, "mInstance", activityManagerProxy);

      if (defaultSingleton.get() == activityManagerProxy) {
           this.mActivityManager = activityManagerProxy;
      }
    } catch (Exception e) {
      e.printStackTrace();
  }
}

hookSystemServices方法也很简单,就是利用ActivityManagerProxy Hook ActivityManagerService服务的

代理类ActivityManagerNative。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值