Kiba518

Kiba518

三线城市架构师一枚。

Fork me on GitHub

Android里使用AspectJ实现双击自定义注解

创建注解

首先创建一个双击注解。

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
​
/**
 * <pre>
 *     desc   : 双击
 *     author : 刘金
 *     time   : 2023/2/28 下午6:35
 * </pre>
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DoubleClick {
​
    long DEFAULT_INTERVAL_MILLIS = 1000;
​
    /**
     * @return 快速点击的间隔(ms),默认是1000ms
     */
    long value() default DEFAULT_INTERVAL_MILLIS;
}

使用AspectJ进行埋点

为了在 Android 使用 AOP 埋点需要引入 AspectJX,在项目根目录的 build.gradle 下加入:

classpath 'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.0'

然后,在 app 目录下的 build.gradle 下加入:

apply plugin: 'android-aspectjx'
implement 'org.aspectj:aspectjrt:1.8.+'
    
// AspectJX默认会处理所有的二进制代码文件和库,为了提升编译效率及规避部分第三方库出现的编译兼容性问题,
// AspectJX提供include,exclude命令来过滤需要处理的文件及排除某些文件(包括class文件及jar文件)。
// 常用排除一些目录下的代码
aspectjx {
    exclude 'versions.9', 'androidx', 'com.google', 'com.taobao', 'com.ut'
}

注:埋点后有时候需要重新编译,不然即使代码正确也提示异常。

然后编写双击埋点的AspectJ类。

/**
 * <pre>
 *     desc   : 双击
 *     author : 刘金
 *     time   : 2023/2/28 下午6:35
 * </pre>
 */
@Aspect
public class DoubleClickAspectJ {
​
    @Pointcut("within(@com.weiguo.collection.annotation.DoubleClick *)")
    public void withinAnnotatedClass() {
    }
​
    @Pointcut("execution(!synthetic * *(..)) && withinAnnotatedClass()")
    public void methodInsideAnnotatedType() {
    }
​
    @Pointcut("execution(@com.weiguo.collection.annotation.DoubleClick * *(..)) || methodInsideAnnotatedType()")
    public void method() {
    }  //方法切入点
​
    @Around("method() && @annotation(doubleClick)")//在连接点进行方法替换
    public void aroundJoinPoint(ProceedingJoinPoint joinPoint, DoubleClick doubleClick) throws Throwable {
         
        if (是双击)) {
            joinPoint.proceed();//是双击,执行原方法
        } else {
​
        }
         
    } 
}

 然后将注解@DoubleClick放到想双击触发的函数上即可。

----------------------------------------------------------------------------------------------------

注:此文章为原创,任何形式的转载都请联系作者获得授权并注明出处!
若您觉得这篇文章还不错,请点击下方的推荐】,非常感谢!

https://www.cnblogs.com/kiba/p/17246302.html

 

 

posted @ 2024-02-22 10:10  kiba518  阅读(26)  评论(0编辑  收藏  举报