目的:本示例中用于检测图片尺寸和Imageview尺寸,当然也可以检测其他操作,便于发现和解决问题。
框架:王大神的epic,关于其原理可百度谷歌。
实现:
gradle中引入:
compile 'me.weishu:epic:0.3.6'
public class ImageHook extends XC_MethodHook {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
super.afterHookedMethod(param);
TBTools.log().i("注入之后");
//注入自己的代码
ImageView imageView = (ImageView) param.thisObject;
TBTools.log().i("img width>>>"+imageView.getWidth()+"img height>>>"+imageView.getHeight());
Drawable drawable = ((ImageView) param.thisObject).getDrawable();
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
TBTools.log().i("drawable width>>>"+bitmap.getWidth()+"drawable height>>>"+bitmap.getHeight());
}
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
super.beforeHookedMethod(param);
TBTools.log().i("注入之前");
//注入自己的代码
ImageView imageView = (ImageView) param.thisObject;
TBTools.log().i("width>>>"+imageView.getWidth()+"height>>>"+imageView.getHeight());
Drawable drawable = ((ImageView) param.thisObject).getDrawable();
if(drawable != null){
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
TBTools.log().i("drawable width>>>"+bitmap.getWidth()+"drawable height>>>"+bitmap.getHeight());
}
}
}
再在Application中添加:
DexposedBridge.findAndHookMethod(ImageView.class,"setImageBitmap", Bitmap.class,new ImageHook());
在任意地方调用:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.test);
img.setImageBitmap(bitmap);
执行结果:
I/AndroidTools_TAG: {Thread:main}[tag=>APPAplication$1.afterHookedMethod(line:56):] ==========> 注入之前
I/AndroidTools_TAG: {Thread:main}[tag=>APPAplication$1.afterHookedMethod(line:56):] ==========> width>>>60height>>>60
I/AndroidTools_TAG: {Thread:main}[tag=>APPAplication$1.afterHookedMethod(line:56):] ==========> 注入之后
I/AndroidTools_TAG: {Thread:main}[tag=>APPAplication$1.afterHookedMethod(line:56):] ==========> img width>>>60img height>>>60
I/AndroidTools_TAG: {Thread:main}[tag=>APPAplication$1.afterHookedMethod(line:56):] ==========> drawable width>>>1024drawable height>>>640
可以看到,输出imageview和drawable的宽高,在实际使用过程中可以举一反三,比如判定两者是否可以结合显示等,如不符合规范可进行错误上报或提示,极大提升优化效率。
通过hook的做法,没有去修改原有的逻辑,只是增加一个注入类,用于注入我们自己所写逻辑,并没有和业务产生耦合,但是在实际使用过程中,hook的方式不是特别的稳定,比如我这自定义的系统上就无法跑起来,所以在使用的时候需要谨慎,尽量不要带到线上。
hook的模式同时被用于很多反编译等,钩住所需代码进行分析。