Using the Decorator Pattern with Android

The decorator pattern is a great design pattern enabling developers to add additional behaviour to a particular object. Below is a UML Diagram (from Wikipedia) showing the design pattern. To start, you have a interface that specifies all the methods that you wish to be able to extend. Then you have the concrete component or base class. This is the original class that will be running. The decorators then contain the additional logic that you wish to add the to base object. In this guide, we look at how we can do this at runtime.

UML Diagram of the Decorator Pattern

Decorator Pattern in UML, Wikipedia

 

Using this pattern, we can enable runtime behavioural variations of classes within an Android application by adding and removing decorators from the decorator stack. One problem with Android (and probably other frameworks), this pattern makes use of Object-Oriented concepts like object construction. On Android, many of the essential classes you work with e.g. Activities and Services, you have no control or ability to construct these objects. Other problems can be attributed to the fact that you do not have real (if I am wrong, then it probably is not the recommended way) control of the activity in terms of updating its reference to another (needed for decorator methods to be invoked). In other languages like C++ it is possible to do pointer manipulation, and therefore get around this problem, but in Java, you can’t.

While this method may not be ideal or perfect, it is a workaround that I am using. With that in mind lets have a look at my example code.

Interface

Firstly, we have the interface MainActivityInterface. In this class we have a single method signature pushMeClick(View V); . This method corresponds to the touch event for the button named “Push Me” (Not very imaginative I know, but you get the point).

Activity

Next, we have the core Activity MainActivity, and this class obviously extends Activity, but also implements MainActivityInterface. Within this class we have decorator class MainActivityDecorator member named toplevel. This reference is needed to direct an invocation to the top of the decorator stack. Also we have a TextView object named txtMe, used to show a piece of text in the Window. In the OnCreate(Bundle) method we get the TextView object from the View.

The method pushMeClick(View v) as declared in the interface checks to see if the class is decorated, if it is not, then a core version of that method is invoked (the base behaviour). If the class is decorated, then the decorator version of that method is invoked. We also have a method named toggleClick(View v). When the button named “ToggleDecorator” is clicked, it checks if it the activity has been decorated. If it hasn’t, then the first decorator is added to the stack. If it has been decorated once, then the second is added to the stack. And if the second has been added, it is removed, leaving only the first.

MainActivityDecorator

Next we the add the base decorator class named MainActivityDecorator. In this class we add the base activity MainActivity naming it activity (I know, I really do pick great names). We also add another class member, of the type MainActivityInterface named parent. This member is used in a decorator chain that is more than 1, with the parent object pointing to the next decorator in the chain/stack. In the decorator we have two constructors whereby the activity is used as a parameter and in one of the constructors allow for the parent decorator to be added.

Next we have the method pushMeClick(View v), to which if there is a parent decorator, the parents version of the method is invoked, if there is no parent, the core version in the base activity MainActivity is invoked. Normally in the decorator pattern you do not need this, can just run the super version. But if you do in this, you will get caught up in a recursive loop and cause a Stack Overflow. The reason this is different, is because like we said before, we can’t update the reference of an activity, and therefore the base activity has to handle the method call at first.

We also add a method to the decorator called removeSelf(). This method removes the reference to the activity (to help cut any ties that will not allow it being collected by gc), and return the decorators parent (so the activity updates its toplevel decorator reference).

Each Specific Decorator
Next we add specific decorators which extend MainActivityDecorator, and in example we just call them MainActivity_decorator_one and MainActivity_decorator_two for simplicity. In these classes I have to add a constructor which just calls its super version. I then add a pushMeClick(View v) method in each. In these methods I firstly call the super version first, I then get the TextView from the activity (package protected) and append either “, decorator1” or “, decorator2”.

 

Screenshots:

Obviously, because of the extra instructions needed, this pattern is not computationally free. When I have time, I will try and profile the effect, and update this entry with its effect

You can find this code at https://deansserver.co.uk/gitweb/?p=codeExamples/AndroidDecorator.git;a=summary where you can view and download (click on snapshot on which revision you want).

Enjoy all.

An Openssource Context Engine for Android : The Concepts

Smart phones in recent years have seen high proliferation, allowing more users to stay productive while away from the desktop. This proliferation has seen the increasing amount of mobile applications being developed and becoming available to consumers through centralised application repositories. It has become highly predictable for these devices to have an array of sensors including GPS, accelerometers, digital compass, proximity sensors, sound etc.

Using these sensors with other equipment already found in phones, a wide set of contextual information can be acquired. This contextual information is consumed by context-aware mobile applications. Context aware applications have been described to be intelligent applications that can monitor the user’s context and, in case of changes in this context, consequently adapt their behaviour in order to satisfy the user’s current needs or anticipate the user’s intentions.

Within this article, I will introduce an openssource engine for context acquisition and composition for Android. This engine is primarily intended to be used in two cases:

  1. Packaged with your application, adding your own context components
  2. Packages outside your application, using the engine with your application(s)
Engine Usage

Engine Usage

Ideally, we hope this engine can turn-into a globally used engine that is used by several applications on the device, leading to more efficient resource handling, preserving precious battery power.

Essentially within the engine context types are contained within their own Component. A Component can be seen as an encapsulation of constants, and methods for acquiring & reasoning that context value from the sensor/data resource.

Component Class

Component Class

Where this gets interesting is, in many situations a context wont be based on a single point or single component, but more based on the composition of many contexts. Because of this, its quickly foreseeable that many contexts will be used in more than one Composite context. With this, and the increasing interest to incorporate context-awareness into mobile applications, its important to manage this carefully to prevent wasteful use of resources.

How our engine attempts to help this issue is to work with context tree structures, in which context changes for individual contexts are broadcasted up the tree to the level above for reasoning and so on. These contexts should not need to know who is listening/requesting the context changes, but just broadcast its state on context change and carry on. Using this approach we aim to make contexts completely self contained and generic.

To help explain this tree structure, we can consider the following Composite context:

Example Context

Example Context

In the Connection Composite, there is a Data Sync Composite, which uses the Wifi and 3G context, and the Battery Context. If there is a change in the Wifi or 3G contexts, the Data Sync context receives the broadcast and then checks its own state. If its state has changed, then it then broadcasts its state, which is then received by the Connection context.

These contexts are then listened to by the application, which then can define its different adaptation logic.

Because of this approach, we need not implement Composite Components for each composition, but instead just define this context composition and let the engine do the work, allowing the engine to be more dynamic in its use.

For more details, please see our paper:

Kramer, D., Kocurova, A., Oussena, S., Clark, T., Komisarczuk, P. (2011) An extensible, self contained, layered approach to context acquisitionIn the Proceedings of the 3nd International Workshop on Middleware for Pervasive Mobile and Embedded Computing.

This software is licensed using the Apache License. Please see https://deansserver.co.uk/~dean/software/context-engine-for-android/ for upto date information of where the source is hosted.

DevXS 2011

DevXS

On the 11th November, I went to the JISC event DevXS. As I am a fan of the Dev8D events held every February, and this event is for undergrad and postgrad students I thought it would be a great chance to meet some very talented computer science students from all over the country.

This event was set to cover the whole weekend, and instead of a focus on teaching sessions like Dev8D, it focused purely on competitions in which teams are given 24 hours to implement their projects in a ‘code marathon’.

Friday Night

As there were a few of us going from UWL, I decided rather than travel to Lincoln alone, I’d go with one of my colleagues, which like me wanted to explore some of Lincoln during the day before the evening event registrations. Have to say I was fascinated with the Cathedral, Castle and Roman remains. I think that after the brief look I got, I would like to go back to explore more of the city.

After some exploring, Malte and I went to registration and then went on to get the hotel keys for the hotel room. The evening was then filled with food, socialising and drinking. The organisers created a game called bingo, which required the person to meet people and see if the statements contained in their grid fitted that person and then get a signature. Once all the grid statements were signed you shouted “bingo”, got a badge and got another drink ticket. This proved a very good way of getting everyone to talk and get to know everyone. After the food and drink, me and another of my colleagues went into Lincoln town to experience the nightlife.

Saturday

Have to say I was rather hungover for the morning, but still ready to get going on one of the competitions. Because there were only 4 of us from my institution we decided to form a team named Team UWL. We decided to try and do a bluetooth system for distribution location based information and events, as part of the Freshers App competition. During the day they had an array of sweets and drink which was good, and we got a good lunch. In the course of the day there were several keynotes, but to be perfectly honest other than the magic show in the evening, I’m unsure how many people really were listening to them.

The Venue

What I found amazing was the amount of people still working hard at 2am, the atmosphere was great, and proved a great way of getting help and support from lots of people. I found also the tip to use f.lux given in the midnight keynote to be fantastic. My team managed to keep programming until about 02:30.

Sunday

In a somewhat funny way, the organisers put “Wham – Wake me up before you go-go” on the speakers to wake us up. There was a great breakfast, and a final rush to try and get everything working and finished in time. If you view our git repo featured in the last post you will see the amount of activity increasing closer to the noon deadline.

We then had to pitch the idea of our work to the whole hall, as a way of the everyone including the judges to see our projects explained, in 60 seconds or less. This was a great way of hearing and in some cases seeing some of the fantastic work done by everyone. Sadly my team had trouble getting both parts of the system to work together but we have agreed it would be great to continue the work.

Overall I had a fantastic weekend, met some great people and now looking forward to Dev8D 2012.

Anyone interesting in knowing more about the event, go to http://devxs.org.

Blueyeti – DevXS team challange

Blueyeti

As part of DevXS, Team UWL decided to implement a bluetooth based indoor tracking software which provides location related information to students inside a university, named Blueyeti. The idea behind is to provide a mechanism to deliver information to students based on their location within the campus. This can help new students find out information regarding the place where they are, activities being held, without them needing to check any website/twitterfeed etc.

The software works by the use of a bluetooth application running on several base stations, that listens for bluetooth clients nearby, its then logs the device mac address, and sends its information out.

On the other end, the user has a mobile application running on a smart phone. This is then ideally left to listen for any connections from the base stations (when walking within range), receiving this information and then informing the user.

 

 

The sourcecode repo can be found at: https://gitorious.org/blueyeti/blueyeti

Aspect Oriented Android Development – Tool Integration

In the last post, I demonstrated a really simple example of how to use AspectJ in a Java program. In this post I will be taking it further and showing you how you can easily integrate the AspectJ and Android Development tools, and quickly be able to run Aspects within your Android app.

First thing though, a little theory about why integrating these tools will make your life of AOP much easier. Though programming applications for Android is mostly in Java (you could use C/C++ with the NDK), its doesn’t run Java bytecode. Android uses the Dalvik VM, as apposed to the Java VM. Now, you may ask why do I care? Well it means that you need to use the Android Toolchain. The first image shows the steps it takes to compile an Android application.

Android Build Processes

Android Build Processes

Now you (hopefully) understand the build process of android applications, lets talk about how aspects are compiled and weaved to an application. When compiling an AspectJ project, it firstly compiles Classes and Aspects to Java bytecode. Then an AspectJ Weaver weaves the Aspect bytecode into the Class bytecode. Now this presents a small issue. Within the build process you see that the class files are changed to Dalvik bytecode using the Dex tool. This means that we need to add a process after the javac and before the dx tool, but the use of the AspectJ builder, which compiles and weaves. This does mean that weaving can only be done compile-time and not run-time, because dynamic weaving would only create Java bytecode, not Dalvik.

I’ve seen over the internet examples of this being done using Ant and other scripts. But surely the better approach would be to integrate the AspectJ tools with the Android tools? In this article I will explain how you can do this. bringing AOP to Android development, while allowing you to still use the tools created for AspectJ and Android development.

Firstly you want to have the AspectJ Developement Tools plugin to Eclipse installed (http://eclipse.org/ajdt//), and the Android SDK and the Android Developer Tools plugin for Eclipse installed (http://developer.android.com/sdk/index.html). Once these have been installed, we will start a new android project, calling it HelloAndroidAspect, and call the first activity HelloWorldActivity, adding the code found in the following image:

Activity

Activity

Now we need to make alterations to the project so we can use AspectJ. Firstly you need to add the AspectJ library to the project. You need to include the AspectJ library (aspectjrt) into the project, which can be found in your Eclipse plugins folder. The folder you are looking for is named org.aspectj.runtime_1.x.x.x depending on what version you have. The library you need from that folder is called aspectjrt.jar.

Add AspectJ Library

Add AspectJ Library

Now we have done that we need to make alterations to the projects .project file. This file should be altered outside Eclipse. Within this file we need add the weaver, so that it weaves the bytecode after compilation but before dex and packaging. Also we need to add the nature of the project, so that the project can be seen as an Android project, as well as a AspectJ project. You add the weaving section by adding the following in the <buildSpec> section of the file:

<buildCommand>
<name>org.eclipse.ajdt.core.ajbuilder</name>
<arguments>
</arguments>
</buildCommand>

This buildCommand should be the first in the <buildSpec> section. After adding this, add the following to the <natures> section of the file:

<nature>org.eclipse.ajdt.ui.ajnature</nature>

This nature should be in the middle of the two already there. For reference I have included a whole .project file.

Now, the tools have been integrated for your Android AspectJ project. We now want to right click on the project and click on New->Other. Then go to the AspectJ folder and click on Aspect. In the form just call it Test and add the code in the following image:

Aspect

Aspect

Now, if you compile and run the code you should see the following on your android phone/emulator and in the DDMS LogCat:

Android Screenshot

Android Screenshot

Android DDMS

Android DDMS

 

 

 

As you can see the AspectJ is working with your Android Application. In this example I am running just a fairly static method, but in the next post I will show you how you can do UI manipulation in Aspects, that are required to run on Activity instances.

To download all the source files please Click Here. Feel free to comment if you have problems with it.

An introduction to Aspect Oriented Programming – AspectJ

As I have been finding in my research, software modularity is crucial to maintainable, separable code. Sadly in modern times, Object Oriented Programming though allowing for common class related code to be modularised, it lacks the modularity needed to avoid code scattering (you know when you have some type of functionality found in parts all over a program) and code tangling (when you have different aspects of your program all mixed up in a single method). Anyhow, this is where the use of Aspect Oriented Programming can come in handy. Aspect-Oriented Programming is based around the idea of modularising “aspects” of your program into their own modules, called Aspects (you was expecting that wasn’t you?).

Common examples to how this can be useful is normally in the situations of say security: On particular class methods you need to do some sort of security checks.  Now in OOP, you would probably have this tangled and scattered across all the classes which require this checking. Though at first may feel normal, what happens when you want to alter the security checking? You need to go through all the classes/methods affected, wasting time (which otherwise can be wasted on facebook).

In this post I will be going through a simple example of AspectJ, an AOP extension to Java.

Firstly, to use aspectj you need to download the tools, these can be for a number of IDEs but I recommend the eclipse plugin (http://eclipse.org/ajdt//). Once the plugin is installed and enabled we are all set and ready to begin.

Starting a new AspectJ Project

Once you have the development tools installed and enabled, we will start by starting a new AspectJ project. For this you may find it isn’t in the menu when clicking on “new”, so click on other. We setup normal Java project settings and make a very basic HelloWorld program.

 

Now, for this example I will work with an aspect called “Logger”. The beauty of AOP is being able to crosscut concerns (code tangling and scattering). For instance, if you updating security aspects of your program that were involved all over your program, you would have these parts in lots of different methods, making it difficult to track. With AOP, you can put all these concerns within a single aspect, needing to edit/update that single aspect file…simple!

Within the aspect, we now first specify the pointcut (where do you want to apply advice) in line 8. Then you want to then want to program what advice you want it to execute and when (before, around, or after the pointcut). As you see in the second screenshot, the string ” Aspect” is appended to the string “Hello World” already outputted.

I strongly suggest after trying this simple example you experiment with other more complex examples. In the next post I will tell you guys how this method can be integrated and used within Android programming as an alternative programming paradigm to OOP.

Until next time!

Dev8D 2011

dev8D

For my third year running, I have attended Dev8D. I was hoping that even though I had a great time last year, can it get better? Well the answer to that is yes! Since having a tiny exposure to Scheme, I decided to try some of the code labs learning different functional languages.

On the first day, I attended the Erlang course (session 1 in the morning, and session 2 in the afternoon). This session was excellently done, obviously by a professional trainer. Being I had only done alittle bit of functional programming previously I was surprised how quickly I was able to keep up and start doing stuff. I have to say I am very impressed at Erlang’s ability to deal with processes, I think I spawned 100,000 processes in just over 2 seconds! Also I liked how easy it is to send messages between processes and give responses, no wonder Facebook use it for their chat system. I also went to the Python session, this language was interesting (though I was slightly miffed at the concept of no atomic types and everything is a object idea).

On the second day, I attended the Kinect Hacking session. I really enjoyed this session as it really shows great potential for interesting HCI in many different areas. I didn’t personally get involved but more took a backseat on it, as I didn’t have a Kinect with me and the hacking software seemed slightly ropy and I didn’t want that all on my macbook. I found it great how it mapped out arms, I just wished I had the chance to see the helicopter flying with the Kinect! :(. For the afternoon, I attended the clojure session. This session was great, where by we were taught the basics of clojure using a squareroot example program. This was very interesting and insightful, though have to admit heavy on my head. I have loved learning something new at this event.
Overall this year was somehow even better than last! And I can’t wait until the next.

iPhone Game – LyricalGenius

Months ago I spoke briefly about a new iPhone/iPod touch game that I was starting to develop for Mammoth Graphics, well recently (a week or so ago) the work was finished, but I hadn’t had time to really sit down and blog about it. The game is called LyricalGenius and is a game targeted at people that want a general quiz game about song lyrics. Obviously the aim of the game is that for each level there is a target of correct answers the player needs to get, and if you get too many wrong, then tough luck! Development of this game has really enabled me to build on my experiences with the development of the Tour de France application which I blogged about summer last year.

The game is now in the hands of mammoth, who are in the process of final testing and adding more questions (as song lyrics need approval from Sony Records) and hopefully will see it up on app store very soon, so if you fancy a new game, give it ago!

Dev8D 2010

Last month I attended for the second year running the JISC supported Dev8D event in central London. For this year because of my change to a PhD, I had a bit more freedom to when I could attend so I decided to go two days this year instead of just one, concentrating on Thursday and Friday. What I found amazing, was how much the event had grown since last year! I’ve haven’t seen so many people like myself in ages, was really nice.

On Thursday I chose to attend the expert lighting talks in the morning with the Cloud Workshop in the afternoon.

Picture of Cloud Computing Workshop at Dev 8 D 2010

Cloud Computing Workshop

In the exper talks there a few talks in particular that stood out to me, firstly the talk about genetic programming, secondly the talk about web security which I took notice of some of the tips they suggested!

Arduino Workshops – Friday

These workshops were by far the coolest thing I’ve done in a good while! I attended two workshops, one for beginners in the morning and a more advanced workshop for the afternoon. In the morning we got a talk about the hardware and how to do very basic programs like getting a single LED to flash and also using a speaker to make very sounds, with one group able to program their arduino to make the Simpsons theme song!

Below are some of the things I worked on in the advanced workshop, including multiplexing LEDs and driving a motor using the arduino

Overall I had a great time, and look forward to next year. Hoping there to be more Arduino workshops.

New year, new start, new experiences

Hi guys,

been a while I know but I have been rather busy with loads of different things. Firstly I realise its slightly late but still wish everyone a happy new year! Currently I have been carrying on with the LyricalGenius iPhone game which I hope to finish within a week or so. When the game is complete I will post screenshots of the application, and hope anyone with a iPod Touch/iPhone will give it ago and support it!

Other than the game, I’m starting my PhD officially this Monday which I am quite excited about, and sadly have a poster I need to get together ready for an annual PhD Conference, which should be quite interesting. I have also a paper I’m trying to start writing, well when i have five minutes that is.

For this paper I’m hoping to write a workshop paper proposing the use of mobile Domain Specific Language as as way of creating almost platform independent applications. Though this paper won’t be appropriate for a conference as I’m merely proposing something, I still think it will be a good starting point for my career in academia.

Because I’m looking at writing this paper with Tony Clark, he said for me to write using LaTex, which so I read could be a very good way of writing my PhD thesis. Because of the markup quality of LaTex, the thesis will be able to be tracked using normal SCM technologies e.g. CVS, SVN, or my personal favourite Git. With the use of SCM, different versions of the document can be stored and differences between different versions can be compared, which should be very useful.

Other than work, I’m also to Slovakia for 6 days from next Friday, which I am extremely looking forward to. This trip isn’t work related but more time to met and spend time with a very special person. I’m looking forward to seeing Bratislava, Vienna in Austria and over all having a great time!

Anyhow, will update you soon!