AndroidStudio 配置 性能优化埋点AOP-AspectJ

  • Post author:
  • Post category:其他



AOP-AspectJ


在buildscript的dependencies中添加如下代码

 classpath 'org.aspectj:aspectjtools:1.9.2'
 classpath 'org.aspectj:aspectjweaver:1.9.2'


在library/module中添加依赖

implementation  'org.aspectj:aspectjrt:1.9.2'


添加gradle任务

import org.aspectj.bridge.IMessage
import org.aspectj.bridge.MessageHandler
import org.aspectj.tools.ajc.Main
final def log = project.logger
final def variants = project.android.applicationVariants

variants.all { variant ->
    if (!variant.buildType.isDebuggable()) {
        log.debug("Skipping non-debuggable build type '${variant.buildType.name}'.")
        return;
    }

    JavaCompile javaCompile = variant.javaCompile
    javaCompile.doLast {
        String[] args = ["-showWeaveInfo",
                         "-1.8",
                         "-inpath", javaCompile.destinationDir.toString(),
                         "-aspectpath", javaCompile.classpath.asPath,
                         "-d", javaCompile.destinationDir.toString(),
                         "-classpath", javaCompile.classpath.asPath,
                         "-bootclasspath", project.android.bootClasspath.join(File.pathSeparator)]
        log.debug "ajc args: " + Arrays.toString(args)

        MessageHandler handler = new MessageHandler(true);
        new Main().run(args, handler);
        for (IMessage message : handler.getMessages(null, true)) {
            switch (message.getKind()) {
                case IMessage.ABORT:
                case IMessage.ERROR:
                case IMessage.FAIL:
                    log.error message.message, message.thrown
                    break;
                case IMessage.WARNING:
                    log.warn message.message, message.thrown
                    break;
                case IMessage.INFO:
                    log.info message.message, message.thrown
                    break;
                case IMessage.DEBUG:
                    log.debug message.message, message.thrown
                    break;
            }
        }
    }
}



如果你的library module中也使用到了aop,这时没有添加依赖的话,使用到library中被@Aspect标注的类的时候,就会出现java.lang.NoSuchMethodError: No static method aspectOf()这个错误。 在library module 中添加依赖的方法如下,也是和之前一样,添加在build.gradle的最后就好了.


import org.aspectj.bridge.IMessage
import org.aspectj.bridge.MessageHandler
import org.aspectj.tools.ajc.Main
final def log = project.logger

android.libraryVariants.all{ variant ->
    if (!variant.buildType.isDebuggable()) {
        log.debug("Skipping non-debuggable build type '${variant.buildType.name}'.")
        return
    }

    JavaCompile javaCompile = variant.javaCompiler
    javaCompile.doLast {
        String[] args = ["-showWeaveInfo",
                         "-1.8",
                         "-inpath", javaCompile.destinationDir.toString(),
                         "-aspectpath", javaCompile.classpath.asPath,
                         "-d", javaCompile.destinationDir.toString(),
                         "-classpath", javaCompile.classpath.asPath,
                         "-bootclasspath", project.android.bootClasspath.join(File.pathSeparator)]
        log.debug "ajc args: " + Arrays.toString(args)

        MessageHandler handler = new MessageHandler(true)
        new Main().run(args, handler)
        for (IMessage message : handler.getMessages(null, true)) {
            switch (message.getKind()) {
                case IMessage.ABORT:
                case IMessage.ERROR:
                case IMessage.FAIL:
                    log.error message.message, message.thrown
                    break
                case IMessage.WARNING:
                    log.warn message.message, message.thrown
                    break
                case IMessage.INFO:
                    log.info message.message, message.thrown
                    break
                case IMessage.DEBUG:
                    log.debug message.message, message.thrown
                    break
            }
        }
    }
}


冲突解决

// AOP 配置
aspectjx {
    // 排除一些第三方库的包名(Gson、 LeakCanary 和 AOP 有冲突)
    // 否则就会起冲突:ClassNotFoundException: Didn't find class on path: DexPathList
    exclude 'androidx', 'com.google', 'com.squareup', 'com.alipay', 'com.taobao',
            'com.baidu','map','vi', 'org.apache', 'com.chad'
}


配置完成之后新建一个类,运行应用即可

@Aspect
public class PerfromanceAop {
    private static final String TAG = "PerfromanceAop";
    @Around("call(* com.nuctech.ai.myapplication.MainActivity.**(..))")
    public void gettime(ProceedingJoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        long l = System.currentTimeMillis();
        try {
            joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        Log.d(TAG,"cost " +signature.getName() + "   "+ (System.currentTimeMillis() -l));
    }
}


配置规则


PointCut  带条件的JoinPoints


Advices  一种Hook,要插入代码的位置   Before:PointCut 之前执行  After:PointCut之后执行  Around :PointCut之前,之后分别执行


Before:Advice 具体的插入位置


execution:处理Join Point的类型,call 或者execution


(* android.app.Activity.on**(..)):匹配规则


onActivityCalled:要插入的代码