Android 中使用 Aspectj 限制快速点击
在AspectJ 在 Android 中的使用中,介绍了 Aspectj 的基本知识及其在 Android 中的基本使用,在这篇将会介绍如何使用 Aspectj 在 Android 中限制快速点击
[原文原创]Android 中使用 Aspectj 限制快速点击
1. 配置依赖
建立 clicklimt 的 lib,添加对 Aspect 的依赖,之前我们要做很多的配置工作,沪江的开源库 gradle_plugin_android_aspectjx 已经帮我们弄了,省了很多工作。
在根项目的 build.gradle 配置
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.3.2'
// 添加 hujiang.aspectjx
classpath 'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.4'
classpath 'com.jakewharton:butterknife-gradle-plugin:9.0.0-rc2'
}
}
在 app 工程的 build.gradle 中使用 AspectJX 插件
apply plugin: 'com.android.application'
apply plugin: 'android-aspectjx' // 使用 AspectJX 插件
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.yxhuang.aspectjlimitclickdemo"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
// Butterknife requires Java 8.
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
aspectjx {
//指定只对含有关键字'universal-image-loader', 'AspectJX-Demo/library'的库进行织入扫描,忽略其他库,提升编译效率
// includeJarFilter 'universal-image-loader', 'AspectJX-Demo/library'
// excludeJarFilter '.jar'
// ajcArgs '-Xlint:warning'
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation project(':clicklimit')
implementation 'com.jakewharton:butterknife:9.0.0-rc1'
annotationProcessor 'com.jakewharton:butterknife-compiler:9.0.0-rc1'
}
在 clicklimt 库的 build.gradle 中添加 aspectj 依赖
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
api 'org.aspectj:aspectjrt:1.8.9'
}
2. 具体的处理
1. 建立 ClickLimit 注解
我们会对整个项目中的点击事件做点击限制,如果不需要限制的方法,可以设置 value = 0 即可, 我们默认设置为 500 毫秒。
@Target({
ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ClickLimit {
int value() default 500;
}
2. 选择 Pointcut
我们这里选择 View#setOnClickListener 作为切入点
// View#setOnClickListener
private static final String POINTCUT_ON_VIEW_CLICK =
"execution(* android.view.View.OnClickListener.onClick(..))";
对 Joint 的处理
private void processJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable