Android AspectJ的使用

1.项目gradle导入

 dependencies {
       ...
        classpath 'org.aspectj:aspectjtools:1.8.10'
        classpath 'org.aspectj:aspectjweaver:1.8.8'
    }

2.App 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;
            }
        }
    }
}

3.App 导入依赖

 implementation 'org.aspectj:aspectjrt:1.8.10'

4.受欢迎按键监听

package com.ztf.my;

import android.util.Log;
import android.view.View;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class MyClick {
    private static final String TAG = "ztfLog";

    @Pointcut("execution(* android.view.View.OnClickListener.onClick(..))")
    public void clickMethod() {
    }

    @Around("clickMethod()")
    public void onClickMethodAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        View view = null;
        for (Object arg : args) {
            if (arg instanceof View) {
                view = (View) arg;
            }
        }
        String resEntrName = null;
        String resName = null;
        if (view != null) {
            resEntrName = view.getContext().getResources().getResourceEntryName(view.getId());
            resName = view.getContext().getResources().getResourceName(view.getId());
        }
        joinPoint.proceed();
        Log.d(TAG, "After onclick:" + "控件名称:" + resEntrName + "控件ID:" + resName);
    }
}

自定义注解,及注解实现类

package com.ztf.my;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface WatcherMethod {
    String MyMsg() default "";
}

package com.ztf.my;

import android.util.Log;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

@Aspect
public class MyWatch {
    private String myMsg;

    @Pointcut("execution(@com.ztf.my.WatcherMethod * *(..))")
    private void doMethod() {

    }

    @Around("doMethod()")
    public void doWatchMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Log.d("ztfLog","1111111111111111");
        if (signature == null){
            return;
        }
        String className = signature.getDeclaringType().getSimpleName();
        String methodName = signature.getName();
        Method method = signature.getMethod();
        Method realMethod = joinPoint.getTarget().getClass().getDeclaredMethod(methodName, method.getParameterTypes());
        WatcherMethod watcherMethod = realMethod.getAnnotation(WatcherMethod.class);
        if (watcherMethod != null){
            myMsg = watcherMethod.MyMsg();
        }
        long begin = System.currentTimeMillis();
        joinPoint.proceed();
        long end = System.currentTimeMillis();
        Log.d("ztfLog",String.format("方法执行时间监控:%s 类 - %s 方法 - 描述:%s 用时:%d",className,methodName,myMsg,end - begin));
    }
}

在方法上添加自定义注解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值