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

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章