Thursday, October 23, 2008

Working on IMAP IDLE support for Android's Email app

For all those screaming about the lack of push e-mail updates for regular IMAP accounts with the basic Email app in Android, I have been digging into the code for the past few days and am preparing a patch for IMAP IDLE support. For those that do not know, IMAP IDLE allows a client to maintain a persistent, light connection to the server that is then notified of new messages as they arrive. Many IMAP servers support this extension, including Microsoft Exchange which would thus allow push e-mail for those that need corporate e-mail options on the G1.

I will post an APK for folks to try once I have the support working well. Stay tuned...

Wednesday, August 27, 2008

Generate Callback Listener Helpers from AIDL

As I redesign Five I find myself tweaking/expanding the callback listeners in my interface which are handled through the RemoteCallbackList class in the service implementation. This class is great, however for each call code must be written similar to:

int N = mCallbacks.beginBroadcast();

for (int i = 0; i < N; i++) {
try {
} catch (RemoteException e) {}


This can quickly pollute the service implementation, and even if you factor these calls out to a separate class it can be a pain to create and maintain them. So, I came up with a solution in the form of a Perl script which takes as input an AIDL file defining the callback interface and outputs a class implementing the extended RemoteCallbackList. To use, simply type:

$ ./ < IFooListener.aidl >


Monday, August 25, 2008

Android Instrumentation Example

As Android approaches maturity with its recent 0.9r1 release, I began to think its time that my main project updates to match. I decided to take another look at Android's instrumentation and unit testing features to build robust tests for my critical services and activities. Unfortunately, there isn't anything new in the way of documentation however there is now is an example we can use in ApiDemos.

Looking at the new ApiDemos we see that there is a new tests directory which contains a second AndroidManifest.xml with no user activities defined. This is important as this structure allows us to have two separate APKs, one for production and one for testing, so our main distribution and build doesn't need to be polluted. Unfortunately, this approach is not compatible with the Eclipse plugin, and so we must define everything in an external build environment.

For convenience, I packaged the complete ApiDemos project with my Ant build environment here: ApiDemos-instrumentation-build.tar.gz. To build, start the emulator and run the following commands:

$ adb shell rm /data/app/ApiDemos.apk
$ ant install
$ cd tests && ant install

It is essential above that you remove the old ApiDemos.apk as the instrumentation APK must be signed with the same key as the package it tests.

Once we've got both APKs installed we can begin running our unit tests. There is no UI in Android for this, however it can be invoked more conveniently through adb as such:

$ adb shell am instrument -w

This will run all defined tests and print a dot character for each successful test, F for failure, or E for invocation error. See the javadoc in tests/src/com/android/samples/ for more sample command lines to run individual test cases or specific tests within them.

My main project, Five, has recently been updated to include unit tests in the five-client component, with more test coverage to follow in the next few weeks. For a non-trivial test case, see my CacheServiceTest.

NOTE: Previously, I was using the masa Android plugin for Maven, however it has not yet been updated to support 0.9r1. I feel that using Maven for this would have been cleaner, but the Ant approach is sufficient for this simple demonstration. Once updated, I will return here and finish this example with a more sophisticated build environment to automate testing.

Thursday, August 7, 2008

Android on the HTC Vogue

As many of you know, the Vogue can run Android quite nicely with support for sending/reciving SMS, incoming and outgoing calls, GPRS, touch screen, etc thanks to dzo over at Xda-Developers. See his posts and materials here:

Several folks from freenode/#android have access to this device, myself included, and have been developing tools and applications to further explore the platform on real hardware. Those tools are being hosted at the android-random project page. There is a simple file manager (Glance), a much-improved threaded text messaging app (Messages), and perhaps most importantly of all a RemoteLogcat tool that allows us to observe the running devices logcat (normally accessible through adb logcat) by piping it to a server on the public Internet.

Recently, I created an emulator skin that can be used to simulate this device's resolution during development. Simply download vogue-skin.tar and unpack it into $ANDROID_SDK/tools/lib/images/skins along with the other default skins. Then fire up the emulator as:

$ emulator -skin vogue

The skin has no decorations, just a simple 240x320px layout, but this should give you a pretty good idea how different Android can be on this device.

Thursday, July 31, 2008

Interruptible I/O example using HttpClient

Recently I found myself considering some of the gotchas of threaded, blocking I/O as I've been using it on Android. Specifically, how do we gracefully handle interruptions demanded by the user or the system to free resources? After some thought there seems to be three basic strategies with Java:
  • 1. Use non-blocking I/O, which is generally clumsy and unintuitive for most Java engineers.
  • 2. Cancel blocking I/O threads by simply setting a stop flag and discarding the reference to the thread. The thread will clean itself up after an arbitrary length of time up to its transmit or connect timeout.
  • 3. Close the socket owning the input stream on which the blocking thread is waiting.
It seems that #2 is the most popular choice on Android however I would like to make a case for #3 as a cleaner method of tidying resources on user request. With this approach, we can be certain to quickly close any open files, relinquish database, object, or file locks, and allow the thread to clean up its resources quickly. As it turns out, using HttpClient makes this approach relatively painless, but there are a few gotchas in this pattern that we must watch out for.

So, to get started we need to create our StoppableDownloadThread class which allows us to encapsulate our interrupt logic.
public class StoppableDownloadThread extends Thread
private String mURL;

private HttpGet mMethod = null;

/* Volatile stop flag used to coordinate state between the two
* threads involved in this example. */
protected volatile boolean mStopped = false;

/* Synchronizes access to mMethod to prevent an unlikely race
* condition when stopDownload() is called before mMethod has
been committed. */
private Object lock = new Object();

public StoppableDownloadThread(String url)
mURL = url;
This simply outlines our basic strategy for stopping and synchronization. A simple volatile boolean flag and a monitor lock to share the HttpGet handle should do just fine. Now let's continue with the implementation of the run() method:
public void run()
HttpClient cli = new DefaultHttpClient();
HttpGet method;

try {
method = new HttpGet(mURL);
} catch (URISyntaxException e) {

/* It's important that we pause here to check if we've been stopped
* already. Otherwise, we would happily progress, seemingly ignoring
* the stop request. */
if (mStopped == true)

synchronized(lock) {
mMethod = method;

HttpResponse resp = null;
HttpEntity ent = null;
InputStream in = null;

try {
resp = cli.execute(mMethod);

if (mStopped == true)

StatusLine status = resp.getStatusLine();

if ((ent = resp.getEntity()) != null)
long len;
if ((len = ent.getContentLength()) >= 0)

in = ent.getContent();

byte[] b = new byte[2048];
int n;
long bytes = 0;

/* Note that for most applications, sending a handler message
* after each read() would be unnecessary. Instead, a timed
* approach should be utilized to send a message at most every
* x seconds. */
while ((n = >= 0)
bytes += n;
System.out.println("Read " + bytes + " bytes...");
} catch (Exception e) {
/* We expect a SocketException on cancellation. Any other type of
* exception that occurs during cancellation is ignored regardless
* as there would be no need to handle it. */
if (mStopped == false)
} finally {
if (in != null)
try { in.close(); } catch (IOException e) {}

synchronized(lock) {
mMethod = null;

/* Close the socket (if it's still open) and cleanup. */
This is a pretty standard example of an HTTP GET using HttpClient4, however do note that we have strategically placed checks against our stop flag to avoid leaving the download thread in an inconsistent state when it's being cancelled. We're not done yet though as we still need to implement the stop part of the interface so that our main thread (or any other thread) can abort the download thread:
public void stopDownload()
if (mStopped == true)

/* Flag to instruct the downloading thread to halt at the next
* opportunity. */
mStopped = true;

/* Interrupt the blocking thread. This won't break out of a blocking
* I/O request, but will break out of a wait or sleep call. While in
* this case we know that no such condition is possible, it is always a
* good idea to include an interrupt to avoid assumptions about the
* thread in question. */

/* A synchronized lock is necessary to avoid catching mMethod in
* an uncommitted state from the download thread. */
synchronized(lock) {
/* This closes the socket handling our blocking I/O, which will
* interrupt the request immediately. This is not the same as
* closing the InputStream yieled by HttpEntity#getContent, as the
* stream is synchronized in such a way that would starve our main
* thread. */
if (mMethod != null)
This completes our basic interface, but we still don't have a usable example here. There's no communication between our download thread back to the user in any meaningful way as would be required for an Android application. For that I have modified the above code slightly and introduced an Android layer in the form of a working demo. Source code for the full example: CancelHttpGet.tar.gz.

Friday, May 30, 2008

Details on the next public SDK

I had hoped to reserve judgment until after an official announcement from Google, however after speaking with Dan Morrill and Jason Chen at Google I/O, it seemed clear that the OHA, up the corporate chain, has not taken the development community seriously. I have confirmed that the ADC winners have now received an updated version of the SDK which they are bound by NDA to keep private. These projects are thus forced to be closed until the NDA restrictions are lifted, which include no source release, performance benchmarking, discussion of new features, screenshots, etc. These restrictions are expected to last until the next public SDK is dropped.

So, when is the next public release? Surely after over 3 months since M5 and only a few major releases so far it should be close, perhaps landing after round 2 of the ADC is over? Not so. The SDK is not expected until either shortly before handset launch later this year, or perhaps on or after that date. We can rest assured that there will be significant changes in this release: modified and new APIs, new core SDK features (like Wi-Fi, bluetooth, etc), modified UI, and of course many important bug fixes. As a result, our applications will require substantial revision to work [well] on this new version, reducing the likelihood that losing ADC entries will be able to "compete" for visibility on the handsets as they launch. Not to mention, generally stressing the larger development community with excessive unnecessary work and "wandering" development with no clear indication of what's coming and when.

I see this as a serious problem, running directly counter to the claims of openness and developer support, however Google and the OHA apparently do not feel that a commitment to openness is binding in the face of proprietary inconvenience.

So, I feel there is no choice but to suspend my development on the current platform and await the launch of handsets. Hopefully I will be able to catch up quickly and still offer a stable and feature-rich application within the first few months of handset availability. That said, I will now be starting on the desktop client for my media streaming system. If anyone is interested, my project is currently open source and I am actively interested in contributors, even if you want to work on the Android component using M5 *grin*.

Tuesday, April 15, 2008

My ADC Submission: Five, a media distribution technique

I have created a system by which your music can be accessed anytime on the go using your cell phone's wireless data connection. Simply install the server software onto your home PC and configure the phone to connect to it. Initially, the meta database will be downloaded and then from there only changes will be synced to the phone. The media itself is retrieved on demand and cached to the storage card. In my real-world tests with a remote server and simulating GPRS or EDGE data throughput has been very promising, requiring only 3 - 8 seconds of buffer time before most content can be played.

For more screenshots and info, see The system, though currently closed, will be opened under the terms of the GPL after the first round challenge winners are announced, regardless of outcome.

I will also be posting a video this week, showing my system in action. Stay tuned.

Thursday, April 10, 2008

Obligatory Google I/O Posting

Seems like Google I/O is all the rage these days, so I decided I'd officially mention that I will be attending. I live in Seattle so airfare was cheap, plus I have friends in the area who want to go too.

Sunday, March 23, 2008

Advanced Tab Activity Demo

I was inspired by the simple TabHost/TabWidget demonstration by Jeffrey Sharkey, and decided to expand upon it significantly. In my demo, I have replaced all the default drawables and layouts, created my own custom ColorStateList, and even utilized TabActivity for greater isolation.

Download: TabActivityDemo.tar.gz

The code and images for this demo are in the public domain, so please feel free to use and modify as you wish.

NOTE: TabActivity is currently marked as deprecated, but according to this post, I believe that may be in error.

Wednesday, March 5, 2008

Tool to read Android binary XML files

I have successfully reverse engineered a good portion of the Android binary XML file format that is found inside of Android package files (.apk). With this tool, you can explore the XML layout, drawable, and animation files used in the applications distributed with the SDK (phone, browser, contacts, etc). My primary motivation for doing this was to simply observe some of the common practices and get a sense for what Google is doing internally that isn't necessarily available through their API demos and samples. Below you can find two links to download either the stand-alone convertor or the collected output as run over every APK file found in the phone's /system directory:

Download: android-xmldump.tar.gz

Please note that this tool was a very quick hack and some of the XML files I found failed to parse. Not many, and the only ones I found were raw XML documents (not Android resources) so I didn't bother to explore any further incompatibilities. If you find any resources that fail to parse or have any insight into the format, feel free to leave a comment and I will investigate when I have time.

EDIT 2012-08-22: Android's come a long way since this post.  It's now possible to use the aapt tool to read the contents of XML documents (and a whole lot more) of APK files.  For example:

android dump xmltree foo.apk AndroidManifest.xml

Sunday, March 2, 2008

Custom Android list widget to access large sorted lists on touch devices

I have developed a custom Android widget for m5-rc14 that automatically (and efficiently) sections a sorted list by alphabet letters and offers a side-bar widget for quickly jumping to each section. This widget could be very useful for any project offering an extremely large list to the user, such as a music player showing artists or albums.

Some things left out with this widget are a smooth scroll to the selected position as well as a finer control for sections that have large item counts themselves. More to come later :)

Here's a screenshot using dummy data:

Download: AlphabetListView.tar.gz

Licensed under the GPLv2.

EDIT 2012-08-22: This approach represents very old design patterns for Android and has been broadly replaced by upstream components such as the fast scroll mode of ListView.

Sunday, February 10, 2008

Android Eclipse Plugin / AIDL bugs

UPDATE: This work-around is no longer necessary since m5-rc14 fixed the aidl bugs.

The current Android SDK (m3-rc37a) has numerous bugs surrounding the aidl parser, the most annoying of which makes it very difficult to work with a project utilizing aidl imports and the Eclipse Android plugin. In order to ease some frustrations, I have created a wrapper around the aidl tool which tries to guess certain usage parameters and automatically inject the necessary -I switch.

To use the script, enter your Android SDK tools directory and issue the following:

mv aidl

Then save the following script as aidl:


my @aidl = split /[\/\\]/, [ grep { /\.aidl$/ } @ARGV ]->[-1];

foreach (reverse @aidl)
last if $_ eq 'src';
undef $_;

my $I = join('/', map { $_ if $_ } @aidl);

my @args;

push @args, "-I$I" if $I;
push @args, @ARGV;

system("$", @args);

And finally, set the script executable:

chmod +x aidl

Wednesday, January 9, 2008

Asynchronous Service Example

Many folks have been asking about asynchronous services (using the Binder) in Android and I decided to whip up a quick example showing how this is intended to work with the current SDK (m3-rc37a). There are rumors from Google that they will be improving things soon and providing a better example, but in the mean time this example should clear up a lot of the confusion:


UPDATE: The project must be built using ant (not Eclipse) because of an SDK bug regarding the invocation of the aidl tool. There are also reports that even ant won't work on Windows due to yet more bugs in aidl. The code does work as Google intended, though, and in the next SDK release they are committed to having these issues resolved.

UPDATE2: Google released m5-rc14 and, as promised, the bugs are fixed and their included RemoteService example has been updated to show similar functionality.