Android开发Android开发经验谈Android技术知识

学习自定义Gradle插件2

2020-04-09  本文已影响0人  卖炭少年炭治郎

前序步骤参考链接:学习自定义gradle插件

使用 ASM,插入字节码到 Activity 文件

1.在 asm_lifecycle_plugin 的 build.gradle 中,添加对 ASM 的依赖,如下:

apply plugin: 'maven'
apply plugin:'groovy'

dependencies {
    compile gradleApi()
    compile localGroovy()

    compile 'com.android.tools.build:gradle:3.4.2'

    //asm相关依赖
    implementation 'org.ow2.asm:asm:7.1'
    implementation 'org.ow2.asm:asm-commons:7.1'
}
...
  1. 在asm_lifecycle_pluginmodule中的src/main/java目录下创建包com.okay.asm,并分别创建LifecycleClassVisitor.java和LifeCycleMethodVisitor.java文件
public class LifeCycleClassVisitor extends ClassVisitor {

    private String className;
    private String superName;

    public LifeCycleClassVisitor(int api) {
        super(api);
    }

    public LifeCycleClassVisitor(int api, ClassVisitor classVisitor) {
        super(api, classVisitor);
    }

    @Override
    public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
        super.visit(version, access, name, signature, superName, interfaces);
        this.className = name;
        this.superName = superName;
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
        System.out.println("ClassVisitor visitMethod name---"+name+",super name = "+superName);
        MethodVisitor mv = cv.visitMethod(access, name, descriptor, signature, exceptions);

        if (superName.equals("androidx/appcompat/app/AppCompatActivity")){
            if (name.startsWith("onCreate")){
                //处理这个方法
                return new LifeCycleMethodVisitor(mv,className,name);
            }
        }

        return mv;
    }
}

public class LifeCycleMethodVisitor extends MethodVisitor {

    private String className;
    private String methodName;

    public LifeCycleMethodVisitor(MethodVisitor mv, String className, String name) {
        super(Opcodes.ASM5, mv);
        this.className = className;
        this.methodName = name;
    }

    /**
     * 方法执行前先走这个
     */
    @Override
    public void visitCode() {
        super.visitCode();
        System.out.println("LifeCycleMethodVisitor -- :visitCode");
        //LDC "SizeConvertUtil"
        //LDC "className---->MethodName"
        //INVOKESTATIC android/util/Log.i (Ljava/lang/String;Ljava/lang/String;)I
        //POP
        mv.visitLdcInsn("zyl_TAG");
        mv.visitLdcInsn(className + "-------->" + methodName);
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, "android/util/Log", "i", "(Ljava/lang/String;Ljava/lang/String;)I", false);
        mv.visitLdcInsn(Opcodes.POP);
    }
}
  1. 修改 LifeCycleTransform 的 transform 方法,并将需要插桩的字节码插入到 MainActivity.class 文件中的transform方法:
  /**
     *
     * @param transformInvocation
     * @throws TransformException* @throws InterruptedException* @throws IOException
     */
    @Override
    void transform(TransformInvocation transformInvocation) throws TransformException, InterruptedException, IOException {
        super.transform(transformInvocation)

        //拿到所有的class文件
        def inputs = transformInvocation.inputs

        def provider = transformInvocation.outputProvider
        inputs.each { transformInput ->
            transformInput.directoryInputs.each { DirectoryInput directoryInput ->
                File dir = directoryInput.file
                if (dir) {
                    dir.traverse(type: FileType.FILES, nameFilter: ~/.*\.class/) { File file ->
                        System.out.println("find class: " + file.name)
                        //对class文件进行读取
                        ClassReader classReader = new ClassReader(file.bytes)
                        //对class文件进行写入
                        ClassWriter classWriter = new ClassWriter(classReader, ClassWriter.COMPUTE_MAXS)
                        //访问相应的内容
                        ClassVisitor classVisitor = new LifeCycleClassVisitor(classWriter)
                        classReader.accept(classVisitor, ClassReader.EXPAND_FRAMES)
                        byte[] bytes = classWriter.toByteArray()
                        //通过文件流写入的形式覆盖掉原有的内容,实现class的改写
                        FileOutputStream outputStream = new FileOutputStream(file.path)
                        outputStream.write(bytes)
                        outputStream.close()
                    }
                }
                //处理完输入文件后把输出传递给下一个文件
                def location = provider.getContentLocation(directoryInput.name, directoryInput.contentTypes, directoryInput.scopes, Format.DIRECTORY)
                FileUtils.copyDirectory(directoryInput.file,location)
            }

        }
    }
  1. 上面几步如果一切执行顺利,那接下来就可以在点击uploadArchives重新部署LifeCyclePlugin。注意:重新部署时,需要先在appmodule的build.gradle中将插件依赖注释,否则报错。部署成功之后,重新在app中依赖自定义插件并运行主项目,当 MainActivity 被打开时,在 logcat中过滤zyl_TAG:
04-08 10:11:07.699 18156-18156/com.okay.asmlifecycle I/zyl_TAG: com/okay/asmlifecycle/MainActivity-------->onCreate

问题与总结

1.运行报错

java.lang.NoClassDefFoundError: Failed resolution of: Landroidx/appcompat/R$drawable;
        at androidx.appcompat.widget.AppCompatDrawableManager$1.<init>(AppCompatDrawableManager.java:63)
        at androidx.appcompat.widget.AppCompatDrawableManager.preload(AppCompatDrawableManager.java:57)
        at androidx.appcompat.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:328)
        at androidx.appcompat.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:278)
        at androidx.appcompat.app.AppCompatDelegate.create(AppCompatDelegate.java:221)
        at androidx.appcompat.app.AppCompatActivity.getDelegate(AppCompatActivity.java:543)
        at androidx.appcompat.app.AppCompatActivity.attachBaseContext(AppCompatActivity.java:98)
        at android.app.Activity.attach(Activity.java:6028)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2462)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2608)
        at android.app.ActivityThread.access$800(ActivityThread.java:178)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
        at android.os.Handler.dispatchMessage(Handler.java:111)
        at android.os.Looper.loop(Looper.java:194)
        at android.app.ActivityThread.main(ActivityThread.java:5637)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "androidx.appcompat.R$drawable" on path: DexPathList[[zip file "/data/app/com.okay.asmlifecycle-1/base.apk"],nativeLibraryDirectories=[/vendor/lib64, /system/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
        at androidx.appcompat.widget.AppCompatDrawableManager$1.<init>(AppCompatDrawableManager.java:63) 
        at androidx.appcompat.widget.AppCompatDrawableManager.preload(AppCompatDrawableManager.java:57) 
        at androidx.appcompat.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:328) 
        at androidx.appcompat.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:278) 
        at androidx.appcompat.app.AppCompatDelegate.create(AppCompatDelegate.java:221) 
        at androidx.appcompat.app.AppCompatActivity.getDelegate(AppCompatActivity.java:543) 
        at androidx.appcompat.app.AppCompatActivity.attachBaseContext(AppCompatActivity.java:98) 
        at android.app.Activity.attach(Activity.java:6028) 
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2462) 
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2608) 
        at android.app.ActivityThread.access$800(ActivityThread.java:178) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470) 
        at android.os.Handler.dispatchMessage(Handler.java:111) 
        at android.os.Looper.loop(Looper.java:194) 
        at android.app.ActivityThread.main(ActivityThread.java:5637) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at java.lang.reflect.Method.invoke(Method.java:372) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754) 
        Suppressed: java.lang.ClassNotFoundException: androidx.appcompat.R$drawable
        at java.lang.Class.classForName(Native Method)
        at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
        at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
                ... 20 more
     Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

上一篇下一篇

猜你喜欢

热点阅读