androidStudio中使用 AspectJ

关于 AOP 的详细介绍请参考 深入理解Android之AOP

本文主要介绍 怎么在 AndroidStudio 中使用 AspectJ

 1 . 在android studio 中新建一个项目 MyApplication



2. 在 app 目录下 的 build.gradle 中完成如下配置:

apply plugin: 'com.android.application'

import org.aspectj.bridge.IMessage
import org.aspectj.bridge.MessageHandler
import org.aspectj.tools.ajc.Main

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

repositories {
    mavenCentral()
}

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.yqqyang.myapplication"
        minSdkVersion 23
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'

    compile 'org.aspectj:aspectjrt:1.8.9'
}

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;
            }
        }
    }
}

如此 gradle 的配置就算完成了,接下来要编写代码了

3.在MainActivity 的同级目录下创建 AspectMethod.java 文件.



4. 在 AspectMethod.java 中编写代码(下方代码中 com.example.yqqyang.myapplication.MainActivity 请换成 自己的包名类名):

package com.example.yqqyang.myapplication;

import android.util.Log;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

/**
 * @author YQQ.yang.
 * @date 2017/5/10 9:26.
 */

@Aspect
public class AspectMethod {

    private static final String TAG = "QQ";

    @Before("execution(* com.example.yqqyang.myapplication.MainActivity.*(..))")
    public void beforeMethodExe(JoinPoint joinPoint) {
        Log.e(TAG, "before----- > " + System.currentTimeMillis());
    }

    @After("execution(* com.example.yqqyang.myapplication.MainActivity.*(..))")
    public void afterMethodExe(JoinPoint joinPoint) {
        Log.e(TAG, "after ----- > " + System.currentTimeMillis());
    }

}

5. 运行 app moudle

在 logcat 会有如下输出:



打开 app/build/intermediates/classes/debug/com/example/yqqyang/myapplication/MainActivity.class 文件,会发现 编译后的 MainActivity 里面的代码已经改变了:





















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值