使用AOP的aspect来观察android的生命周期

来源:互联网 发布:迅雷会员获取软件 编辑:程序博客网 时间:2024/05/20 12:49

主要的目标是不用在activity代码中写日志记录onxxxx函数,通过AOP的方式了解app运行的信息。

参考如下两个人的项目

https://fernandocejas.com/2014/08/03/aspect-oriented-programming-in-android/

http://blog.csdn.net/woshimalingyi/article/details/51519851#insertcode

主要的工作:

第一部分是空的main activity,只需要修改build.gradle。

第二部分是aspect的library,需要编写AOP的代码,修改build.gradle。

代码如下:

https://github.com/boystray/MyApplication


这种方式的AOP是在编译的时候使用ajc将aspect代码编织到android代码中。具体的编译原理参考

https://stackoverflow.com/questions/26802394/running-aspectj-causes-nosuchmethoderror-aspect-aspectof


如果android运行的时候报错java.lang.NoSuchMethodError: com.xxx.xxx.TraceAspect.aspectOf

这是因为AOP没有正确的编译


The weaver would be responsible for adding the aspectOf() method. Although your annotation style aspects will compile fine with javac, they must be 'finished off' by aspectj at some point to introduce the infrastructure methods that support weaving. If you were load-time weaving this is done as the aspects are loaded but if you are compile time or post-compile time weaving then you need to get them to ajc some other way. If you have a library built like this:

javac MyAspect.java
jar -cvMf code.jar MyAspect.class

then you'd need to get that jar woven to 'complete' the aspects:

ajc -inpath code.jar -outjar myfinishedcode.jar

Or you could just use ajc instead of javac for the initial step

ajc MyAspect.java

Or you could do it at the point the aspects are being applied to your other code:

ajc <myAppSourceFiles> -inpath myaspects.jar

By including myaspects.jar on the inpath, any aspect classes in there will be 'finished off' as part of this compile step and the finished versions put alongside your compiled application source files. Note this is different to if you used the aspect path:

ajc <myAppSourceFiles> -aspectpath myaspects.jar

Here the aspects on the aspect path are applied to your code but they are only loaded from there, they are not finished off and so you wouldn't get the finished versions alongside your compiled application source files.


原创粉丝点击