AOP在安卓中主要是指把某一方面的一些功能提取出来与一批对象进行隔离,提取之后我们就可以对某个单方面的功能进行编程,如请求网络时,需要先判断网络是否连通,或MVP中Model是否为空等.
1、下载jar包
前往aspectj下载jar包,然后安装,一直点击下一步(前提配置好jdk)
asppectj2.将aspectj安装目录下lib中的aspectjrt.jar加入项目下
3.在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'
classpath 'org.aspectj:aspectjweaver:1.8.9'
}
}
repositories {
mavenCentral()
}
android {
//.......
}
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 {
//.....
compile files('libs/aspectjrt.jar')
}
使用
1.添加注解,所有需要检查的方法均使用CheckNet进行注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)//放在方法上
public @interface CheckNet {
}
2.创建切面,处理切面
package com.loser.active.myapplication;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
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 Active_Loser on 2018/9/19
* Content:处理网络请求的切点
*/
@Aspect
public class SectionAspect {
/**
* 找到处理的节点
* * *(..)表示处理所有的方法
*/
@Pointcut("execution(@com.loser.active.myapplication.CheckNet * *(..))")
public void checkNetAspect() {
}
/**
* 处理切面
*
* @Around() 表示处理那个点
*/
@Around("checkNetAspect()")
public Object checkNet(ProceedingJoinPoint joinPoint) throws Throwable {
Log.i("LOG", "checkNet: ss");
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
CheckNet checkNet = signature.getMethod().getAnnotation(CheckNet.class);
if (null != checkNet) {
if (!isNetworkAvailable(MyApplication.getmInstance())) {
return null;
}
}
return joinPoint.proceed();
}
/**
* 检查当前网络是否可用
*
* @return
*/
private static boolean isNetworkAvailable(Context context) {
// 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
// 获取NetworkInfo对象
NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
if (networkInfo != null && networkInfo.length > 0) {
for (int i = 0; i < networkInfo.length; i++) {
// 判断当前网络状态是否为连接状态
if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
3.在需要检查网络的方法上进行注解,
@CheckNet
public void getData(){
Toast.makeText(this, "获取数据", Toast.LENGTH_SHORT).show();
}
网友评论