您的位置:首页 > 移动开发 > Android开发

Android中Hook Instrumentation的一些思考

2016-07-31 14:28 281 查看
众所周知,稍微知道Android主线程ActivityThread的人都知道有这个Instrumentation的存在,这个类是用来做什么的呢,通过源代码可以知道,这个类的作用非常重要,它是创建Activity,Application,等组件的一个分水岭,简单的说,它是ActivityThread的一个管家吧,也许你会问,Hook Instrumentation有什么作用,其实作用还是蛮大的,通过替换掉为我们自己的instrumentation的话,可以实现一些特别的事情,比如我们可以在创建Activity之前做些自己的事情,在美团的多dex分包中,链接为:

http://tech.meituan.com/mt-android-auto-split-dex.html

就是Hook 了Instrumentation,来实现自己的行为,那么如何Hook Instrumentation呢, 下面是代码:

public static void hookInstrumentation() throws Exception{
Class<?> activityThread=Class.forName("android.app.ActivityThread");
Method currentActivityThread=activityThread.getDeclaredMethod("currentActivityThread");
currentActivityThread.setAccessible(true);
//获取主线程对象
Object activityThreadObject=currentActivityThread.invoke(null);

//获取Instrumentation字段
Field mInstrumentation=activityThread.getDeclaredField("mInstrumentation");
mInstrumentation.setAccessible(true);
Instrumentation instrumentation= (Instrumentation) mInstrumentation.get(activityThreadObject);
CustomInstrumentation customInstrumentation=new CustomInstrumentation(instrumentation);
//替换掉原来的,就是把系统的instrumentation替换为自己的Instrumentation对象
mInstrumentation.set(activityThreadObject,customInstrumentation);
Log.d("[app]","Hook Instrumentation成功");

}


OK,以上便是Hook Instrumentation的代码,当然了,还有 CustomInstrumentation 这个类的源代码,这个类就是继承了Instrumentation,然后重新了生成Activity的方法,代码如下:

public class CustomInstrumentation  extends Instrumentation{
private Instrumentation base;

public CustomInstrumentation(Instrumentation base) {
this.base = base;
}

private void  getLoaderApk() throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException {
MyApplication myApplication=MyApplication.getInstance();
Field mLoadedApk=myApplication.getClass().getSuperclass().getDeclaredField("mLoadedApk");
mLoadedApk.setAccessible(true);
Object mLoadedApkObject=mLoadedApk.get(myApplication);
Log.d("[app]","获取的mLoadedApkObject="+mLoadedApkObject);
}

//重写创建Activity的方法
@Override
public Activity newActivity(ClassLoader cl, String className, Intent intent) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
Log.d("[app]","哈哈,你被Hook了");
try {
getLoaderApk();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
Log.d("[app]","className="+className+" intent="+intent);
return super.newActivity(cl, className, intent);
}
}


OK,代码写好了,我们只需在application中的onCreate方法中注入就好了,测试一下吧,现在运行程序,由于注入了我们的Instrumentation,因此进入主页的时候会打印出,哈哈,你被Hook这句话,如图:



可以看到是有这句话了,因此Hook Instrumentation是成功的,当然你也许会说这没有什么卵用啊,不是的,在一些特殊的时候还是很有用的,在一篇文章中的秒开优化中就是用了这种方法,下面是链接

http://zhengxiaoyong.me/2016/07/18/Android%E7%AB%AF%E5%BA%94%E7%94%A8%E7%A7%92%E5%BC%80%E4%BC%98%E5%8C%96%E4%BD%93%E9%AA%8C/

其实原理就这样,在第三方sdk优化的时候,根据优先级并行优化,因此可以在创建Activity的时候判断做些自己的事情,当然能做的事情很多,你可以拦截其他方法实现自己的目的,今天的文章就写到这吧,谢谢大家阅读。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  源代码