一款基于沪江AOP插件支持>=gradle7.3.3<=8.0版
2022-08-26 本文已影响0人
TMAC_EAH
0x0.配置小云孙 链接
plugins {
...
id("io.github.xiaoyun-sun.aspectjx") version "1.0.0"
}
>> settings.gradle
pluginManagement {
repositories {
maven { url "https://plugins.gradle.org/m2/" }
mavenLocal()
gradlePluginPortal()
google()
mavenCentral()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
maven { url "https://plugins.gradle.org/m2/" }
mavenLocal()
google()
mavenCentral()
}
}
//buildscript {
// repositories {
// maven { url "https://plugins.gradle.org/m2/" }
// mavenLocal()
// }
//
// dependencies {
// classpath("io.github.xiaoyun-sun.aspectjx:1.0.0")
// }
//}
0x1.app/build.gralde配置如下
apply plugin: 'io.github.xiaoyun-sun.aspectjx'
// android同级别
// 不支持 include exclude 同时使用
// 支持日志输出到文件,便与排查错误
// 支持gradle7.+
aspectjx {
logEnabled true // aop输出日志
enabled true // 启用/关闭
// include 扫描指定包名下,匹配包名生效
include 'androidx.*'
include 'android.app.*'
include 'com.android.*'
include 'com.amap.map3d.*'
}
android {
...
}
0x2.编写防抖代码
package com.amap.map3d.aspectj;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface SingleClick {
/**
* 最小间隔时间,单位 Millis
*
* @return interval
*/
long interval() default 600;
}
@Keep
@Aspect
public class SingleClickAspect {
private static final String TAG = "SingleClickAspect";
private static long mLastClickTime = 0L;
private static String mLastSignature;
@Pointcut(value = "execution(@com.amap.map3d.aspectj.SingleClick * *(..)) && @annotation(ann)", argNames = "ann")
public void methodAnnotated(SingleClick ann) {
}
public static boolean equals(final CharSequence s1, final CharSequence s2) {
if (s1 == s2) {
return true;
}
int length;
if (s1 != null && s2 != null && (length = s1.length()) == s2.length()) {
if (s1 instanceof String && s2 instanceof String) {
return s1.equals(s2);
} else {
for (int i = 0; i < length; i++) {
if (s1.charAt(i) != s2.charAt(i)) {
return false;
}
}
return true;
}
}
return false;
}
@Around(value = "methodAnnotated(ann)", argNames = "joinPoint,ann")
public void aroundJoinPoint(ProceedingJoinPoint joinPoint, SingleClick ann) throws Throwable {
long currentTime = System.currentTimeMillis();
long interval = ann.interval();
String currentSignature = joinPoint.getSignature().toString();
// 过滤掉指定间隔内的对同一个方法的连续调用,默认600毫秒
if (currentTime - mLastClickTime > interval
|| !equals(currentSignature, mLastSignature)) {
mLastClickTime = currentTime;
joinPoint.proceed();
} else {
Log.d(TAG, "ignored method { " + joinPoint.toShortString() + " } quick call interval=" + interval);
}
Log.d(TAG, "ignored method { " + joinPoint.toShortString() + " } quick call interval=" + interval);
mLastSignature = currentSignature;
}
}
0x3.咋用?
mTest.setOnClickListener(new View.OnClickListener() {
@Override
@SingleClick(interval = 1000)
public void onClick(View v) {
Log.d("SingleClickAspect", "手抖么?");
}
});