Android AOP编程

用于权限处理,日志,埋点,单击处理、网络检测等等场景。

Aspectj将代码生成字节码插入到需要的地方

Project的build.gradle配置

  1. // AOP 配置插件:https://github.com/HujiangTechnology/gradle_plugin_android_aspectjx
  2. classpath 'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.10'

依赖引入

  1. // AOP 插件库:https://mvnrepository.com/artifact/org.aspectj/aspectjrt
  2. api 'org.aspectj:aspectjrt:1.9.5'

app.gradle配置

  1. apply plugin: 'android-aspectjx'
  2. // AOP 配置
  3. aspectjx {
  4. // 排除一些第三方库的包名(Gson、 LeakCanary 和 AOP 有冲突)
  5. // 否则就会起冲突:ClassNotFoundException: Didn't find class on path: DexPathList
  6. exclude 'androidx', 'com.google', 'com.squareup', 'com.alipay', 'com.taobao', 'org.apache','org.jetbrains.kotlin',
  7. "module-info", 'versions.9'
  8. }

切面类

被@Aspect注解修饰的类,实现代码添加的地方

  • 定义入口
  1. /**
  2. * 方法切入点
  3. */
  4. @注解 单击 返回值类型 类名.函数名(参数)
  5. @Pointcut("execution(@com.yhj.lib_base.aop.SingleClick * *(..))")
  6. public void method() {
  7. }
  8. /**
  9. * 定义入口
  10. * @注解 访问权限 返回值类型 类名.函数名(参数)
  11. * ..表示参数不限定
  12. * 注解方法传值,通过
  13. */
  14. @Pointcut("execution(@com.yhj.module_home.aspectj.annotation.PermissionNeed * * (..)) && @annotation(permissionNeed) ")
  15. public void requestPermission(PermissionNeed permissionNeed){
  16. }
  1. /**
  2. * 变量必须一样
  3. * @Around 下面两种写法相同,规范是第一种
  4. * @Around 表示替换方法代码,但是如果想要执行可以通过 joinPoint.proceed();
  5. * 不支持和After()、Before()一起使用
  6. */
  7. // @After()
  8. // @Before()
  9. @Around("requestPermission(permissionNeed)")
  10. // @Around("execution(@com.yhj.module_home.aspectj.annotation.PermissionNeed * * (..)) && @annotation(permissionNeed) ")
  11. public void aroundJoinPoint( ProceedingJoinPoint joinPoint,PermissionNeed permissionNeed){
  12. //实现功能
  13. Object obj = joinPoint.getThis();
  14. Context context= (Context) obj;
  15. }