Android AOP
参考文章
1. http://www.jianshu.com/p/2779e3bb1f14
2. https://juejin.im/entry/588d45365c497d0056c471ef
3. http://blog.csdn.net/njuzhou/article/details/1619406
用法
1. 完整写法:
@Pointcut("execution(* com.brothergang.demo.aop.TestActivity.onCreate(..)) ||"
+ "execution(* com.brothergang.demo.aop.TestActivity.onStart(..)) ||"
+ "execution(* com.brothergang.demo.aop.TestActivity.onResume(..)) ||"
+ "execution(* com.brothergang.demo.aop.TestActivity.onDestroy(..)) ||"
+ "execution(* com.brothergang.demo.aop.TestActivity.onPause(..))"
)
public void logForActivity() {
}
//注意,这个函数必须要有实现,否则Java编译器会报错
/*
@Before:这就是Before的advice,对于after,after -returning,和after-throwing。对于的注解格式为
@After,@AfterReturning,@AfterThrowing。Before后面跟的是pointcut名字,然后其代码块由一个函数来实现。
比如此处的log。
*/
@Before("logForActivity()")
public void log(JoinPoint joinPoint) {
String tag = ((TestActivity) joinPoint.getTarget()).tag;
Log.e(TAG, "AOP 埋点:" + joinPoint.toShortString() + "==" + tag);
}
2. 精简写法
/** * 精简写法 */ @Around("execution(* android.view.View.OnClickListener.onClick(..))") public void logClickEvent(ProceedingJoinPoint joinPoint) { Log.e(TAG, "AOP 埋点:" + joinPoint.toShortString()); try { joinPoint.proceed(); } catch (Throwable throwable) { throwable.printStackTrace(); } }
3.获取参数
private void debugLog(String loginfo) { LogUtils.i(this.getClass(), loginfo); }
@Around("execution(* debugLog(..))")
public void debugLog(ProceedingJoinPoint joinPoint) {
// joinPoint.getArgs() //获取getargs 获取参数
Log.e(TAG, "AOP 埋点:" + joinPoint.toShortString());
try {
joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
4. 获取Annatation参数
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyAnnatation { String value() default "code"; }
@MyAnnatation(value = "ourself") private void aopAnnatation() { LogUtils.i(this.getClass(), "11111111111"); }
@Around("execution(* aopAnnatation(..))&&@annotation(params)")
public void aopAnnatation(ProceedingJoinPoint joinPoint, MyAnnatation params) {
// joinPoint.getArgs() //获取getargs 获取参数
Log.e(TAG, "AOP 埋点:" + joinPoint.toShortString() + "--" + params.value().toString());
try {
joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
Demo: https://github.com/dengshaomin/AndroidDemo/tree/master/demo-android-aop-master
转载标明出处:http://www.cnblogs.com/no-coding
有问题邮件 nocoding@163.com QQ:418244382

浙公网安备 33010602011771号