The application of AOP in Android __AOP

Source: Internet
Author: User
Tags aop reflection

Website address: Https://fernandocejas.com/2014/08/03/aspect-oriented-programming-in-android/


Oop

(object-oriented programming) encapsulates the entities and their attributes and behaviors of the business process to achieve a clearer and more efficient logical unit partition.


Aop

(Face to face) in order to extract the section of the business process, it is faced with a step or stage in the process of processing, to obtain the isolation effect of the low coupling between the parts of the logic process.

The two design ideas are fundamentally different from each other in the target.



AOP is a complement to OOP, not an alternative.


Several concepts (from http://blog.csdn.net/a1314517love/article/details/11847087)

1. Cross cutting concern: is an independent service that is spread throughout the process of the system
2. Aspect to the crosscutting line of concern to the modular
3. Advice specific implementation of crosscutting concerns (with the concept of classification, before, after, throw)
4. Pointcut it defines which joinpoint the advice applies to, and for spring it is a method call
5. Weave the process of applying advice to target object is woven, and spring supports dynamic weaving
6. Target Object Advice applied objects
7. Proxy:spring AOP uses the JDK's dynamic proxy by default, its agent is runtime-created, or it can use the Cglib proxy
8.Introduction can dynamically add a method to a class
9.joinpoint:advice the point or timing of execution on an application, spring only supports the Jointpoint of the method
These concepts sound more abstract, and we'll look at what these concepts specifically refer to by using AOP schematics and examples.



The following demo demonstrates the use of AOP:

GitHub on the article introduced a very detailed: https://github.com/hehonghui/android-tech-frontier/blob/master/issue-22/Android%E4%B8%AD%E7% 9a%84aop%e7%bc%96%e7%a8%8b.md

AOP involves the knowledge of reflection and annotation

Reflection: http://blog.csdn.net/whitepony/article/details/23096845

Note: http://blog.csdn.net/whitepony/article/details/23099541


About execution in AOP

Content Source: http://www.it610.com/article/256837.htm

Indicates that all methods under the Com.xy.service package are managed for the transaction.

Execution (* com.aptech.jb.epet.dao.hibimpl.*.* (..))

This should be done. This is all the methods of the class under the Com.aptech.jb.epet.dao.hibimpl package.

The first * represents all return value types

The second * represents all the classes

The third * represents the last of all methods of class. Represents all the parameters.

Here are some examples of common pointcut expressions:

Execution of any public method:

Execution (Public * * (..))

Execution of any method that starts with "set":

Execution (* set* (..))

Accountservice the execution of any method of the interface:

Execution (* com.xyz.service.accountservice.* (..))

Define the execution of any method in the service pack:

Execution (* com.xyz.service.*.* (..))

The execution of any method that defines any class in a service package or a child package:

Execution (* com.xyz.service. *.*(..))



The following two small demo, a direct application in the Android project, a seat Android library using


Android Project:


Project structure



Need to use the Aspectjrt.jar package, source code with the official website (build.gradle file configuration needs attention)


Mainactivity.java class

Package Cn.edu.sxu.www.aopdemo;
Import Android.os.Bundle;
Import Android.os.SystemClock;
Import android.support.v7.app.AppCompatActivity;
Import Android.view.View;

Import Android.widget.Button;
    public class Mainactivity extends appcompatactivity implements view.onclicklistener{private button button;
    Private Button button2;
    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);
        Button.setonclicklistener (this);
    Button2.setonclicklistener (this); @Override public void OnClick (view view) {switch (View.getid ()) {case R.id.butto
                N:commontest ();
            Break
         Case R.id.button2:aoptest ();       Break }/** * General statistics/private void Commontest () {final stopwatch stopwatch = new Stopwa
        TCH ();
        Stopwatch.start ();
        Systemclock.sleep (2000);

        Stopwatch.stop ();

    DebugLog.log (TAG, "The length of Time:" +stopwatch.gettotaltimemillis ());
    /** * AOP Statistics */@DebugTrace private void Aoptest () {systemclock.sleep (3000);
 }
}


Debugtrace.java class

Package Cn.edu.sxu.www.aopdemo;

Import Java.lang.annotation.ElementType;
Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;
Import Java.lang.annotation.Target;

@Retention (Retentionpolicy.class)
@Target ({elementtype.constructor, elementtype.method}) public
@ Interface Debugtrace {}


Traceaspect.java class

Package Cn.edu.sxu.www.aopdemo;
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.MethodSignature;
 /** * Aspect representing the cross Cutting-concern:method and constructor tracing. * * @Aspect public class Traceaspect {private static final String Pointcut_method = "Execution (@cn. Edu.sxu.www.ao Pdemo.

  Debugtrace * * (..)) ";

  private static final String Pointcut_constructor = "Execution (@cn. Edu.sxu.www.aopdemo *.new (..))"; @Pointcut (Pointcut_method) public void Methodannotatedwithdebugtrace () {} @Pointcut (pointcut_constructor) public VO ID constructorannotateddebugtrace () {} @Around ("Methodannotatedwithdebugtrace () | | Constructorannotateddebugtrace () ") Public Object Weavejoinpoint (Proceedingjoinpoint joinpoint) throws Throwable {Me Thodsignature methodsignature = (methodsignature) 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 Strin
    Gbuilder ();
    Message.append ("Gintonic-->");
    Message.append (methodname);
    Message.append ("-->");
    Message.append ("[");
    Message.append (methodduration);
    Message.append ("MS");

    Message.append ("]");
  return message.tostring ();
 }
}

Stopwatch.java class

Package Cn.edu.sxu.www.aopdemo;

Import Java.util.concurrent.TimeUnit;

/**
 * Class representing a stopwatch for measuring time.
 * * Public
class Stopwatch {
  private long starttime;
  Private long Endtime;
  Private long elapsedtime;

  Public stopwatch () {
    //empty
  }

  private void Reset () {
    starttime = 0;
    Endtime = 0;
    elapsedtime = 0;
  }

  public void Start () {
    reset ();
    StartTime = System.nanotime ();
  }

  public void Stop () {
    if (starttime!= 0) {
      endtime = System.nanotime ();
      ElapsedTime = Endtime-starttime;
    } else {
      reset ();
    }
  }

  Public long Gettotaltimemillis () {return
    (elapsedtime!= 0)? TimeUnit.NANOSECONDS.toMillis (Endtime-starttime): 0;
  }
}


Debuglog.java class

Package Cn.edu.sxu.www.aopdemo;

Import Android.util.Log;

/**
 * wrapper around {@link Android.util.Log}
 *
/public class Debuglog {

  private Debuglog () {}

  /**< c7/>* Send A debug log message
   *
   * @param the tag Source of a log message.
   * @param message "would like logged."
   */public
  static void log (string tag, string message) {
    LOG.D (tag, message);
  }
}


Activity_main.xml file

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android= "http://schemas.android.com/apk/res/" Android "xmlns:tools=" Http://schemas.android.com/tools "android:id=" @+id/activity_main "android:layout_width=" Match_parent "android:layout_height=" match_parent "android:paddingbottom=" @dimen/activity_vertical_margin "and
    roid:paddingleft= "@dimen/activity_horizontal_margin" android:paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools:context= "cn.edu.sxu.www.aopdemo.MainActivity" > ; TextView android:layout_width= "wrap_content" android:layout_height= "wrap_content" official website Demo, statistical method run Time "android:id=" @+id/textview "/> <button android:text=" normal Way "android:layout _width= "Wrap_content" android:layout_height= "wrap_content" android:layout_below= "@+id/textview" an
Droid:layout_alignparentleft= "true"        Android:layout_alignparentstart= "true" android:layout_margintop= "42DP" android:id= "@+id/button"/&

    Gt <button android:text= "AOP mode" android:layout_width= "Wrap_content" android:layout_height= "Wrap_co Ntent "android:layout_below=" @+id/button "android:layout_alignright=" @+id/button "Android:layout_a" Lignend= "@+id/button" android:layout_margintop= "87DP" android:id= "@+id/button2"/> </relativelayout&
 Gt


Build.gradle file


Apply plugin: ' com.android.application ' import org.aspectj.bridge.IMessage import Org.aspectj.bridge.MessageHandler
        Import Org.aspectj.tools.ajc.Main Buildscript {repositories {mavencentral ()} dependencies { Classpath ' org.aspectj:aspectjtools:1.8.9 ' classpath ' org.aspectj:aspectjweaver:1.8.9 '}} android {comp
        Ilesdkversion buildtoolsversion "25.0.2" defaultconfig {ApplicationID "Cn.edu.sxu.www.aopdemo" Minsdkversion targetsdkversion Versioncode 1 Versionname "1.0" Testinstrumentationr Unner "Android.support.test.runner.AndroidJUnitRunner"} buildtypes {release {minifyenabled False Proguardfiles getdefaultproguardfile (' proguard-android.txt '), ' Proguard-rules.pro '}} fi  nal def log = Project.logger final def variants = Project.android.applicationVariants Variants.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) Messageha
        Ndler handler = new MessageHandler (true);
        New Main (). Run (args, handler); For (IMessage message:handler.getMessages (null, true)) {switch (Message.getkind ()) {case I
            Message.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 Bre
            Ak }}} dependencies {compile Filetree (dir: ' Libs ', include: [' *.jar ']) androidtestcompile (' Com.andr oid.support.test.espresso:espresso-core:2.2.2 ', {Exclude group: ' Com.android.support ', module: ' Support-annotatio
 NS '}) Compile ' com.android.support:appcompat-v7:25.1.0 ' testcompile ' junit:junit:4.12 '}


Build.gradle file Configuration Way official online, but the official website provided is used as a dependent library


Verify:




Source Address: http://download.csdn.net/detail/huohacker/9761873


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.