发现网上有很多权限请求框架,所以我自己也来写一个aop的请求框架,好处是不入侵原有代码达到解耦的效果。
1、首先在projcet的build中添加
classpath 'org.aspectj:aspectjtools:1.8.9'
之后在module的build添加如下配置
dependencies {
......
compile 'org.aspectj:aspectjrt:1.8.9'
}
android.applicationVariants.all { variant ->
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)]
MessageHandler handler = new MessageHandler(true);
new Main().run(args, handler)
def log = project.logger
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:
case IMessage.INFO:
log.info message.message, message.thrown
break;
case IMessage.DEBUG:
log.debug message.message, message.thrown
break;
}
}
}
}
添加注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Permission {
String[] value();
}
核心代码
package com.example.aoppermission;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
/**
* Created by yang2 on 2017/8/3.
*/
@Aspect
public class PermissionAspect {
@Around("execution(@com.example.aoppermission.Permission * *(..)) && @annotation(permission)")
public void aroundJoinPoint(final ProceedingJoinPoint joinPoint, final Permission permission) throws Throwable {
PermissionUtil.requestPermissionsResult(MainActivity.mainActivity, 1, permission.value()
, new PermissionUtil.OnPermissionListener() {
@Override
public void onPermissionGranted() {
try {
joinPoint.proceed();//获得权限,执行原方法
} catch (Throwable e) {
e.printStackTrace();
}
}
@Override
public void onPermissionDenied() {
PermissionUtil.showTipsDialog(MainActivity.mainActivity);
}
});
}
}
就这样权限请求框架及就搭好了
- GitHub项目地址,欢迎fork或star,提出宝贵意见https://github.com/AndroidCrow/AopPermission