一个分为4个步骤
1. 首先我们需要下载一个 aspectjrt.jar放在libs目录下然后在Moudle的gradle 中配置
dependencies{. implementation files('libs/aspectjrt.jar')}
buildscript { repositories { mavenCentral() } dependencies { classpath 'org.aspectj:aspectjtools:1.8.8' classpath 'org.aspectj:aspectjweaver:1.8.8' } } 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; } } } }
2.写一个注解类
@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface BehaviorTrace { String value(); }
3.
@Aspect public class BehaviorTraceAspect { private static final String TAG = "BehaviorTraceAspect"; // 定义切面的规则 // 就是原来那些应用注释的地方要用到切面 // execution(注释名 助使用的地方) @Pointcut("execution(@com.test.chenmiaojun.aoptest.annotion.BehaviorTrace * *(..))") public void methodAnnotatedWithBehaviorTrace(){} // 对进入切面的地方进行处理 // @Around 在切入点前后都运行 // @Before 在切入点之前运行 // @After 在切入点之后运行 @Around("methodAnnotatedWithBehaviorTrace()") public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); String className = methodSignature.getDeclaringType().getName(); String methodName = methodSignature.getName(); String funName = methodSignature.getMethod().getAnnotation(BehaviorTrace.class).value(); // 统计时间 long begin = System.currentTimeMillis(); Object result = joinPoint.proceed(); long duration = System.currentTimeMillis() - begin; Log.d(TAG, String.format("功能:%s,%s类的%s方法执行了,用时%d ms",funName,className,methodName,duration)); return result; } }
4 接下来就是使用
@BehaviorTrace("test")
可以看到 我们可以拿到这个方法的时间,方法名等等。