Android知识Android开发程序员

Android AOP浅析

2018-02-06  本文已影响0人  EasyLife90

AOP 是 Aspect Oriented Programming的缩写,我们意为“面向切面编程”。我们平时也称为“注解”。
我们多数用来进行用户行为的统计。废话少说,直接上码。

1.首先创建一个BehaviorTrace.java 的interface类 如下

package com.example.zkq.myapplication.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * Created by ZKQ on 2018/1/26.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface BehaviorTrace {
    String  value();
}

2.创建BehaviorAspect.java类来实现方法。

package com.example.zkq.myapplication.aspect;
import android.util.Log;
import com.example.zkq.myapplication.annotation.BehaviorTrace;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
/**
 * Created by ZKQ on 2018/1/26.
 */
@Aspect
public class BehaviorAspect {
  private final static String PATH = "execution(@com.example.zkq.myapplication.annotation.BehaviorTrace * *(. .))";
    @Pointcut(PATH)
    public void methodWithBehaviorTrace() {
    }
    // @Before 切入點之前执行
    //@After()  切入点之后
    //@Around 切入点之间。
    @Around("methodWithBehaviorTrace()")
    public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature= (MethodSignature) joinPoint.getSignature();
        String  className=methodSignature.getDeclaringType().getSimpleName();
        String methodName=methodSignature.getName();
        BehaviorTrace behaviorTrace=methodSignature.getMethod().getAnnotation(BehaviorTrace.class);
        String value=behaviorTrace.value();
        long begin = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long duration = System.currentTimeMillis() - begin;
        String contentStr=String.format("%s类的%s方法被执行,%s耗时%d",className,methodName,value,duration);
        Log.i("zkq",contentStr);
        return result;
    }
}

3.最后在你想要监听的事件上添加注解就ok了。

    @BehaviorTrace("视频消息")
    public void onAudio(View view) {
    SystemClock.sleep(new Random().nextInt(500));
    }
    @BehaviorTrace("语音消息")
    public void onVoice(View view) {
  SystemClock.sleep(new Random().nextInt(500));
    }

4.最重要的一部是配置你项目build.gradle。

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.aspectj:aspectjtools:1.8.13'
        classpath 'org.aspectj:aspectjweaver:1.8.13'
    }
}


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.5",
                         "-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;
            }
        }
    }
}

5. jar下载地址 aspectjrt.jar

初次使用Markdown,之前都没用。这样写起来感觉好漂亮好整齐。处女座的我、、哈哈哈拜拜。

上一篇下一篇

猜你喜欢

热点阅读