AOP在Android中的使用(作为依赖库)
来源:互联网 发布:扎克拉文体测数据 手掌 编辑:程序博客网 时间:2024/06/06 00:24
上篇博客中无法对构造方法应用AOP,本篇做了修改
项目目录:
没有给出的类,在上篇博客中:
依赖库中的build.gradle文件
apply plugin: 'com.android.library'import com.android.build.gradle.LibraryPluginimport org.aspectj.bridge.IMessageimport org.aspectj.bridge.MessageHandlerimport org.aspectj.tools.ajc.Mainbuildscript { repositories { mavenCentral() } dependencies { classpath 'org.aspectj:aspectjtools:1.8.9' classpath 'org.aspectj:aspectjweaver:1.8.9' }}android { compileSdkVersion 25 buildToolsVersion "25.0.2" lintOptions { abortOnError false } defaultConfig { minSdkVersion 15 targetSdkVersion 25 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } }}android.libraryVariants.all { variant -> LibraryPlugin plugin = project.plugins.getPlugin(LibraryPlugin) JavaCompile javaCompile = variant.javaCompile javaCompile.doLast { String[] args = ["-showWeaveInfo", "-1.5", "-inpath", javaCompile.destinationDir.toString(), "-aspectpath", javaCompile.classpath.asPath, "-d", javaCompile.destinationDir.toString(), "-classpath", javaCompile.classpath.asPath, "-bootclasspath", plugin.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; } } }}dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:25.1.0' testCompile 'junit:junit:4.12'}
主工程build.gradle文件
apply plugin: 'com.android.application'import org.aspectj.bridge.IMessageimport org.aspectj.bridge.MessageHandlerimport org.aspectj.tools.ajc.Mainbuildscript { repositories { mavenCentral() } dependencies { classpath 'org.aspectj:aspectjtools:1.8.9' classpath 'org.aspectj:aspectjweaver:1.8.9' }}android { compileSdkVersion 25 buildToolsVersion "25.0.2" defaultConfig { applicationId "cn.edu.sxu.www.aopdemolibrary" minSdkVersion 15 targetSdkVersion 25 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } }}final def log = project.loggerfinal def variants = project.android.applicationVariantsvariants.all { variant -> if (!variant.buildType.isDebuggable()) { log.debug("Skipping non-debuggable build type '${variant.buildType.name}'.") return; } 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)] log.debug "ajc args: " + Arrays.toString(args) MessageHandler handler = new MessageHandler(true); new Main().run(args, handler); 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: log.warn message.message, message.thrown break; case IMessage.INFO: log.info message.message, message.thrown break; case IMessage.DEBUG: log.debug message.message, message.thrown break; } } }}dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:25.1.0' testCompile 'junit:junit:4.12' compile project(':aoplibrary')}
package cn.edu.sxu.www.aoplibrary;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.aspectj.lang.reflect.CodeSignature;import org.aspectj.lang.reflect.ConstructorSignature;import org.aspectj.lang.reflect.MethodSignature;/** * Aspect representing the cross cutting-concern: Method and Constructor Tracing. */@Aspectpublic class TraceAspect { private static final String POINTCUT_METHOD = "execution(@cn.edu.sxu.www.aoplibrary.DebugTrace * *(..))"; private static final String POINTCUT_CONSTRUCTOR = "execution(@cn.edu.sxu.www.aoplibrary.DebugTrace *.new(..))"; @Pointcut(POINTCUT_METHOD) public void methodAnnotatedWithDebugTrace() {} @Pointcut(POINTCUT_CONSTRUCTOR) public void constructorAnnotatedDebugTrace() {} @Around("methodAnnotatedWithDebugTrace() || constructorAnnotatedDebugTrace()") public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable { CodeSignature methodSignature=null; if(joinPoint.getSignature() instanceof MethodSignature)//普通方法 { methodSignature = (MethodSignature) joinPoint.getSignature(); } else if(joinPoint.getSignature() instanceof ConstructorSignature)//构造方法 { methodSignature = (ConstructorSignature) joinPoint.getSignature(); } String className = methodSignature.getDeclaringType().getSimpleName(); String methodName = methodSignature.getName(); final StopWatch stopWatch = new StopWatch(); stopWatch.start(); Object result = joinPoint.proceed(); stopWatch.stop(); DebugLog.log(className, buildLogMessage(methodName, stopWatch.getTotalTimeMillis())); return result; } /** * Create a log message. * * @param methodName A string with the method name. * @param methodDuration Duration of the method in milliseconds. * @return A string representing message. */ private static String buildLogMessage(String methodName, long methodDuration) { StringBuilder message = new StringBuilder(); message.append("Gintonic --> "); message.append(methodName); message.append(" --> "); message.append("["); message.append(methodDuration); message.append("ms"); message.append("]"); return message.toString(); }}
package cn.edu.sxu.www.aopdemolibrary;import android.os.Bundle;import android.os.SystemClock;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import cn.edu.sxu.www.aoplibrary.DebugLog;import cn.edu.sxu.www.aoplibrary.DebugTrace;import cn.edu.sxu.www.aoplibrary.StopWatch;public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private Button button; private Button button2; private Button button3; private String TAG="cn.edu.sxu.www.aopdemo.MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button= (Button) findViewById(R.id.button); button2= (Button) findViewById(R.id.button2); button3= (Button) findViewById(R.id.button3); button.setOnClickListener(this); button2.setOnClickListener(this); button3.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.button: commonTest(); break; case R.id.button2: aopTest(); break; case R.id.button3: initConstructor(); break; } } /** * 普通统计 */ private void commonTest() { final StopWatch stopWatch = new StopWatch(); stopWatch.start(); SystemClock.sleep(2000); stopWatch.stop(); DebugLog.log(TAG, "所用时长:"+stopWatch.getTotalTimeMillis()); } /** * aop 统计 */ @DebugTrace private void aopTest() { SystemClock.sleep(3000); } /** * 演示构造方法 */ private void initConstructor() {// Person person=new Person("张三",10);// person.setAge(80); Person person=new Person(); }}
activity_main.xml文件
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="官网demo,统计方法运行时间" android:id="@+id/textView" /> <Button android:text="普通方式" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginTop="42dp" android:id="@+id/button" /> <Button android:text="aop方式" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/button" android:layout_alignRight="@+id/button" android:layout_alignEnd="@+id/button" android:layout_marginTop="87dp" android:id="@+id/button2" /> <Button android:text="aop构造方法" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="69dp" android:id="@+id/button3" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /></RelativeLayout>
Person.java类
package cn.edu.sxu.www.aopdemolibrary;import android.os.SystemClock;import java.io.Serializable;import cn.edu.sxu.www.aoplibrary.DebugTrace;/** * Created by ${huozhenpeng} on 17/2/23. * Company : www.miduo.com * 演示AOP对构造方法的使用 */public class Person implements Serializable { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } @DebugTrace public void setAge(int age) { this.age = age; SystemClock.sleep(100); } public Person(String name, int age) { this.name = name; this.age = age; SystemClock.sleep(1000); } @DebugTrace public Person() { SystemClock.sleep(1500); }}
源码地址:http://download.csdn.net/detail/huohacker/9761903
0 0
- AOP在Android中的使用(作为依赖库)
- AOP在Android中的应用
- [译]依赖反转在Android中的实践
- 依赖注入在JAVA中的使用
- Android中的依赖注入:Dagger函数库的使用(一)
- 在android studio 中使用SlidingMenu依赖库方法
- 导入moudle作为自己工程的依赖库进行使用
- 导入moudle作为自己工程的依赖库进行使用
- 使用AspectJ在Android中实现Aop
- Android Studio如何导入一个Android Studio项目作为依赖使用?
- 在Android Studio中讲一个module作为另一个module的依赖
- Android 在项目中引入另一个项目作为依赖(引入Module)
- spirng aop依赖库下载
- opencv在ubuntu中的依赖库
- 归纳AOP在Android开发中的几种常见用法
- AOP编程简介及其在Spring框架中的使用
- Android 中的 AOP 编程
- Android中的AOP编程
- zoj2901【DP·二进制优化】
- 将iOS默认上下文坐标系改变为Quartz通常坐标系
- 第十四章 Spring集成测试
- swift 3.0 哈希sha1方法
- 类型转换小细节
- AOP在Android中的使用(作为依赖库)
- CCCC练习 5-10树的遍历
- 基于蒙特卡罗的VOI(Value of Information)
- mysql 用户
- Ubuntu安装eclipse,并创建桌面快捷方式
- vagrant打造跨平台可移动的开发环境四
- 贪心算法基本介绍以及在lintcode上的典型题型
- oracle 存储过程
- Android Fragment 真正的完全解析(上) (转)