Android 中使用Aspectj进行切面编程

1 说明

在Android中有时需要用到AOP编程的场景,aspectj是一个不错的选择。因此特此记录下

2 Android引入Aspectj

项目的build.gradle中引入如下配置

        //for AspectJ
        classpath 'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.4'

需要切入的模块build.gradle如下配置

apply plugin: 'android-aspectjx' // apply plugin

    //AspectJ
    api 'org.aspectj:aspectjrt:1.8.9'

接下来就可以写要切的代码了,这里以Application为例

@Aspect
public class PerformanceManager {

    private static final String TAG = "PerformanceManager";

    @Around("execution(* com.qiyei.android.AndroidApplication.on**(..))")
    public void getAndroidApplicationTime(ProceedingJoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        long time = System.currentTimeMillis();
        try {
            joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        LogManager.i(TAG, "getAndroidApplicationTime " + signature.getName() + " cost " + (System.currentTimeMillis() - time) + " ms");
    }

    @Around("call(* com.qiyei.android.AndroidApplication.**(..))")
    public void getApplicationTime(ProceedingJoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        long time = System.currentTimeMillis();
        try {
            joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        LogManager.i(TAG, "getApplicationTime " + signature.getName() + " cost " + (System.currentTimeMillis() - time) + " ms");
    }

}

基本配置完毕

你可能感兴趣的:(android,架构)