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.

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.

Summer in Slovakia so far

Hey guys, just thought I would talk about what I have been upto while in Slovakia, as I’m about halfway through my trip.
Well, firstly happy to report I’m having a great time here. First week/10 days was spent at Katkas parents house which was nice, we went mushroom picking and a little sight seeing in the town. Other activites include going to a rodeo (like in America) and taking her dogs for walks in the local fields. Also saw Anna for abit which was nice.
In other news, a paper I wrote for the doctoral symposium at SLE2010 got accepted which I’m happy about. Just have to now revise the piece ready for final submission September 17th. The symposium is being held in Eindhoven, Netherlands and will give me a chance to talk to some very experienced researchers to help get some direction and tips which is great and something to look forward to!
Other than that currently I have been doing a few different bits and pieces which includes some android development (a little app I hope to openssource to add to a openssource project called phpsysinfo) and playing with aspectJ. For those that don’t know what aspectJ is, well it is a java implementation allowing the programmer to use aspect oriented programming, a technique that allows you to crosscut program aspects and concerns which can help increase the modularity of a program. When I have something worth putting up I will.
Anyhow, until next time!

Android and iPhone progress

Hey guys! This will most likely be my last entry before the new year, which I’m looking forward to. One hopes next year will bring some great new experiences and hopefully a new start in some aspects of my life, though not forgetting to hopefully have more success in my professional life either! I think this year has been full of drama in some aspect, some sad moments but also a new opportunity to take my career to the next level.

Moving on, yes my mobile development seems to be coming along ok. Currently I am in process of designing the data model of the iPhone game, and also have started building the interfaces which is exciting to see come together. I will obviously have alot to do over the christmas holidays with it, but I guess it will keep my mind active in that sense. As more development happens and I have screenshots to show, I will post them.

As for the android development, like I said in a post not long ago I was planning to development a music catalog and mobile app, well I have artist data being stored, and also album names being stored (though I get the occasional unhandled exception, that I need to look into). I need to look into being able to get a album artist, as different songs may have different artists (Say if there was a colaborative song). I am currently thinking to get the album artist from the artist folder it is stored in, as I dont think there is way of accessing the album artist ID tag using the library I have. For the android side of it, currently I have a SAX XML Parser running, and just displaying everything in a console-like program. For the moment I am programming the logic and fetching of data, the representation layer of my app will be sorted last. Im thinking to have a search page that terms can be searched across artist and album…

Android app screenshot showing parsed artist data

Android app screenshot showing parsed artist data

Only issue that I am currently having is there seems to be an issue with either “/” or “&” in the XML when it comes to parsing, which I will need to sort out before I continue, though I think I’ve made a good start considering the limited time I have to put to this project.

Anyhow, will update you when I have to talk, or show.

Merry Christmas and a Happy New Year!

Elgg development and other activities

Hey guys, only got a few more weeks of Elgg development at least for the foreseeable future anyhow, to which to I have mixed feelings about. Seems like everytime you begin to get used to and fully in your stride with something its time to change, which is a shame but equally help keeps my work and life interesting.

As of what I’ve been working on, erm.. Well I’ve been continuing with the work on the videos plugin, which for the moment is almost ahead of previous expectations. Currently I have videos uploading and being able to be played, sound’s simple but it’s not quite. I’m in the process of being able to link the videos with the opportunities on the site, but need to be told how they are to be match, or I may just implement some sort of assumption. Also been working on some cool stuff with a piece of software called GATE (General Architecture for Text Engineering), which is intending on being used to ‘mine’ the text and help find offensive words/phrases. I have been working with a fellow colleague Dr. Ying Zhang, who is in the field of text/data mining to help set up GATE for our particular context, which is now working (at least for the moment).

A very small program has been written to use the backend of the software, getting strings of text that will eventually be sent from Elgg. I’m hoping to integrate it all from this Monday, with some re-engineering of how Elgg deals with any type of entered text, sending everything to GATE first for checking, if something isn’t allowed an error message will be sent to the user. Other than that I have to try and prepare Elgg to be able to integrate with BT’s MOSAIC, which I’m unsure of my ability to complete that in time. After the project, if I have time I am planning to try and generalise the video plugin so it will work with other Elgg installations and release it on the Elgg Development site under GPL open source licence.

From December I’m then starting the iPhone game with Mammoth Graphics at Ealing Studios, which I’m actually getting quite excited about. I hope the guys have started preparing the material that I need to get started and hopefully will have a version of the game implemented for February. I just have concerns about my pay as I’m having to come off general payroll and go back to hourly slips (which is really annoying). As long as I’m not being paid less than I will be getting from my PhD bursary then I don’t mind, as I guess an agreement has been made for me to spend time on my PhD during this project giving me almost an extra 2 months for it.

At home, I’ve been working on a little project of my own. I have a lot of music and when I go to music stores I’ve found several times I can’t remember if I have a CD already. So to solve this problem I am developing two applications:

  1. A backend file crawler, that trails through my music library and automatically indexes the artist, album and songs in a database, for which a PHP set of APi’s are being written to search and retrieve this data and relay it using XML.
  2. Because I have an Android based smart phone, I’m developing a app to get these details and help facilitate easy searching of what media I have already.

The backend app is already beginning to work, though have run into a few issues already that I will need to look into. The first issue being the speed, perhaps the speed of the crawler is going to be slower as I am not testing on the machine that will be run on and the crawling is being done over a network. Other reason I think is that I need to turn it into a threaded app, and allow more songs to be sorted concurrently. This will be something I implement last as to me efficiency and speed is something you look to once everything is working. The second issue is how to deal with multiple combinations of artists, as some song aren’t made with only one artist, leaving you will potentially copies of artists and combinations of artist which may affect search results if you only type in the one of the artists. This something I will need to look into more as this project progresses. Hopefully once the backend is complete (or as complete as I feel is necessary) work on the android app will commence which I look forward to completing as the app I think will be useful by myself and my step dad as we both have the same phone.

Anyhow, until next time chums