Aspect Oriented Programming in Android

Aspect-oriented programming entails breaking down program logic into “concerns” (cohesive areas of functionality). This means, that with AOP, we can add executable blocks to some source code without explicitly changing it. This programming paradigm pretends that “cross-cutting concerns” (the logic needed at many places, without a single class where to implement them) should be implemented once and injected it many times into those places.

Code injection becomes a very important part of AOP: it is useful for dealing with the mentioned “concerns” that cut across the whole application, such as logging or performance monitoring, and, using it in this way, should not be something used rarely as you might think, quite the contrary; every programmer will come into a situation where this ability of injecting code, could prevent a lot of pain and frustration.

AOP is a paradigm that has been with us for many years, and I found it very useful to apply it to Android. After some investigation I consider that we can get a lot of advantages and very useful stuff when making use of it.

Terminology (Mini glossary)

Before we get started, let’s have a look at some vocabulary that we should take into account:

  • Cross-cutting concerns: Even though most classes in an OO model will perform a single, specific function, they often share common, secondary requirements with other classes. For example, we may want to add logging to classes within the data-access layer and also to classes in the UI layer whenever a thread enters or exits a method. Even though each class has a very different primary functionality, the code needed to perform the secondary functionality is often identical.
  • Advice: The code that is injected to a class file. Typically we talk about before, after, and around advices, which are executed before, after, or instead of a target method. It’s possible to make also other changes than injecting code into methods, e.g. adding fields or interfaces to a class.
  • Joint point: A particular point in a program that might be the target of code injection, e.g. a method call or method entry.
  • Pointcut: An expression which tells a code injection tool where to inject a particular piece of code, i.e. to which joint points to apply a particular advice. It could select only a single such point – e.g. execution of a single method – or many similar points – e.g. executions of all methods marked with a custom annotation such as @DebugTrace.
  • Aspect: The combination of the pointcut and the advice is termed an aspect. For instance, we add a logging aspect to our application by defining a pointcut and giving the correct advice.
  • Weaving: The process of injecting code – advices – into the target places – joint points.

This picture summarizes a bit a few of this concepts:

Aspect Oriented Programming

So…where and when can we apply AOP?

Some examples of cross-cutting concerns are:

  • Logging
  • Persistance
  • Performance monitoring
  • Data Validation
  • Caching
  • Many others

And in relation with “when the magic happens”, the code can be injected at different points in time:

  • At run-time: your code has to explicitly ask for the enhanced code, e.g. by using a Dynamic Proxy (this is arguably not true code injection). Anyway here is an example I created for testing it.
  • At load-time: the modification are performed when the target classes are being loaded by Dalvik or ART. Byte-code or Dex-code weaving.
  • At build-time: you add an extra step to your build process to modify the compiled classes before packaging and deploying your application. Source-code weaving.

Depending on the situation you will be choosing one or the other :).

Tools and Libraries

There are a few tools and libraries out there that help us use AOP:

  • AspectJ: A seamless aspect-oriented extension to the Javatm programming language (works with Android).
  • Javassist for Android: An android porting of the very well known java library Javassist for bytecode manipulation.
  • DexMaker: A Java-language API for doing compile time or runtime code generation targeting the Dalvik VM.
  • ASMDEX: A bytecode manipulation library as ASM but it handles the DEX bytecode used by Android executables.

Why AspectJ?

For our example below I have chosen AspectJ for the following reasons:

  • Very powerful.
  • Supports build time and load time code injection.
  • Easy to use.


Let’s say we want to measure the performance of a method (how long takes its execution). For doing this we want to mark our method with a @DebugTrace annotation and want to see the results using the logcat transparently without having to write code in each annotated method. Our approach is to use AspectJ for this purpose.
This is what is gonna happen under the hood:

  • The annotation will be processed in a new step we are adding to our compilation fase.
  • Necessary boilerplate code will be generated and injected in the annotated method.

I have to say here that while I was researching I found Jake Wharton’s Hugo Library that it is suppose to do the same, so I refactored my code and looks similar to it, although mine is a more primitive and simpler version (I have learnt a lot by looking at its code by the way).


Project structure

We will break up our sample application into 2 modules, the first will contain our android app and the second will be an android library that will make use of AspectJ library for weaving (code injection).
You may be wondering why we are using an android library module instead of a pure java library: the reason is that for AspectJ to work on Android we have to make use of some hooks when compiling our app and this is only possible using the android-library gradle plugin. (Do not worry about this yet, cause I will be giving some more details later).

Creating our annotation

We first create our Java annotation. This annotation will be persisted in the class (RetentionPolicy.CLASS) file and we will be able to annotate any constructor or method with it (ElementType.CONSTRUCTOR and ElementType.METHOD). So our file will look like this:

Our StopWatch for performance monitoring

I have created a simple class that encapsulates time start/stop. Here is our class:

DebugLog Class

I just decorated the “android.util.Log” cause my first idea was to add some more functionality to the android log. Here it is:

Our Aspect

Now it is time to create our aspect class ( that will be in charge of managing the annotation processing and source-code weaving.

Some important points to mention here:

  • We declare 2 public methods with 2 pointcuts that will filter all methods and constructors annotated with “org.android10.gintonic.annotation.DebugTrace”.
  • We define the “weaveJointPoint(ProceedingJoinPoint joinPoint)” annotated with “@Around” which means that our code injection will happen around the annotated method with “@DebugTrace”.
  • The line “Object result = joinPoint.proceed();” is where the annotated method execution happens, so before this, is where we start our StopWatch to start measuring time, and after that, we stop it.
  • Finally we build our message and print it using the Android Log.

Making AspectJ work with Android

Now everything should be working, but, if we compile our sample, we will see that nothing happens.
The reason is that we have to use the AspectJ compiler (ajc, an extension of the java compiler) to weave all classes that are affected by an aspect. That’s why, as I mention before, we need to add some extra configuration to our gradle build task to make it work.
This is how our build.gradle looks like:

Our test method

Let’s use our cool aspect annotation by adding it to a test method. I have created a method inside the main activity for testing purpose. Let’s have a look at it:

Executing our application

We build and install our app on an android device/emulator by executing the gradle command:

If we open the logcat and execute our sample, we will see a debug log with:

Our first android application using AOP worked!
You can use the Dex Dump android application (from your phone), or any any other reverse engineering tool for decompiling the apk and see the source code generated and injected.


So to recap and summarize:

  • We have had a taste of Aspect Oriented programming paradigm.
  • Code Injection becomes a very important part of this approach (AOP).
  • AspectJ is a very powerful and easy to use tool for source code weaving in Android applications.
  • We have created a working example using AOP capabilities.


Aspect Oriented Programming is very powerful. Using it the right way, you can avoid duplicating a lot of code when you have “cross-cutting concerns” in your Android apps, like performance monitoring, as we have seen in our example. I do encourage you to give it a try, you will find it very useful.
I hope you like the article, the purpose of it was to share what I’ve learnt so far, so feel free to comment and give feedback, or even better, fork the code and play a bit with it.
I’m sure we can add very interesting stuff to our AOP module in the sample app. Ideas are very welcome ;).

Source Code

You can check the example app here (using AspectJ):
Also I have another AOP example for Java (you can use if for Android as well) using a Dynamic Proxy:


Unit testing asynchronous methods with Mockito

After promising (and not keeping my promise) that I would be writing and maintaining my blog, here I go again (3289423987 attempt). But lest’s forget about that…
So in this occasion I wanted to write about Mockito…yes, this mocking framework that is a ‘must have’ when writing your unit tests ;).


This is article assumes that you know what a unit test is and why you should write tests.
Also I strongly recommend this famous article from Martin Fowler that talks about test doubles, it is a must read to understand about test doubles.

Common case scenario

Sometimes we have to test methods that use callbacks, meaning that they are asynchronous by definition. These methods are not easy to test and using Thread.sleep(milliseconds) method to wait for the response is not a good practice and can convert your tests in non-deterministic ones (I have seen this many times to be honest).
So how do we do this? Mockito to the rescue!

Let’s put an example

Suppose we have a class called DummyCaller that implements a DummyCallback and has a method doSomethingAsynchronously() that delegates its functionality to a collaborator of the the class called DummyCollaborator that has a doSomethingAsynchronously(DummyCallback callback) as well, but receives a callback as a parameter (in this case our DummyCallback), so this methods creates a new thread to run his job and then gives us a result when is done.
Here is the code to understand this scenario in a better way:

Creating our test class

We have 2 options to test our asynchronous method but first we will create our test class DummyCollaboratorCallerTest (for convention we just add Test at the end of the class so this becomes part of its name).

So here we are using MockitoAnotations to initialize both Mock and ArgumentCaptor, but don’t worry about them yet, cause this is what we will be seeing next.
The only thing to take into account here is that both mock and class under test are being initialized before each test is executed in the setUp() method (using the @Before annotation).
Remember that for unit testing all the collaborators for a CUT (class under test) must be test doubles.
Let’s take a look at our 2 test solutions.

Setting up an answer for our callback

This is our test case using a doAnswer() for stubbing a method with a generic Answer. This means that since we need a callback to return immediately (synchronously), we generate an answer so when the method under test is called, the callback will be executed right away with the data we tell it to return.
Finally we call our real method and verify state and interaction.

Using an ArgumentCaptor

Our second option is to use an ArgumentCaptor. Here we treat our callback asynchronously: we capture the DummyCallback object passed to our DummyCollaborator using an ArgumentCaptor.
Finally we can make all our assertions at the test method level and call onSuccess() when we want to verify state and interaction.


The main difference between both solutions is that when using DoAnswer() we are creating an anonymous inner class, and casting (in an unsafe way) the elements from invocation.getArguments()[n] to the data type we want, but in case we modify our parameters the test will ‘fail fast’ letting know that something has happened. On the other side, when using ArgumentCaptor we probably have more control cause we can call the callbacks in the order we want in case we need it.
As interest in unit testing, this is a common case that sometimes we do not know how deal with, so in my experience using both solutions has helped me to have a robust approach when having to test asynchronous methods.
I hope you find this article useful, and as always, remember that any feedback is very welcome, as well as other ways of doing this. Of course if you have any doubt do not hesitate to contact me.

Code Sample

Here is the link where you can find this example and others. Most of them are related with Java and Android because this comes from a talk I gave a couple of months ago.
The presentation is in english but the video is in spanish (sorry for those who do not understand my argentinian accent…haha…BTW I will try to upload an english version as soon as possible…)

Further Reading

I highly recommend to take a look at Mockito documentation to have a better understanding of the framework. The documentation is very clear and has great examples. See you!

NFC on Android

Hi all! I’m so proud that finally I’ve created my new blog. Since this is my 12372983 attempt for having a development blog, I can only promise you that will put all my effort to keep it up to date. So welcome!

And now that this is my first post I just wanted to share with you a talk about Near Field Communication I gave last year which was requested by a lot of colleagues. Here it is guys! (take into account that the video is in spanish, anyway I promise to explain some examples and use cases soon).

Enjoy and feel free to comment and give very useful feedback.

You can find the source code of the example application of both the presentation and video here:

Here is the presentation (english):


Here is the video (spanish):

See you!!!