目的:本示例中用於檢測圖片尺寸和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的模式同時被用於很多反編譯等,鉤住所需代碼進行分析。