Brain Flush

August 15, 2008

Handling Long Running Operations In Google Android

Filed under: Mobile Devices, Software Development & Programming — Tags: , , — Matthias @ 12:27 pm

User interface responsiveness is a crucial thing for all applications that require user interaction, but maybe even more so when programming for mobile handsets. Google’s Android programming environment unfortunately does not provide any mechanism for handling operations that may require a fair amount of time to complete, but which in itself are not meant to be implemented as Android Services. An example for this would be network I/O in an Activity, such as posting data to (or retrieving data from) a remote Web server. Because the Android runtime will terminate any Activity that does not respond within a couple of seconds, it is impossible (and simply a bad idea anyway) to perform such tasks from within the UI main thread.

That being said, I have come up with a generic class that handles long running operations by spawning a separate thread and passing back any result or error data to the main thread using a callback mechanism. An animated progress dialog will be displayed while the operation is running. That way the user is kept informed about any program activity that may take some time to complete.

The class can be used as follows:

public class MyActivity implements LongRunningActionCallback<Void> {

    private LongRunningActionDispatcher<Void> dispatcher;

    private void startLongRunningOperation() {
        // the first argument is a reference to the current Context, in this
        // case the current Activity. The second argument is a reference to
        // the object implementing the callback method.
        this.dispatcher = new LongRunningActionDispatcher<Void>(this, this);
        dispatcher.startLongRunningAction(new Callable<Void>() {
            public Void call() throws Exception {
                // perform your actions that take a long time
                return null;
        }, "Dialog Title", "Dialog message");

    // the callback
    public void onLongRunningActionFinished(Void result, Exception error) {
        if (error != null) {
            // handle error
        } else {
            // success, work with the result, if any

This will spawn a progress dialog (not indicating any actual progress in percentage, it’s just a “busy” dialog) with the given title and message. If an exception occurred in the Callable you provided, it will be passed as the error argument to the callback, so you should always check whether it’s non-null.

Below are the source codes for both LongRunningActionDispatcher and LongRunningActionCallback.

import java.util.concurrent.Callable;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

 * Use this class if you need to dispatch expensive (long running) operations
 * from your Activity. The long running operation is provided to
 * {@link startLongRunningAction} as a {@link Callable}. The result of the
 * operation and any potential exception that occurred during the call are
 * passed to {@link LongRunningActionCallback.onLongRunningActionFinished},
 * which will be called on successful or unsuccessful completion of the
 * Callable.
 * This code is in the public domain. You may use, alter, and redistribute it
 * free of any charges or obligations, with the following exceptions:
 * 1. You are not allowed to remove the statement naming the original author.
 * 2. You are not allowed to remove this license statement.
 * @author Matthias Kaeppler
public final class LongRunningActionDispatcher<ResultType> {

    private Context context;

    private LongRunningActionCallback<ResultType> callback;

     * A progress dialog shown during long-lasting operations
    private ProgressDialog progressDialog;

    private Handler finishedHandler = new Handler();

    public LongRunningActionDispatcher(Context context,
            LongRunningActionCallback<ResultType> callback) {
        this.context = context;
        this.callback = callback;

     * Invoke this method to start long running operations which may block your
     * activity and therefore the main UI thread. A progress dialog will be
     * shown while the operation is executing.
     * @param callable
     *            The callable
     * @param progressDialogTitle
     *            The progress dialog title
     * @param progressDialogMessage
     *            The progress dialog message
    public void startLongRunningAction(final Callable<ResultType> callable,
            String progressDialogTitle, String progressDialogMessage) {

        progressDialog =, progressDialogTitle,
                progressDialogMessage, true, false);

        new Thread(new Runnable() {

            public void run() {
                ResultType result = null;
                Exception error = null;
                try {
                    result =;
                } catch (Exception e) {
                    Log.e("ERROR", e.getMessage());
                    error = e;

                final ResultType finalResult = result;
                final Exception finalError = error;
       Runnable() {

                    public void run() {
                        onLongRunningActionFinished(finalResult, finalError);

    private void onLongRunningActionFinished(ResultType result, Exception error) {
        callback.onLongRunningActionFinished(result, error);
 * This code is in the public domain. You may use, alter, and redistribute it
 * free of any charges or obligations, with the following exceptions:
 * 1. You are not allowed to remove the statement naming the original author.
 * 2. You are not allowed to remove this license statement.
 * @author Matthias Kaeppler
public interface LongRunningActionCallback<ResultType> {

     * Called when the callable provided to
     * {@link LongRunningActionDispatcher.startLongRunningAction} completes.
     * @param <ResultType>
     *            The result type of
     * @param result
     *            Whatever the callable returns if it completes successfully, or
     *            null if an exception was thrown
     * @param error
     *            Whatever the callable throws if it executes in error, or null
     *            if it completed successfully
    void onLongRunningActionFinished(ResultType result, Exception error);

January 24, 2008

Cowon iAudio D2 – PMP With Two Faces

Filed under: Hardware & Technology, Mobile Devices — Tags: , , , , , , , , — Matthias @ 10:23 am

I am currently in Tokyo for a couple of months and I commute five days a week between Soka-shi in the Saitama prefecture to Bunkyo-ku in Tokyo. In total, that’s a one hour trip two times per day, which may not seem that big of an issue to most people, but for my part, I am simply not used to it and it is really becoming a chore.

Obviously, it was time to upgrade my mobile gear and let go of my iPod Nano, which I learned to hate in its few months of use. Sound quality and headphones are almost ridiculously bad for a device with a 180€ price tag, I never got used to the navigation wheel, it operates very fuzzy and unprecise and the display is small, low-res and everything but rich in color. My biggest gripe however with the Nano — and iPods in general — is Apple’s inability (refusal maybe) to provide proper Linux support for their devices. Their iTunes software has still not been ported to Linux, and most probably never will. There are open-source solutions like GTKPod, Floola and various iPod plugins for popular Linux media players like Rhythmbox, Banshee or Exaile, but I have used them all, and most of them are buggy, difficult to use or do not support newer iPods. Being an open-source aficionado and full-time Linux user myself, I have to face the truth: iPods simply do not fit into my setup. I admit it though, the iPod Touch looks sexy and I thought about buying it. I would have loved to have Wi-Fi on my PMP. But, considering these points and the fact that almost everyone between 10 and 30 is running around with an iPod these days, my urge to buy one has somewhat declined — or, as some user on the forums put it: “It is my personal opinion that owning a soul and owning an apple product are incompatible concepts”. Although my attitude towards Apple products ain’t that radical, I can definitely see where he is coming from.

Long story short, I went with Cowon’s iAudio D2, the 4GB version, in white. South-Korea based Cowon has made itself a name for building portable audio players with excellent sound quality, and best of all, which can be used with Linux, because they do not use a database model that can only be updated by means of a proprietary software (such as iTunes or Sony’s equivalent for their Walkman players). Instead, the D2 is recognized by the system as a USB mass storage device and you can simply drag-and-drop your music and video files onto the respective folders. Easy and simple. For Windows users, Cowon also ships their JetShell and JetAudio software for transferring and converting media files.

The device is small and handy (though maybe a bit thick — check this site to see how its size compares to an iPod Touch) and sports a high resolution, color rich display which is operated by touch. In fact, the only buttons on the D2 are the power and hold button (which are incorporated into a single snap-slider, very cool), a menu or “M” button (which can be configured to do different things), and two buttons for volume control. Navigation using the touch screen is responsive and for most parts straight forward. The default user interface already looks really sleek, but if you do not like it: it’s skinnable. For those people whose fingers aren’t slim anough to hit the (sometimes really small) on-screen buttons, Cowon also packs a plastic pointer with the D2.

Sound quality is great, it’s lightyears ahead of an iPod. Moreover, the D2 has the most capable equalizer I have ever seen on a PMP, it lets you adjust an almost ridiculous amount of options. The earphones bundled with the D2 are decent, but maybe not great. Still, much better than the ones coming with a Nano. Video playback is fluent, and the 16 Million colors display is crisp, which — despite its small size (2.5 inch at 320×240 pixels) — lets you read smaller text as well.

Concerning audio formats, the player supports a much wider range of codecs than most other players I have seen to date, including OGG, which will make many Linux users happy (at the time of this writing, OGG support is buggy on the D2 as some OGG tags are not properly read by the player; playback support is there however). For the video support, the D2 unfortunately doesn’t shine as bright. In fact, this is one of my biggest gripes with the D2: It doesn’t play videos encoded with the AAC audio codec, the format employed by Apple which almost every website that syndicates podcasts uses. Instead, the D2 can only play videos with MP3 encoded audio. This is extremely annoying, as you have to fall back to a video transcoder in order to play back video podcasts downloaded from the internet. There is also some confusion about the actual video codec and container format (I am no expert on this, so please anyone correct me if I’m wrong): The player is often tagged as an MP3/MP4 player, which is supposed to indicate that it can play back MPEG-4 encoded video (it supports the XviD codec, I am not sure about other MPEG-4 codecs). Technically, this is wrong however, because MP4 does not refer to the video codec, but the multimedia container format, and the D2 does not use MP4 here, but AVI (the format introduced by Microsoft in the `90s). Although the specs are silent about the supported container formats, my D2 won`t even display video files ending in .mp4, but it does display all files ending in .avi.

Another extremely annoying issue I am having with my D2 is its seemingly buggy support for ID3v2 tags. Although my MP3s are properly tagged, they always show up in the Music Library in wrong order, that means, not sorted by track number. For albums where order matters, like DJ mixes or audio books, this is a show-stopper, as there is no support to manually sort tracks on the D2. As a fallback, one has to go through the D2’s file browser instead. I seriously hope this will be fixed with a future firmware update.

To draw a conclusion, I think the D2 is a somewhat two-faced PMP. It does so many things right, like providing OGG support for Linux users, but then again, the support is buggy or incomplete. Then it provides lots of audio codecs, which makes it very versatile in that department, but for video, it only supports a format that almost nobody on the WWW uses to distribute podcasts — the killer application for portable media players! Concerning the user interface and functionality, light and shadow continue to co-exist on the D2: There are two (!) different calculator programs (gimme a break), but I can’t even do simple things like sorting my tracks or create playlists.

While I can still recommend the D2, if even for the mere lack of decent competition in the deserted lands of Linux-compatible PMPs, these points just make me pull out my hair and scream: “It would have been so simple, why, Cowon, why?!”.

Find below some reference and software proposals on how to operate the D2 under Linux.

Podcast management: GPodder — a very decent podcatcher for Linux (GTK-based)

Video conversion: iRiverter* — get the D2 device profile here

* some Ubuntu Linux users (including me) had problems running iRiverter. If you get an exception about a missing SWT library, try following this proposed solution, which fixed the problem for me.

UPDATE 2008-01-26: Modified section about video and codec support

Create a free website or blog at