当前位置:   article > 正文

AOP在Android中的使用(作为依赖库)_android library 调用 主app 里面的方法

android library 调用 主app 里面的方法

上篇博客中无法对构造方法应用AOP,本篇做了修改


项目目录:



没有给出的类,在上篇博客中:

依赖库中的build.gradle文件

  1. apply plugin: 'com.android.library'
  2. import com.android.build.gradle.LibraryPlugin
  3. import org.aspectj.bridge.IMessage
  4. import org.aspectj.bridge.MessageHandler
  5. import org.aspectj.tools.ajc.Main
  6. buildscript {
  7. repositories {
  8. mavenCentral()
  9. }
  10. dependencies {
  11. classpath 'org.aspectj:aspectjtools:1.8.9'
  12. classpath 'org.aspectj:aspectjweaver:1.8.9'
  13. }
  14. }
  15. android {
  16. compileSdkVersion 25
  17. buildToolsVersion "25.0.2"
  18. lintOptions {
  19. abortOnError false
  20. }
  21. defaultConfig {
  22. minSdkVersion 15
  23. targetSdkVersion 25
  24. versionCode 1
  25. versionName "1.0"
  26. testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
  27. }
  28. buildTypes {
  29. release {
  30. minifyEnabled false
  31. proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  32. }
  33. }
  34. }
  35. android.libraryVariants.all { variant ->
  36. LibraryPlugin plugin = project.plugins.getPlugin(LibraryPlugin)
  37. JavaCompile javaCompile = variant.javaCompile
  38. javaCompile.doLast {
  39. String[] args = ["-showWeaveInfo",
  40. "-1.5",
  41. "-inpath", javaCompile.destinationDir.toString(),
  42. "-aspectpath", javaCompile.classpath.asPath,
  43. "-d", javaCompile.destinationDir.toString(),
  44. "-classpath", javaCompile.classpath.asPath,
  45. "-bootclasspath", plugin.project.android.bootClasspath.join(
  46. File.pathSeparator)]
  47. MessageHandler handler = new MessageHandler(true);
  48. new Main().run(args, handler)
  49. def log = project.logger
  50. for (IMessage message : handler.getMessages(null, true)) {
  51. switch (message.getKind()) {
  52. case IMessage.ABORT:
  53. case IMessage.ERROR:
  54. case IMessage.FAIL:
  55. log.error message.message, message.thrown
  56. break;
  57. case IMessage.WARNING:
  58. case IMessage.INFO:
  59. log.info message.message, message.thrown
  60. break;
  61. case IMessage.DEBUG:
  62. log.debug message.message, message.thrown
  63. break;
  64. }
  65. }
  66. }
  67. }
  68. dependencies {
  69. compile fileTree(dir: 'libs', include: ['*.jar'])
  70. androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
  71. exclude group: 'com.android.support', module: 'support-annotations'
  72. })
  73. compile 'com.android.support:appcompat-v7:25.1.0'
  74. testCompile 'junit:junit:4.12'
  75. }




主工程build.gradle文件

  1. apply plugin: 'com.android.application'
  2. import org.aspectj.bridge.IMessage
  3. import org.aspectj.bridge.MessageHandler
  4. import org.aspectj.tools.ajc.Main
  5. buildscript {
  6. repositories {
  7. mavenCentral()
  8. }
  9. dependencies {
  10. classpath 'org.aspectj:aspectjtools:1.8.9'
  11. classpath 'org.aspectj:aspectjweaver:1.8.9'
  12. }
  13. }
  14. android {
  15. compileSdkVersion 25
  16. buildToolsVersion "25.0.2"
  17. defaultConfig {
  18. applicationId "cn.edu.sxu.www.aopdemolibrary"
  19. minSdkVersion 15
  20. targetSdkVersion 25
  21. versionCode 1
  22. versionName "1.0"
  23. testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
  24. }
  25. buildTypes {
  26. release {
  27. minifyEnabled false
  28. proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  29. }
  30. }
  31. }
  32. final def log = project.logger
  33. final def variants = project.android.applicationVariants
  34. variants.all { variant ->
  35. if (!variant.buildType.isDebuggable()) {
  36. log.debug("Skipping non-debuggable build type '${variant.buildType.name}'.")
  37. return;
  38. }
  39. JavaCompile javaCompile = variant.javaCompile
  40. javaCompile.doLast {
  41. String[] args = ["-showWeaveInfo",
  42. "-1.8",
  43. "-inpath", javaCompile.destinationDir.toString(),
  44. "-aspectpath", javaCompile.classpath.asPath,
  45. "-d", javaCompile.destinationDir.toString(),
  46. "-classpath", javaCompile.classpath.asPath,
  47. "-bootclasspath", project.android.bootClasspath.join(File.pathSeparator)]
  48. log.debug "ajc args: " + Arrays.toString(args)
  49. MessageHandler handler = new MessageHandler(true);
  50. new Main().run(args, handler);
  51. for (IMessage message : handler.getMessages(null, true)) {
  52. switch (message.getKind()) {
  53. case IMessage.ABORT:
  54. case IMessage.ERROR:
  55. case IMessage.FAIL:
  56. log.error message.message, message.thrown
  57. break;
  58. case IMessage.WARNING:
  59. log.warn message.message, message.thrown
  60. break;
  61. case IMessage.INFO:
  62. log.info message.message, message.thrown
  63. break;
  64. case IMessage.DEBUG:
  65. log.debug message.message, message.thrown
  66. break;
  67. }
  68. }
  69. }
  70. }
  71. dependencies {
  72. compile fileTree(include: ['*.jar'], dir: 'libs')
  73. androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
  74. exclude group: 'com.android.support', module: 'support-annotations'
  75. })
  76. compile 'com.android.support:appcompat-v7:25.1.0'
  77. testCompile 'junit:junit:4.12'
  78. compile project(':aoplibrary')
  79. }



TraceAspect.java类做了修改,增加了对构造函数的支持

  1. package cn.edu.sxu.www.aoplibrary;
  2. import org.aspectj.lang.ProceedingJoinPoint;
  3. import org.aspectj.lang.annotation.Around;
  4. import org.aspectj.lang.annotation.Aspect;
  5. import org.aspectj.lang.annotation.Pointcut;
  6. import org.aspectj.lang.reflect.CodeSignature;
  7. import org.aspectj.lang.reflect.ConstructorSignature;
  8. import org.aspectj.lang.reflect.MethodSignature;
  9. /**
  10. * Aspect representing the cross cutting-concern: Method and Constructor Tracing.
  11. */
  12. @Aspect
  13. public class TraceAspect {
  14. private static final String POINTCUT_METHOD =
  15. "execution(@cn.edu.sxu.www.aoplibrary.DebugTrace * *(..))";
  16. private static final String POINTCUT_CONSTRUCTOR =
  17. "execution(@cn.edu.sxu.www.aoplibrary.DebugTrace *.new(..))";
  18. @Pointcut(POINTCUT_METHOD)
  19. public void methodAnnotatedWithDebugTrace() {}
  20. @Pointcut(POINTCUT_CONSTRUCTOR)
  21. public void constructorAnnotatedDebugTrace() {}
  22. @Around("methodAnnotatedWithDebugTrace() || constructorAnnotatedDebugTrace()")
  23. public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable {
  24. CodeSignature methodSignature=null;
  25. if(joinPoint.getSignature() instanceof MethodSignature)//普通方法
  26. {
  27. methodSignature = (MethodSignature) joinPoint.getSignature();
  28. }
  29. else if(joinPoint.getSignature() instanceof ConstructorSignature)//构造方法
  30. {
  31. methodSignature = (ConstructorSignature) joinPoint.getSignature();
  32. }
  33. String className = methodSignature.getDeclaringType().getSimpleName();
  34. String methodName = methodSignature.getName();
  35. final StopWatch stopWatch = new StopWatch();
  36. stopWatch.start();
  37. Object result = joinPoint.proceed();
  38. stopWatch.stop();
  39. DebugLog.log(className, buildLogMessage(methodName, stopWatch.getTotalTimeMillis()));
  40. return result;
  41. }
  42. /**
  43. * Create a log message.
  44. *
  45. * @param methodName A string with the method name.
  46. * @param methodDuration Duration of the method in milliseconds.
  47. * @return A string representing message.
  48. */
  49. private static String buildLogMessage(String methodName, long methodDuration) {
  50. StringBuilder message = new StringBuilder();
  51. message.append("Gintonic --> ");
  52. message.append(methodName);
  53. message.append(" --> ");
  54. message.append("[");
  55. message.append(methodDuration);
  56. message.append("ms");
  57. message.append("]");
  58. return message.toString();
  59. }
  60. }


MainActivity.java类

  1. package cn.edu.sxu.www.aopdemolibrary;
  2. import android.os.Bundle;
  3. import android.os.SystemClock;
  4. import android.support.v7.app.AppCompatActivity;
  5. import android.view.View;
  6. import android.widget.Button;
  7. import cn.edu.sxu.www.aoplibrary.DebugLog;
  8. import cn.edu.sxu.www.aoplibrary.DebugTrace;
  9. import cn.edu.sxu.www.aoplibrary.StopWatch;
  10. public class MainActivity extends AppCompatActivity implements View.OnClickListener{
  11. private Button button;
  12. private Button button2;
  13. private Button button3;
  14. private String TAG="cn.edu.sxu.www.aopdemo.MainActivity";
  15. @Override
  16. protected void onCreate(Bundle savedInstanceState) {
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.activity_main);
  19. button= (Button) findViewById(R.id.button);
  20. button2= (Button) findViewById(R.id.button2);
  21. button3= (Button) findViewById(R.id.button3);
  22. button.setOnClickListener(this);
  23. button2.setOnClickListener(this);
  24. button3.setOnClickListener(this);
  25. }
  26. @Override
  27. public void onClick(View view) {
  28. switch (view.getId())
  29. {
  30. case R.id.button:
  31. commonTest();
  32. break;
  33. case R.id.button2:
  34. aopTest();
  35. break;
  36. case R.id.button3:
  37. initConstructor();
  38. break;
  39. }
  40. }
  41. /**
  42. * 普通统计
  43. */
  44. private void commonTest()
  45. {
  46. final StopWatch stopWatch = new StopWatch();
  47. stopWatch.start();
  48. SystemClock.sleep(2000);
  49. stopWatch.stop();
  50. DebugLog.log(TAG, "所用时长:"+stopWatch.getTotalTimeMillis());
  51. }
  52. /**
  53. * aop 统计
  54. */
  55. @DebugTrace
  56. private void aopTest()
  57. {
  58. SystemClock.sleep(3000);
  59. }
  60. /**
  61. * 演示构造方法
  62. */
  63. private void initConstructor()
  64. {
  65. // Person person=new Person("张三",10);
  66. // person.setAge(80);
  67. Person person=new Person();
  68. }
  69. }



activity_main.xml文件

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:id="@+id/activity_main"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. android:paddingBottom="@dimen/activity_vertical_margin"
  7. android:paddingLeft="@dimen/activity_horizontal_margin"
  8. android:paddingRight="@dimen/activity_horizontal_margin"
  9. android:paddingTop="@dimen/activity_vertical_margin"
  10. >
  11. <TextView
  12. android:layout_width="wrap_content"
  13. android:layout_height="wrap_content"
  14. android:text="官网demo,统计方法运行时间"
  15. android:id="@+id/textView" />
  16. <Button
  17. android:text="普通方式"
  18. android:layout_width="wrap_content"
  19. android:layout_height="wrap_content"
  20. android:layout_below="@+id/textView"
  21. android:layout_alignParentLeft="true"
  22. android:layout_alignParentStart="true"
  23. android:layout_marginTop="42dp"
  24. android:id="@+id/button" />
  25. <Button
  26. android:text="aop方式"
  27. android:layout_width="wrap_content"
  28. android:layout_height="wrap_content"
  29. android:layout_below="@+id/button"
  30. android:layout_alignRight="@+id/button"
  31. android:layout_alignEnd="@+id/button"
  32. android:layout_marginTop="87dp"
  33. android:id="@+id/button2" />
  34. <Button
  35. android:text="aop构造方法"
  36. android:layout_width="wrap_content"
  37. android:layout_height="wrap_content"
  38. android:layout_marginBottom="69dp"
  39. android:id="@+id/button3"
  40. android:layout_alignParentBottom="true"
  41. android:layout_alignParentLeft="true"
  42. android:layout_alignParentStart="true" />
  43. </RelativeLayout>


Person.java类

  1. package cn.edu.sxu.www.aopdemolibrary;
  2. import android.os.SystemClock;
  3. import java.io.Serializable;
  4. import cn.edu.sxu.www.aoplibrary.DebugTrace;
  5. /**
  6. * Created by ${huozhenpeng} on 17/2/23.
  7. * Company : www.miduo.com
  8. * 演示AOP对构造方法的使用
  9. */
  10. public class Person implements Serializable {
  11. private String name;
  12. private int age;
  13. public String getName() {
  14. return name;
  15. }
  16. public void setName(String name) {
  17. this.name = name;
  18. }
  19. public int getAge() {
  20. return age;
  21. }
  22. @DebugTrace
  23. public void setAge(int age) {
  24. this.age = age;
  25. SystemClock.sleep(100);
  26. }
  27. public Person(String name, int age) {
  28. this.name = name;
  29. this.age = age;
  30. SystemClock.sleep(1000);
  31. }
  32. @DebugTrace
  33. public Person() {
  34. SystemClock.sleep(1500);
  35. }
  36. }



源码地址:http://download.csdn.net/detail/huohacker/9761903

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号