android 面向切面(AOP)编程简例

28 阅读2分钟

jcenter()

mavenCentral()

}

dependencies {

classpath 'com.android.tools.build:gradle:2.3.3'

classpath 'org.aspectj:aspectjtools:1.9.1'

classpath 'org.aspectj:aspectjweaver:1.9.1'

}

}

allprojects {

repositories {

jcenter()

maven { url 'jitpack.io' }

mavenCentral()

}

}

  • 在mudle的build.gradle中配置,注意一定是mudle中,lib中报错

import org.aspectj.bridge.IMessage

import org.aspectj.bridge.MessageHandler

import org.aspectj.tools.ajc.Main

这里的javaCompile.doLast配置和aspectj对应,我这里是1.9.1版本

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.9",

"-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

}

}

}

}

我的整个mudle配置页面如下:

apply plugin: 'com.android.application'

import org.aspectj.bridge.IMessage

import org.aspectj.bridge.MessageHandler

import org.aspectj.tools.ajc.Main

android {

compileSdkVersion 26

buildToolsVersion "26.0.2"

defaultConfig {

applicationId "tsou.cn.zidinyidemo"

minSdkVersion 15

targetSdkVersion 26

versionCode 1

versionName "1.0"

testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

}

sourceSets {

main {

jniLibs.srcDirs = ['libs']

}

}

buildTypes {

release {

minifyEnabled false

proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

}

}

}

repositories {

flatDir {

dirs 'libs'

}

}

dependencies {

compile fileTree(include: ['*.jar'], dir: 'libs')

androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {

exclude group: 'com.android.support', module: 'support-annotations'

})

//noinspection GradleCompatible

compile(name: 'hxgioc', ext: 'aar')

// compile project(':lib_hxgioc')

compile project(':lib_recycleview')

compile 'com.android.support:appcompat-v7:27.0.2'

compile 'com.android.support.constraint:constraint-layout:1.0.2'

testCompile 'junit:junit:4.12'

compile project(':lib_hxgaop')

compile 'com.squareup.okhttp3:okhttp:3.8.0'

}

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.9",

"-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

}

}

}

}

  • 引入aspectjrt

第一种方式

compile 'org.aspectj:aspectjrt:1.9.1'

第二种方式:

引入aspectjrt.jar

注意aspectjrt和注解放在一起

  • 检查网络注解

package tsou.cn.lib_hxgaop;

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

/**

  • Created by Administrator on 2018/6/25 0025.

*/

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

public @interface HxgAopCheckNet {

int value();

}

  • 处理切点

package tsou.cn.zidinyidemo.aop;

import android.annotation.SuppressLint;

import android.app.Activity;

import android.app.Fragment;

import android.content.Context;

import android.net.ConnectivityManager;

import android.net.NetworkInfo;

import android.view.View;

import android.widget.Toast;

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;

import tsou.cn.lib_hxgaop.HxgAopCheckNet;

/**

  • Created by Administrator on 2018/6/25 0025.

  • 处理切点

*/

@Aspect

public class CheckNetSectionAspect {

/**

  • 找到处理的切点

    • *(..))处理所有的方法
  • execution:切点的位置(包名+方法名)

*/

@Pointcut("execution(@tsou.cn.lib_hxgaop.HxgAopCheckNet * *(..))")

最后

为了方便有学习需要的朋友,我把资料都整理成了视频教程(实际上比预期多花了不少精力),由于篇幅有限,都放在了我的GitHub上,点击即可免费获取!

Androidndroid架构视频+BAT面试专题PDF+学习笔记

当程序员容易,当一个优秀的程序员是需要不断学习的,从初级程序员到高级程序员,从初级架构师到资深架构师,或者走向管理,从技术经理到技术总监,每个阶段都需要掌握不同的能力。早早确定自己的职业方向,才能在工作和能力提升中甩开同龄人。

  • 无论你现在水平怎么样一定要 持续学习 没有鸡汤,别人看起来的毫不费力,其实费了很大力,这四个字就是我的建议!!
  • 我希望每一个努力生活的IT工程师,都会得到自己想要的,因为我们很辛苦,我们应得的。

当程序员容易,当一个优秀的程序员是需要不断学习的,从初级程序员到高级程序员,从初级架构师到资深架构师,或者走向管理,从技术经理到技术总监,每个阶段都需要掌握不同的能力。早早确定自己的职业方向,才能在工作和能力提升中甩开同龄人。

无论你现在水平怎么样一定要 持续学习 没有鸡汤,别人看起来的毫不费力,其实费了很大力,没有人能随随便便成功。

加油,共勉。