参考了:https://www.jianshu.com/p/4cf5cb9e4b99
项目gradle
在plugins上面添加buildscript 如下:
buildscript {
dependencies {
classpath 'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.10'
}
}
plugins {
id 'com.android.application' version '7.1.3' apply false
id 'com.android.library' version '7.1.3' apply false
id 'org.jetbrains.kotlin.android' version '1.7.0' apply false
}
task clean(type: Delete) {
delete rootProject.buildDir
}
这里application和library的版本要改成7.1.3,我一开始用7.2.1会报下面的错。估计是兼容性问题
A problem occurred evaluating project ':app'.
> Failed to apply plugin 'android-aspectjx'.
> No such property: FD_INTERMEDIATES for class: com.android.builder.model.AndroidProject
app.bulid.gradle的plugins同级下面添加apply plugin: 'android-aspectjx'
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
apply plugin: 'android-aspectjx'
添加依赖
implementation 'org.aspectj:aspectjrt:1.9.5'
添加不扫描的包 跟android同级
aspectjx {
// 排除一些第三方库的包名(Gson、 LeakCanary 和 AOP 有冲突)
// 否则就会起冲突:ClassNotFoundException: Didn't find class on path: DexPathList
exclude 'androidx', 'com.google', 'com.squareup', 'com.alipay', 'com.taobao',
'org.apache',
'org.jetbrains.kotlin',
"module-info", 'versions.9'
}
特别要排除 'versions.9',不然kotlin编译时报错 报错 zip file is empty,
zip file is empty · Issue #286 · HujiangTechnology/gradle_plugin_android_aspectjx · GitHub
测试代码
@Aspect
class MethodAspect {
// 此处指定一个切点,后面括号中的是切点表达式(个人理解:其表达的就是一个join point),详细见Aspect基本语法
@Pointcut("call(* com.test.myapplication.MainActivity.haha(..))")
private fun callMethod() {
}
//表示一个通知,类型为Before并指定切点为上面callMethod方法所表示的那个切点
@Before("callMethod()")
fun beforeMethodCall(joinPoint: JoinPoint) {
Log.e("haha", "before->" + joinPoint.target.toString()) //织入的代码
}
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<TextView>(R.id.text).setOnClickListener {
haha()
}
}
fun haha() {
Log.d("haha", "haha")
}
}
打印
before->com.test.myapplication.MainActivity@4b5a4b
haha