Android开发经验谈Android开发Android技术知识

小试牛刀--Android AOP(面向切面编程)开发

2018-05-03  本文已影响403人  DDDDLU

AOP面向切面编程开发

说明

定义

把某方面的功能提出来与一批对象进行隔离,这样与一批对象之间降低耦合性,就可以对某个功能进行编程。

应用
AOP实现流程

是一个面向切面编程框架,它有专门的编译器用来生成java 字节 码,生成class文件。我们使用这个框架后编译字节码的工具不再试javac

下载aspectj 地址: http://www.eclipse.org/aspectj/downloads.php
下载aspectj的adt地址: http://www.eclipse.org/ajdt/downloads/#43zips
aspectJ 写法: http://fernandocejas.com/2014/08/03/aspect-oriented-programming-in-android/

编码实现

此处我们使用AOP实现方法耗时统计

Android studio添加AspectJ框架

//需要添加
import org.aspectj.bridge.IMessage
import org.aspectj.bridge.MessageHandler
import org.aspectj.tools.ajc.Main

apply plugin: 'com.android.application'

buildscript {
    repositories {
        mavenCentral()
    }
    //需要添加
    dependencies {
        classpath 'org.aspectj:aspectjtools:1.8.9'
        classpath 'org.aspectj:aspectjweaver:1.8.9'
    }
}
repositories {
    mavenCentral()
}
android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.siqiyan.lightlu.aoptest"
        minSdkVersion 23
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
//需要添加
final def log = project.logger
final def variants = project.android.applicationVariants
variants.all { variant ->
    if (!variant.buildType.isDebuggable()) {
        log.debug("Skipping non-debuggable build type '${variant.buildType.name}'.")
        return;
    }

    JavaCompile javaCompile = variant.javaCompile
    javaCompile.doLast {
        String[] args = ["-showWeaveInfo",
                         "-1.8",
                         "-inpath", javaCompile.destinationDir.toString(),
                         "-aspectpath", javaCompile.classpath.asPath,
                         "-d", javaCompile.destinationDir.toString(),
                         "-classpath", javaCompile.classpath.asPath,
                         "-bootclasspath", project.android.bootClasspath.join(File.pathSeparator)]
        log.debug "ajc args: " + Arrays.toString(args)

        MessageHandler handler = new MessageHandler(true);
        new Main().run(args, handler);
        for (IMessage message : handler.getMessages(null, true)) {
            switch (message.getKind()) {
                case IMessage.ABORT:
                case IMessage.ERROR:
                case IMessage.FAIL:
                    log.error message.message, message.thrown
                    break;
                case IMessage.WARNING:
                    log.warn message.message, message.thrown
                    break;
                case IMessage.INFO:
                    log.info message.message, message.thrown
                    break;
                case IMessage.DEBUG:
                    log.debug message.message, message.thrown
                    break;
            }
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    //需要添加
    compile files('libs/aspectjrt.jar')
    implementation files('libs/aspectjrt.jar')
}

创建注解类



@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BehaviorTimeTrace {
    String value();
}

添加标记点(在需要处理的方法使用驻点)

/**
     * 语音的模块
     *
     * @param view
     */
    public  void shake(View view)
    {
        long beagin=System.currentTimeMillis();

        //摇一摇的代码逻辑
        
        SystemClock.sleep(3000);
        Log.i(TAG,"摇到一个妹子,距离500公里");
       

        Log.i(TAG,"消耗时间:  "+(System.currentTimeMillis()-beagin)+"ms");
    }

   /**
     * 摇一摇的模块
     *
     * @param view
     */
  @BehaviorTimeTrace("摇一摇")
    public void shake(View view){
        SystemClock.sleep(3000);
        Log.i(TAG,"摇到一个妹子,距离500公里");
    }

AOP处理

具体处理思想分为下面几步:

详细实现:

@Aspect
public class BehaviorTimeAspect {
    SimpleDateFormat format =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static  final String TAG="AOPDemo";
    //比作切蛋糕,如何切蛋糕
    //第一步获切点,即获得想要处理方法:* *代表所有方法,(..)代表所有参数,这里可以根据具体的方法类型来做处理
//    @Pointcut("execution(@com.siqiyan.lightlu.aoptest.BehaviorTimeTrace  * *(..))")
    @Pointcut("execution(@com.siqiyan.lightlu.aoptest.BehaviorTimeTrace  * *(..))")
    public void insertBehavior(){

    }

     //对于想好切的蛋糕,如何吃
    //第二步处理获取的切点
    @Around("insertBehavior()")
    public Object dealPoint(ProceedingJoinPoint proceedingJoinPoint)throws Throwable{
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        //获取标记的方法
        BehaviorTimeTrace annotation = signature.getMethod().getAnnotation(BehaviorTimeTrace.class);
        //获取标记方法名
        String value = annotation.value();

        Log.i(TAG,value+"开始使用的时间:   "+format.format(new Date()));
        long beagin=System.currentTimeMillis();
        Object proceed=null;

        try {
            //执行方法
            proceed = proceedingJoinPoint.proceed();
        }catch (Exception e){

        }
        Log.i(TAG,"消耗时间:  "+(System.currentTimeMillis()-beagin)+"ms");

        return proceed;

    }


}
@Pointcut("execution(@com.siqiyan.lightlu.aoptest.BehaviorTimeTrace  * *(..))")
    public void insertBehavior(){

    }
//关联上面的方法
  @Around("insertBehavior()")
    public Object dealPoint(ProceedingJoinPoint proceedingJoinPoint)throws Throwable{
    //固定写法,用于获取标记点
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        //获取标记的方法
        BehaviorTimeTrace annotation = signature.getMethod().getAnnotation(BehaviorTimeTrace.class);
        //获取标记方法名,即我们注解传的参数
        String value = annotation.value();

        Log.i(TAG,value+"开始使用的时间:   "+format.format(new Date()));
        long beagin=System.currentTimeMillis();
        Object proceed=null;

        try {
            //执行我们注解的方法
            proceed = proceedingJoinPoint.proceed();
        }catch (Exception e){

        }
        Log.i(TAG,"消耗时间:  "+(System.currentTimeMillis()-beagin)+"ms");

        return proceed;

    }

效率

测试如下:


image

可以看到使用AspectJ 框架编译时生成的字节码,所以处理逻辑会占用更少的时间。查看编译的源码我们可以看到生成的class文件里面包含注解的处理。

Demo源码

源码 AOPTest

上一篇 下一篇

猜你喜欢

热点阅读