Android AOP

參考文章

1. http://www.jianshu.com/p/2779e3bb1f14android

2. https://juejin.im/entry/588d45365c497d0056c471efgit

3. http://blog.csdn.net/njuzhou/article/details/1619406github

用法

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. 精簡寫法this

/**
     * 精簡寫法
     */
    @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.獲取參數spa

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參數.net

@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-masterdebug

相關文章
相關標籤/搜索