其他
大图检测插件的落地
本文作者
作者:layz4android
链接:
https://juejin.cn/post/7219908995338223671
本文由作者授权发布。
我们都知道,大图是导致OOM的真凶之一,对大图做工程级的check,就能避免类似问题的出现。
也就是说,这张图片加载到内存中就需要占用885k的内存空间,而且系统对于res目录下的资源加载,如果是不同的drawable目录,例如drawable-xhdpi、drawable-xxhdpi,都是先进行分辨率的转换,再加载到内存。而且我们在显示这张图片的时候,设置ImageView的大小为40dpx40dp,显然这张图片是过大了。
2.1 大图加载的优化策略
想要详细了解其中的实现原理,可以看下面的两篇文章:
Android进阶宝典 -- 学会Bitmap内存管理,你的App内存还会暴增吗?
Android性能优化 -- 大图治理
https://juejin.cn/post/7201444843138580517
https://juejin.cn/post/7131385674694918180
2.2 大图检测的思想
public void setImageDrawable(@Nullable Drawable drawable) {
if (mDrawable != drawable) {
mResource = 0;
mUri = null;
final int oldWidth = mDrawableWidth;
final int oldHeight = mDrawableHeight;
updateDrawable(drawable);
if (oldWidth != mDrawableWidth || oldHeight != mDrawableHeight) {
requestLayout();
}
invalidate();
}
}
@android.view.RemotableViewMethod(asyncImpl="setImageIconAsync")
public void setImageIcon(@Nullable Icon icon) {
setImageDrawable(icon == null ? null : icon.loadDrawable(mContext));
}
@android.view.RemotableViewMethod
public void setImageBitmap(Bitmap bm) {
// Hacky fix to force setImageDrawable to do a full setImageDrawable
// instead of doing an object reference comparison
mDrawable = null;
if (mRecycleableBitmapDrawable == null) {
mRecycleableBitmapDrawable = new BitmapDrawable(mContext.getResources(), bm);
} else {
mRecycleableBitmapDrawable.setBitmap(bm);
}
setImageDrawable(mRecycleableBitmapDrawable);
}
@android.view.RemotableViewMethod(asyncImpl="setImageResourceAsync")
public void setImageResource(@DrawableRes int resId) {
// The resource configuration may have changed, so we should always
// try to load the resource even if the resId hasn't changed.
final int oldWidth = mDrawableWidth;
final int oldHeight = mDrawableHeight;
updateDrawable(null);
mResource = resId;
mUri = null;
resolveUri();
if (oldWidth != mDrawableWidth || oldHeight != mDrawableHeight) {
requestLayout();
}
invalidate();
}
public class MyImageView extends ImageView {
public MyImageView(Context context) {
super(context);
}
public MyImageView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public MyImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MyImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public void setImageDrawable(@Nullable Drawable drawable) {
super.setImageDrawable(drawable);
//容器的大小
int widthContainer = this.getWidth();
int heightContainer = this.getHeight();
if (drawable != null){
//获取图片的大小
int intrinsicWidth = drawable.getIntrinsicWidth();
int intrinsicHeight = drawable.getIntrinsicHeight();
//只要有一个方向超了,都会报警
if (intrinsicWidth > widthContainer * 2 || intrinsicHeight > heightContainer * 2 ){
Log.e("BigViewCheck","BigViewCheck | checkIsBigView | $drawable $intrinsicWidth * $intrinsicHeight is bigView");
}
}
}
}
2.3 大图检测插件实现
如果不熟悉字节码插桩的伙伴,可以回头看看这篇文章Android 字节码插桩全流程解析。
public class ViewCheckPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
AppExtension extension = project.getExtensions().getByType(AppExtension.class);
if (extension != null){
extension.registerTransform(new ViewCheckTransform());
}
}
}
2.3.1 Transform的实现
public class ViewCheckTransform extends Transform {
@Override
public String getName() {
return "ViewCheckTransform";
}
@Override
public Set<QualifiedContent.ContentType> getInputTypes() {
return TransformManager.CONTENT_CLASS;
}
@Override
public Set<QualifiedContent.Scope> getScopes() {
HashSet hashSet = new HashSet();
hashSet.add(QualifiedContent.Scope.PROJECT);
hashSet.add(QualifiedContent.Scope.SUB_PROJECTS);
hashSet.add(QualifiedContent.Scope.EXTERNAL_LIBRARIES);
return hashSet;
}
@Override
public boolean isIncremental() {
return false;
}
@Override
public void transform(Context context, Collection<TransformInput> inputs, Collection<TransformInput> referencedInputs, TransformOutputProvider outputProvider, boolean isIncremental) throws IOException, TransformException, InterruptedException {
System.out.println("ViewCheckTransform start transform");
//需要对jar包处理,ImageView存在Android SDK的jar包里
inputs.forEach(new Consumer<TransformInput>() {
@Override
public void accept(TransformInput transformInput) {
//文件夹交给下一级Transform即可,DirectoryInput仅限于我们自己的工程下的目录
transformInput.getDirectoryInputs().forEach(new Consumer<DirectoryInput>() {
@Override
public void accept(DirectoryInput directoryInput) {
File dest = outputProvider.getContentLocation(directoryInput.getName(),
directoryInput.getContentTypes(),
directoryInput.getScopes(), Format.DIRECTORY);
try {
FileUtils.copyDirectory(directoryInput.getFile(),dest);
} catch (IOException e) {
e.printStackTrace();
}
}
});
transformInput.getJarInputs().forEach(new Consumer<JarInput>() {
@Override
public void accept(JarInput jarInput) {
findClass(jarInput.getFile());
File dest = outputProvider.getContentLocation(jarInput.getName(), jarInput.getContentTypes(), jarInput.getScopes(), Format.JAR);
try {
FileUtils.copyFile(jarInput.getFile(),dest);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
}
private void findClass(File file){
if (file.isDirectory()){
for (File temp:file.listFiles()){
findClass(temp);
}
}else {
//如果是文件,判断是不是ImageView
handleFile(file);
}
}
private void handleFile(File file) {
System.out.println("ViewCheckTransform | handleFile | "+file);
}
}
2.3.2 jar包处理
private void handleFile(File file) {
try {
JarFile jarFile = new JarFile(file);
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
if (jarEntry.getName().startsWith("androidx/appcompat/widget/AppCompatImageView")){
System.out.println("ViewCheckTransform | handleFile | jarEntry " + jarEntry);
InputStream inputStream = jarFile.getInputStream(jarEntry);
System.out.println("ViewCheckTransform | inputStream "+inputStream);
//完成字节码插桩
handleASM(inputStream);
}
}
} catch (Exception exp) {
}
}
private byte[] handleASM(InputStream inputStream) {
//
try {
ClassReader classReader = new ClassReader(inputStream);
ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classReader.accept(new ViewCheckVisitor(Opcodes.ASM9,classWriter),ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG);
return classWriter.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
}
public class ViewCheckVisitor extends ClassVisitor {
public ViewCheckVisitor(int api) {
super(api);
}
public ViewCheckVisitor(int api, ClassVisitor classVisitor) {
super(api, classVisitor);
}
@Override
public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
System.out.println("ViewCheckVisitor | visitMethod | name "+name);
MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions);
return new ViewCheckAdapter(api, mv, access, name, descriptor);
}
}
public class ViewCheckAdapter extends AdviceAdapter {
/**
* Constructs a new {@link AdviceAdapter}.
*
* @param api the ASM API version implemented by this visitor. Must be one of {@link
* Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}.
* @param methodVisitor the method visitor to which this adapter delegates calls.
* @param access the method's access flags (see {@link Opcodes}).
* @param name the method's name.
* @param descriptor the method's descriptor (see {@link Type Type}).
*/
protected ViewCheckAdapter(int api, MethodVisitor methodVisitor, int access, String name, String descriptor) {
super(api, methodVisitor, access, name, descriptor);
}
@Override
protected void onMethodEnter() {
super.onMethodEnter();
}
}
ViewCheckVisitor | visitMethod | name <init>
ViewCheckVisitor | visitMethod | name <init>
ViewCheckVisitor | visitMethod | name <init>
ViewCheckVisitor | visitMethod | name setImageResource
ViewCheckVisitor | visitMethod | name setImageDrawable
ViewCheckVisitor | visitMethod | name setImageBitmap
ViewCheckVisitor | visitMethod | name setImageURI
ViewCheckVisitor | visitMethod | name setBackgroundResource
ViewCheckVisitor | visitMethod | name setBackgroundDrawable
ViewCheckVisitor | visitMethod | name setSupportBackgroundTintList
ViewCheckVisitor | visitMethod | name getSupportBackgroundTintList
ViewCheckVisitor | visitMethod | name setSupportBackgroundTintMode
ViewCheckVisitor | visitMethod | name getSupportBackgroundTintMode
ViewCheckVisitor | visitMethod | name setSupportImageTintList
ViewCheckVisitor | visitMethod | name getSupportImageTintList
ViewCheckVisitor | visitMethod | name setSupportImageTintMode
ViewCheckVisitor | visitMethod | name getSupportImageTintMode
ViewCheckVisitor | visitMethod | name drawableStateChanged
ViewCheckVisitor | visitMethod | name hasOverlappingRendering
ViewCheckVisitor | visitMethod | name setImageLevel
private File handleJarFile(File file) {
try {
//将jar包读写到内存中
JarFile jarFile = new JarFile(file);
//创建一个新的jar包
File newJarFile = new File(file.getParentFile(), "temp_" + file.getName());
System.out.println("ViewCheckTransform | newJarFile | name " + getName());
if (newJarFile.exists()) newJarFile.delete();
JarOutputStream jos =
new JarOutputStream(new BufferedOutputStream(new FileOutputStream(newJarFile)));
//读取jar包内容
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
//获取jar包文件输入流
JarEntry jarEntry = entries.nextElement();
InputStream inputStream = jarFile.getInputStream(jarEntry);
//先往新jar包里加Entry
jos.putNextEntry(new JarEntry(jarEntry.getName()));
//判断是否需要字节码插桩
if (jarEntry.getName().startsWith("androidx/appcompat/widget/AppCompatImageView")) {
System.out.println("ViewCheckTransform | handleFile | jarEntry " + jarEntry);
System.out.println("ViewCheckTransform | inputStream " + inputStream);
//完成字节码插桩
byte[] bytes = handleASM(inputStream);
jos.write(bytes);
jos.flush();
inputStream.close();
} else {
//如果不需要修改,那么就把entry写到新的jar里就行了
jos.write(IOUtils.toByteArray(inputStream));
inputStream.close();
}
}
//当前jar包处理完成
jarFile.close();
jos.closeEntry();
jos.flush();
jos.close();
return newJarFile;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private File findClass(File file) {
if (file.isDirectory()) {
for (File temp : file.listFiles()) {
findClass(temp);
}
} else {
//如果是文件,判断是不是ImageView
return handleJarFile(file);
}
return null;
}
transformInput.getJarInputs().forEach(new Consumer<JarInput>() {
@Override
public void accept(JarInput jarInput) {
File srcFile = findClass(jarInput.getFile());
System.out.println("ViewCheckTransform | findClass | srcFile "+srcFile);
File dest = outputProvider.getContentLocation(jarInput.getName(), jarInput.getContentTypes(), jarInput.getScopes(), Format.JAR);
try {
FileUtils.copyFile(srcFile, dest);
} catch (IOException e) {
e.printStackTrace();
}
}
});
2.3.3 实现代码插桩逻辑
@Override
protected void onMethodEnter() {
super.onMethodEnter();
visitLdcInsn("ViewCheck");
visitLdcInsn("\u5f00\u542f\u63d2\u6869\u4e86");
visitMethodInsn(INVOKESTATIC, "android/util/Log", "e", "(Ljava/lang/String;Ljava/lang/String;)I", false);
visitInsn(POP);
}
2023-04-08 21:02:55.356 12309-12309/com.lay.dm E/ViewCheck: 开启插桩了
2023-04-08 21:02:56.172 12309-12309/com.lay.dm E/ViewCheck: 开启插桩了
2023-04-08 21:02:56.286 12309-12309/com.lay.dm E/ViewCheck: 开启插桩了
2023-04-08 21:02:56.648 12309-12309/com.lay.dm E/ViewCheck: 开启插桩了
2023-04-08 21:02:56.966 12309-12309/com.lay.dm E/ViewCheck: 开启插桩了
L0
LINENUMBER 36 L0
LDC "ViewCheck"
LDC "\u5f00\u542f\u63d2\u6869\u4e86"
INVOKESTATIC android/util/Log.e (Ljava/lang/String;Ljava/lang/String;)I
POP
L1
LINENUMBER 37 L1
ALOAD 0
INVOKEVIRTUAL com/lay/dm/MyImageView.getWidth ()I
ISTORE 2
L2
LINENUMBER 38 L2
ALOAD 0
INVOKEVIRTUAL com/lay/dm/MyImageView.getHeight ()I
ISTORE 3
L3
LINENUMBER 40 L3
ALOAD 1
IFNULL L4
L5
LINENUMBER 42 L5
ALOAD 1
INVOKEVIRTUAL android/graphics/drawable/Drawable.getIntrinsicWidth ()I
ISTORE 4
L6
LINENUMBER 43 L6
ALOAD 1
INVOKEVIRTUAL android/graphics/drawable/Drawable.getIntrinsicHeight ()I
ISTORE 5
L7
LINENUMBER 46 L7
ILOAD 4
ILOAD 2
ICONST_2
IMUL
IF_ICMPGT L8
ILOAD 5
ILOAD 3
ICONST_2
IMUL
IF_ICMPLE L4
L8
LINENUMBER 47 L8
FRAME FULL [com/lay/dm/MyImageView android/graphics/drawable/Drawable I I I I] []
LDC "BigViewCheck"
LDC "BigViewCheck | checkIsBigView | $drawable $intrinsicWidth * $intrinsicHeight is bigView"
INVOKESTATIC android/util/Log.e (Ljava/lang/String;Ljava/lang/String;)I
POP
L4
LINENUMBER 50 L4
FRAME FULL [com/lay/dm/MyImageView android/graphics/drawable/Drawable I I] []
RETURN
L9
LOCALVARIABLE intrinsicWidth I L6 L4 4
LOCALVARIABLE intrinsicHeight I L7 L4 5
LOCALVARIABLE this Lcom/lay/dm/MyImageView; L0 L9 0
LOCALVARIABLE drawable Landroid/graphics/drawable/Drawable; L0 L9 1
LOCALVARIABLE widthContainer I L2 L9 2
LOCALVARIABLE heightContainer I L3 L9 3
MAXSTACK = 3
MAXLOCALS = 6
L3
LINENUMBER 40 L3
ALOAD 1
IFNULL L4
L4
LINENUMBER 50 L4
FRAME FULL [com/lay/dm/MyImageView android/graphics/drawable/Drawable I I] []
RETURN
@Override
protected void onMethodEnter() {
super.onMethodEnter();
visitLdcInsn("ViewCheck");
visitLdcInsn("\u5f00\u542f\u63d2\u6869\u4e86");
visitMethodInsn(INVOKESTATIC, "android/util/Log", "e", "(Ljava/lang/String;Ljava/lang/String;)I", false);
visitInsn(POP);
visitVarInsn(ALOAD, 0);
visitMethodInsn(INVOKEVIRTUAL, "android/widget/ImageView", "getWidth", "()I");
visitVarInsn(ISTORE, 2);
visitVarInsn(ALOAD, 0);
visitMethodInsn(INVOKEVIRTUAL, "android/widget/ImageView", "getHeight", "()I");
visitVarInsn(ISTORE, 3);
visitVarInsn(ALOAD, 1);
Label nullLabel = new Label();
visitJumpInsn(IFNULL, nullLabel);
visitVarInsn(ALOAD, 1);
visitMethodInsn(INVOKEVIRTUAL, "android/graphics/drawable/Drawable", "getIntrinsicWidth", "()I");
visitVarInsn(ISTORE, 4);
visitVarInsn(ALOAD, 1);
visitMethodInsn(INVOKEVIRTUAL, "android/graphics/drawable/Drawable", "getIntrinsicHeight", "()I");
visitVarInsn(ISTORE, 5);
visitVarInsn(ILOAD, 4);
visitVarInsn(ILOAD, 2);
visitInsn(ICONST_2);
visitInsn(IMUL);
Label printLabel = new Label();
visitJumpInsn(IF_ICMPGT, printLabel);
visitVarInsn(ILOAD, 5);
visitVarInsn(ILOAD, 3);
visitInsn(ICONST_2);
visitInsn(IMUL);
visitJumpInsn(IF_ICMPLE, nullLabel);
visitLabel(printLabel);
visitLdcInsn("BigViewCheck");
visitLdcInsn("BigViewCheck | checkIsBigView | $drawable $intrinsicWidth * $intrinsicHeight is bigView");
visitMethodInsn(INVOKESTATIC, "android/util/Log", "e", "(Ljava/lang/String;Ljava/lang/String;)I", false);
visitInsn(POP);
visitLabel(nullLabel);
}
public void setImageDrawable(@Nullable Drawable var1) {
Log.e("ViewCheck", "开启插桩了");
int var2 = this.getWidth();
int var3 = this.getHeight();
if (var1 != null) {
int var4 = var1.getIntrinsicWidth();
int var5 = var1.getIntrinsicHeight();
if (var4 > var2 * 2 || var5 > var3 * 2) {
Log.e("BigViewCheck", "BigViewCheck | checkIsBigView | $drawable $intrinsicWidth * $intrinsicHeight is bigView");
}
}
if (this.mImageHelper != null && var1 != null && !this.mHasLevel) {
this.mImageHelper.obtainLevelFromDrawable(var1);
}
super.setImageDrawable(var1);
if (this.mImageHelper != null) {
this.mImageHelper.applySupportImageTint();
if (!this.mHasLevel) {
this.mImageHelper.applyImageLevel();
}
}
}
最后推荐一下我做的网站,玩Android: wanandroid.com ,包含详尽的知识体系、好用的工具,还有本公众号文章合集,欢迎体验和收藏!
扫一扫 关注我的公众号
如果你想要跟大家分享你的文章,欢迎投稿~
┏(^0^)┛明天见!