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.

SQLite on Android

In the past week I started working with SQLite databases on Android.

It can be quite cumbersome to explore the data stored in the DB on an actual device. What has helped me a lot is grabbing the DB from the device and loading the SQLite DB in a third party SQLite browser / manager. This will give you a lot more flexibility on exploring the data that is stored and will also be a great help for testing your queries.
You can retrieve your database from the device using ADB:

  1. adb pull /data/data/[app_package]/databases/[db_file] .

I’ve been using SQLiteBrowser to explore the DB and test my queries.

One thing I noticed is that inserting around a hundred rows took quite some time, about 350ms. I was inserting one row at a time and after some Googling on how to insert multiple rows in one query, I found an answer on StackOverflow. The suggestion was to do something like the following:

  1. INSERT INTO 'tablename'
  2.     SELECT 'data1' AS 'column1', 'data2' AS 'column2'
  3.     UNION SELECT 'data3', 'data4'
  4.     UNION SELECT 'data5', 'data6'
  5.     UNION SELECT 'data7', 'data8'

After trying this approach it cut the insertion time in half near the 170ms mark, still quite slow.
Some more searching brought me to an article about “Speeding up SQLite insert operations“. What this article advises is to use transactions, an example:

  1. database.beginTransaction();
  2. for (...) {
  3.     database.insert(...);
  4. }
  5. database.setTransactionSuccessful();
  6. database.endTransaction();

Using this technique the insertion was sped up to roughly 25ms, much better!

As an alternative to using a database, you could just store the data on disk. This works fine especially when you just use a database to store data and don’t need to sort it or do more complex queries. Even if you needed sorting, you could use the SortedMap class.

IntelliJ keyboard shortcuts

Recently I switched from Eclipe to IntelliJ and that meant getting to know IntelliJ’s keyboard shortcuts. Below is a list of the shortcuts I use most.

Generic
crtl + n = Open resource.
ctrl + f4 = Close window.
alt + [left/right arrow] = Move to the window on the left/right.
ctrl + shift + f = Find in path, i.e search in whole project.

Text operations
ctrl + d = Duplicate line.
ctrl + y = Remove line.
ctrl + shift + [up/down arrow] = Move line up / down.
ctrl + g = Navigate to line.
ctrl + shift + u = Toggle case.

Code
ctrl + q = Quick docs (floating documentation window when having selected a class, method, member).
ctrl + f12 = Show members.
alt + f7 = Find usage.
shift + f6 = Refactor > rename.
ctrl + alt + l = Format.
ctrl + alt + [left/right arrow] = Back / Forward.
alt + insert = Generate code, i.e. constructor, getters/setters.

Global Exception handling in Android

To be able to catch any exception you may encounter that isn’t part of a try-catch-clause, you can use the Thread.setDefaultUncaughtExceptionHandler( Thread. UncaughtExceptionHandler ) method.

In the handler you can then perform whatever action you want. Don’t forget to call “System.exit()” though, because otherwise this won’t work!

A simple example:

  1. public class SomeActivity extends Activity {
  2.  
  3.     private static final String LOG_TAG = "SomeActivity";
  4.  
  5.     @Override
  6.     protected void onCreate(Bundle savedInstanceState) {
  7.         super.onCreate(savedInstanceState);
  8.         Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
  9.             @Override
  10.             public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
  11.                 Log.e(LOG_TAG, "OMG! Uncaught Exception!");
  12.                 // Without calling System.exit() this will not work.
  13.                 System.exit(2);
  14.             }
  15.         });
  16.     }
  17. }

For some more details have a look at “Using Global Exception Handling on android” on StackOverflow.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.