Privileged Aspects

When you are using Aspect-Oriented Programming with AspectJ and you want to get around Java restrictions in your Aspect, you can declare the Aspect “privileged“.

Say you perform some logging from your Aspect, but the member you want to access has no (public) accessor method. You could create a public getter method and use that. Better would be to make the Aspect privileged so it can access the member even though it is declared private. This scenario is demonstrated in the snippets below.

Given the following class “Foo”.

  1. ppublic class Foo {
  2.     private String bar;
  3.  
  4.     private void doSomething() {
  5.         bar = "bar";
  6.     }
  7. }

The Aspect would look something like this.

  1. public privileged aspect FooLogging {
  2.     protected pointcut myClass(): within(Foo);
  3.     private pointcut doSomethingMethod(): myClass()
  4.             && execution(doSomething());
  5.  
  6.     after(): doSomethingMethod() {
  7.         String value = ((Foo) (thisJoinPoint.getThis())).bar;
  8.         // Logging goes here.
  9.     }
  10. }

There is one limitation to privileged Aspects though:

Privileged aspects are not supported by the annotation style.

See “Aspect Declarations” in “Chapter 9. An Annotation Based Development Style” of the “The AspectJ 5 Dev Kit Developer’s Notebook“.

Loading Contact photos with Picasso

The Picasso image downloading library has an interesting feature that I just stumbled upon. It can load Contact photos based on a passed in Contact Uri containing the ContactsContract.Contacts.LOOKUP_KEY. It is as simple as:

  1. Uri uri = Uri.withAppendedPath(
  2.     ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
  3. Picasso.load(uri).into(myImageView);

It doesn’t seem to be mentioned on the Picasso website, but it is a very useful feature.

If you want to know exactly how Picasso loads the Contact photo, have a look at the ContactsPhotoBitmapHunter class.

Android RenderScript support library

A while back I wrote about RenderScript and the lack of a support library. Now Google has released the support library for RenderScript, making it a lot more accessible for a lot of developers.
Usage is really simple, just import the correct classes:

  1. import android.support.v8.renderscript.*;

And target Android API 18 when building:

  1. renderscript.target=18
  2. renderscript.support.mode=true
  3. sdk.buildtools=18.1.0

There are unfortunately some limitations, but nothing that’s a real show-stopper.

“Allocation.USAGE_IO_INPUT and Allocation.USAGE_IO_OUTPUT are not currently available in the RenderScript Support Library.”

“Devices running Android 4.2 and earlier will always run their RenderScript applications on the CPU, while devices running Android 4.3 or later will run their RenderScript applications on whatever processors are available on that particular device.”

“Support Library versions have to be precompiled to support all possible platforms, there is a performance hit when running the precompiled scripts compared to runtime compilation on Android 4.3.”

Read the full details in Google’s blog post.

Android fragmentation 2013

At last  year’s DroidCon in London, Robin Puthli’s talked about Device Fragmentation among Android devices. Open Signal has just posted a new visualization of device fragmentation for 2013.

Fragmentation is both a strength and weakness of the Android ecosystem. When comparisons are made between Android and iOS the issue of different API levels, and the vastly different devices running them, is often emphasised. In this report we examine the extent of Android fragmentation and analyse its impact on both users and developers.

Read the full article on opensignal.com.

Renderscript

To do some faster image manipulation I’ve been looking at Renderscript.

Renderscript provides a platform-independent computation engine that operates at the native level. Use it to accelerate your apps that require extensive computational horsepower.

This made it a better candidate than using the NDK with JNI. It’s also easier to maintain as an Android developer.

What I wanted to achieve is a fast way to apply Gaussian blur. Googling around will provide you plenty ways to do this in Java. It let me to a blog post about using a Convolution matrix combined with various kernels to achieve different effects. Unfortunately doing this on large images in Java is slow.

The other option was to use JNI, but I don’t feel confident enough about writing C/C++. There are, however, some libraries out there worth looking at. OpenCV and Lightbox’ PhotoProcessing for instance. But when you’re just trying to use one or two effects, this seems a bit overkill.

Last but not least is Renderscript. This is a bit more accessible than the NDK and only results in a slight loss of performance compared to using the NDK. The only requirement is Android 3+ (API level 11 and above).
If you’re looking to get started with Renderscript, Google has a good introduction and more in-depth article about the design goals of Renderscript. The Renderscript reference comes in very handy when you are writing your own scripts.
At first I was happy to find the ScriptIntrinsicBlur class, but unfortunately that one is only available from API level 17. Discarding that option, I decided to implement my own class to create a Gaussian blur effect. To start work on a fast algorithm for Gaussian blur, I had a look at how this is being done for games and came across a blog post about “Efficient Gaussian blur“. I’ve made a first (yet to be further optimized) version and tried it out, you can find the script at Github. This implementation already renders a Gaussian blur effect extremely fast. It looks great when using the emulator, but unfortunately when used on a phone it seems to produce some scanline-like side-effect.

The biggest downside of Renderscript is that it is only available on Android 3+. It does, however, look like Google is working on a compatibility library for Android 2.2. When you clone “https://android.googlesource.com/platform/frameworks/support“, there seems to be a “renderscript\v8” folder. I tried building it using the supplied Make file, but there were some errors.

I hope the compatibility library for Renderscript arrives soon, so it can be used across a bigger range of devices.

Sending SMS

Being able to send an SMS to a device can come in really handy from time to time. Below are two methods for sending text to a device using SMS. The first is to send to a hardware device, the second to send to a virtual device on an emulator.

Hardware device

  1. > adb shell
  2. $ am start -a android.intent.action.SENDTO -d sms:01123123123 --es sms_body "Text to send" --ez exit_on_sent true
  3. $ input keyevent 22
  4. $ input keyevent 66

For more info, see “How do I send an SMS from a shell?” on Stackoverflow.

Emulator

  1. Open the DDMS perspective in Eclipse.
  2. Under “Telephony Actions” select “SMS”.
  3. Fill out “Incoming number” and “Message”.
  4. Hit “Send”

For more info, see “Using DDMS” on the Android developers site.

Fast, user-friendly and power-efficient network communication on Android

Notes from Erik Hellman’s talk about “Fast, user-friendly and power-efficient network communication on Android” on the second day of DroidCon UK 2012.

Doing network communication the right way isn’t all that hard, just keep a couple of recommendations in mind. There is no need to “re-invent the wheel”, other fields have struggled with this problem before, we can learn from them. There are also a lot of open source projects that tackle various network related problems, quite often one of those will meet your requirements.

That being said, handling the network on a mobile phone can be difficult. The connection can drop out of nowhere, the quality can change or you might not even be online at all. There are a couple of things that developers can do to make the experience better:

  •  HTTP Client handling
  • Background network I/O
  • Playing server

Generally speaking HttpUrlConnection is the best client to use, except for Eclair and Froyo, for these API versions the Apache HTTP client has fewer bugs.
Make sure to wrap the HttpUrlConnection streams in buffers and always exhaust the streams.

Enable caching, it will save a lot of network traffic.

To avoid blocking the UI thread, always run your network related tasks on a different thread using a Service with a Handler implementation.
If you need to poll a URL on a regular basis, use the AlarmManager to schedule requests at a set (slightly inexact) interval.

An Android device could also serve as a server (think multiplayer gaming). This could be quite complex to create, but luckily the Netty.io library will probably meet most of your needs.

And lastly, don’t use a splash-screen, there should be no need for it. Give the user as much control as possible.

You can watch the full presentation on the Droidcon UK website or read it in pdf format on Sony’s site.

Custom Notifications

Today I ran into an interesting problem with custom Notifications. The following error kept on being thrown while I was testing with a Samsung Galaxy Ace phone:

“android.widget.RemoteViews$ActionException: can’t find view: …”

My custom Notification contains an ImageView and some TextViews. The image for the ImageView was being loaded from a remote server. When the image was retrieved I tried updating the Notification by modifying a clone of the original Notification I sent, calling:

  1. RemoteView.setImageViewBitmap(myViewId, bitmap)

 After this the app would crash. The LogCat output would then show the error above.

Having a close look at the other Notifications displayed by the phone, it turned out that ImageViews were automatically removed.

To solve the issue you have to make sure to always create a new Notification, that way your custom XML gets inflated and the ImageView is (again) accessible.

Device Fragmentation by Robin Puthli

Notes from Robin Puthli’s talk about Device Fragmentation among Android devices on the 1st day of DroidCon UK 2012.

Device fragmentation starts to become a big part of Android development as there are more and more Android devices available. As a result there are a lot of different resolutions and screen sizes that need to be taken into account. OpenSignal.com has a very interesting report on their blog that illustrates this fragmentation.

Luckily (device) fragmentation is a very old problem. It had to be solved on operation systems (Window, Mac, Linux, etc), browsers (Chrome, FireFox, Internet Explorer, etc), Java (ME, SE, FX, etc) and more before.

There are roughly nine strategies you can pick from to deal with device fragmentation.
Multi-manual: Phone vs tablet, writing separate code for each.
Derive multi: QT or J2ME Polish, Mono Touch, writing pseudo code and then letting the framework generate the rest.
One (size) fits all: HTML5, PhoneGap. This approach is based on coding for the lowest common denominator.
Single adapt
: Writing adaptive layouts, using 9-patches, fragments.

“There is no silver bullet. You have to pick and mix [from the available solutions].”

The full presentation can be found at Itude Mobile’s blog.