一.前言:AOP(Aspect Orented Programming):面向切面编程,通过ajc编译器把java文件编译为加工过的class文件,个人感觉就是定点插入代码。
二.应用场景:权限申请,日志统计,行为统计,性能检测。
三.项目配置:这里我放在公共模块中
(1)project中添加:
classpath 'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.4'
(2)主module中
apply plugin: 'com.hujiang.android-aspectjx'
***
implementation 'org.aspectj:aspectjrt:1.8.13'
(3)common module中
apply plugin: 'com.hujiang.android-aspectjx'
***
api 'org.aspectj:aspectjrt:1.8.13'
四.简单例子一:按钮两秒内不可再按
(1)声明注解类:
package aop
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class AopOnclick (val value:Long = 2000){
}
(2)功能类:
package aop
import android.os.SystemClock
/*
两次间隔是否超过规定时间
*/
object AopClickUtil {
private var mLastClickTime:Long = 0
fun isFastDoubleClick(intervalMillis:Long):Boolean{
val time = SystemClock.elapsedRealtime()
val tiemInterval = Math.abs(time- mLastClickTime)
return if(tiemInterval<intervalMillis){
true
}else{
mLastClickTime = time
false
}
}
}
(3) 切面类:
@Aspect
class AopClickAspect{
/*
定义入口 @注解 访问权限 返回值类型 类名.函数名(参数)
*/
@Pointcut("execution(@aop.AopOnclick * *(..))")
fun methodAnnotated(){
}
@Around("methodAnnotated()")
@Throws(Throwable::class)
fun aroundJoinPoint(joinPoint: ProceedingJoinPoint){
val methodSignature = joinPoint.signature as MethodSignature
val method = methodSignature.method