Aop切面编程

Aop原理
https://blog.csdn.net/xwh_1230/article/details/78225258

1:定义AspectJ类

@Aspect
public class PermissionAspect {

   private static final String POINTCUT_METHOD =
        "execution(@com.sankuai.moviepro.aop.injectaop.PermissionCheck * *(..))";

private static final String POINTCUT_CONSTRUCTOR =
        "execution(@com.sankuai.moviepro.aop.injectaop.PermissionCheck *.new(..))";

      @Pointcut(POINTCUT_METHOD)
public void methodAnnotatedWithPermissionCheck() {}

@Pointcut(POINTCUT_CONSTRUCTOR)
public void constructorAnnotatedPermissionCheck() {}

@Around("methodAnnotatedWithPermissionCheck() || constructorAnnotatedPermissionCheck()")
public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable {
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    Method method = methodSignature.getMethod();
    PermissionCheck auth = method.getAnnotation(PermissionCheck.class);
    String permission = auth.permission();
    int code = auth.code();

 if(MovieProPermissionUtil.checkSelfPermission(MovieProApplication.getContext(), permission)){
            return joinPoint.proceed();//有权限,则执行所拦截的方法
           } else {
               if (joinPoint.getThis() instanceof Activity) {
                  MPermissions.requestPermissions((Activity) joinPoint.getThis(), code, permission);
                  }else if (joinPoint.getThis() instanceof Fragment) {
                      MPermissions.requestPermissions((Fragment) joinPoint.getThis(), code, permission);
                  }
                  return null;//没有权限,这不做操作
            }
      }
}

2:定义注解

@Retention(RetentionPolicy.CLASS)
@Target({ ElementType.CONSTRUCTOR, ElementType.METHOD })
public @interface PermissionCheck {
     String permission();
     int code() default 0;
 }

3:使用

@PermissionCheck(permission=Manifest.permission.READ_EXTERNAL_STORAGE, code= 
ExternalStoragePermission.CODE_READ_EXTERNAL_STORAGE)
@Override
public void onChooseAlbumClick() {
    navigator.toImagePick(this, 1, true, PHOTO_PICK_REQUEST);
}

你可能感兴趣的:(Aop切面编程)