Bacon Rank Android App Details

Bacon Rank is currently my most ambitious Android project from UI and background processing point of view. It has custom UI controls and it deals gracefully with long running network operations.

Let’s start with the custom SeekBar first, which is used to select the number of strips of bacon you ate. When you have a touch screen device, especially with no physical keyboard, you want to avoid situations where the user is forced to type anything. In my case SeekBar works great, since you can’t eat that many strips of bacon at one sitting. To draw the SeekBar with custom images I created bacon_seekbar.xml in the drawable folder:

<layer-list
  xmlns:android="http://schemas.android.com/apk/res/android"
>
  <item
    android:id="@+android:id/background"
    android:drawable="@drawable/progress_mediumbacon" />
  <item
    android:id="@+android:id/SecondaryProgress"
    android:drawable="@drawable/progress_rawbacon" />
  <item
    android:id="@+android:id/progress"
    android:drawable="@drawable/progress_cookedbacon" />
</layer-list>

The progress_* drawables are PNG images.

In the main layout I use the custom SeekBar and set a custom thumb (a PNG image of a skillet):

<SeekBar
    android:id="@+id/SEEKBAR"
    android:layout_below="@id/BACON_STRIPS"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:max="20"
    android:progress="0"
    android:secondaryProgress="0"
    android:paddingLeft="32px"
    android:paddingRight="32px"
    android:progressDrawable="@drawable/bacon_seekbar"
    android:thumb="@drawable/skillet"
    />

SeekBar has three states (if you count background), but I am really just using two. The weird part is that I thought I would use background and progress states, but I could not get that to work. Instead, I am using SecondaryProgress as background, and background is not visible anywhere. In onCreate I set up the SeekBar:

mSeekBar = (SeekBar)findViewById(R.id.SEEKBAR);
mSeekBar.setOnSeekBarChangeListener(this);
mSeekBar.setMax(PROGRESS_MAX);

In onProgressChanged method I update the amount in the UI and that is about it for the SeekBar. I think it looks pretty nice, but it would be better if I could make it look more 3D:

The trickiest part of the application was handling of the network activity while allowing for screen orientation changes. None of the tutorials I’ve read or the stackoverflow questions and answers regarding this seemed workable (or maybe I did not understand them). The problem is this: suppose in your activity you start an AsyncTask for the network activity. This is what is actually recommended pretty much everywhere. But suppose your user then changes the screen orientation. By default Android destroys and recreates the current activity. Your AsyncTask is still going, but it does not know about the new activity, and your new activity has no knowledge of the AsyncTask. So what is the fix?

It turns out you can create a custom application object, which will be available as long as your process is running. So in your activity you can start the AsyncTask as before, but keep a reference to the AsyncTask in the application object. The AsyncTask needs a reference to the current activity to draw on the screen, which your activity keeps up to date. Basically set it on AsyncTask creation, null it during screen orientation and activity destroy, and restore when the activity is recreated. We also want to run an indeterminate progress indicator in the UI while network activity is going. In code this looks something like this (I’m omitting many irrelevant details):

public class BaconApp extends Application {
    public BaconRank.SyncTask mSyncTask = null;
 
    // ...
}
 
public class BaconRank extends Activity implements SeekBar.OnSeekBarChangeListener {
    // ...
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        // ...
    }
 
    BaconRank.SyncTask getSyncTask() {
        return ((BaconApp)getApplication()).mSyncTask;
    }
 
    void sync(String action) {
        ((BaconApp)getApplication()).mSyncTask = (SyncTask) new SyncTask(this).execute(getUserAgent(), mUserId,
                mBaconStrips.getText().toString(),
                action);
    }
 
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        SyncTask syncTask = getSyncTask(); 
        if (syncTask != null) {
            syncTask.setActivity(null);
        }
    }
 
    @Override
    public void onRestoreInstanceState(Bundle inState) {
        super.onRestoreInstanceState(inState);
        SyncTask syncTask = getSyncTask(); 
        if (syncTask != null) {
            setProgressBarIndeterminateVisibility(true);
            syncTask.setActivity(this);
        }
    }
 
    @Override
    public void onStop() {
        super.onStop();
        SyncTask syncTask = getSyncTask(); 
        if (syncTask != null) {
            syncTask.setActivity(null);
        }
    }
 
    public class SyncTask extends AsyncTask<String, Void, JSONObject> {
        // ...
 
        public SyncTask(BaconRank activity) {
            super();
            mActivity = activity;
        }
 
        public void setActivity(BaconRank activity) {
            mActivity = activity;
        }
 
        protected void onPreExecute() {
            if (mActivity != null) {
                mActivity.setProgressBarIndeterminateVisibility(true);
            }
        }
 
        protected void onCancelled() {
            // mActivity cannot be null
            mActivity.setProgressBarIndeterminateVisibility(false);
            clearActivity();
        }
 
        void clearActivity() {
            // call in ui thread only
            ((BaconApp)mActivity.getApplication()).mSyncTask = null;            
        }
 
        protected void onPostExecute(JSONObject result) {
            if (mActivity != null) {
                // Update UI
            }
            clearActivity();
        }
 
        protected JSONObject doInBackground(String... params) {
            // Do the network stuff
        }
 
        // ...
 
    }

You will also need to specify the custom application object in the AndroidManifest.xml:

  <application
    android:name=".BaconApp"
  >

And that wraps the Bacon Rank presentation. If you know how to do anything I presented above in a better way, please leave a comment. The application is also localizeable, so if you want to translate the app into your language let me know.

If you did not read it already, you might want to read about the application running baconrank.com, the server the Android application talks to.

baconrank.com Powered by Turbogears 2

The baconrank.com website was written with the Turbogears 2 web application framework. It is pretty lightly modified from the quickstart project.

In the UI front the quickstart project used a lot of images to make rounded corners and so on to make everything look good in cross-platform way. I dislike this practice, so I decided to see if I could take the basic layout and not use any images for corners and backgrounds and the like. I think the result looks pretty good in modern browsers, including the default browser in Android 2.1. border-radius and -moz-linear-gradient did the bulk of the work. Which reminds me that I forgot to look for the equivalent of -moz-linear-gradient for other browsers…

The template language I used was Genshi, both because it is the default that comes with TG2 and the quickstart project, but also because I wanted to try out another template language as well. The thing I like about Genshi is that it guarantees I get well-formed output. However, its use of XPath can be a pretty steep learning curve to someone who doesn’t know XPath (like me). I did not see how to control the whitespace around elements: in some cases I have elements one on each row, other times they end up on the same row. I think I also could not get a comment to appear at the end of the document (to put in page rendering time, for example, although it turned out you’d need to hack tg2 itself to get the rendering time – unfortunately I lost the link).

I originally had bigger plans for the application, including forum, password recovery and so on, but canned those plans for now because I realized I could not find enough time to do all those and ship something before the summer. Part of that I did get in, although it is only exposed to the admin user. Being the security-minded geek that I am, I hacked the auth code to use bcrypt. I also learned about doing password comparison in a way that does not leak information due to timing.

I designed the small protocol that the Android client uses to communicate with the server. Most operations are covered by the following:

Initial sync:

>>>request<<<
POST /users
@JSON@

>>>response<<<
201
Location: /users/123

>>>request<<<
GET /users/123

>>>request<<<
200
@JSON@

Add bacon:

>>>request<<<
POST /users/123
@JSON@

>>>response<<<
200
@JSON@

Incidentally, if you'd like to write another client (iPhone anyone?), let me know...

I wanted to wrap the client API in its own class, but could not get that to work as a separate class so had to just settle with a method that does way too too much. Something I hope I can visit later.

I really wanted to like Turbogears 2 since it is based on my favorite, Pylons, but I actually felt that TG2 was getting in my way almost as often as it was helping me. I am happy that I did not have to write the auth code from scratch, and having the admin area almost as easy as in Django were big wins, but since I did not yet implement the forum (where I think I could really have used more of tg2's strengths) I would probably have been better off with plain Pylons. The documentation has been in flux the whole time I've been working on my app, some things working, some broken, and I had to resort to comments at the end of docs and doing web searches to try and figure things out. There were periods of time when the dependent packages were out of sync, and you could not even get a working quickstart project without setting version limits. I think that the controller methods not returning the actual string to render can be potentially big headache (for me, I just could not get the timing information output into the end of the returned HTML). I'd say TG2 has potential to be great, but right now things feel a little bit too unfinished. I know 2.1 will fix some of the issues I run into, but I don't know if anyone is looking at checking and cleaning up the documentation.

Bacon Rank Released

I am pleased to release Bacon Rank, the application you have been waiting for to count your bacon! (You may not have realized this, of course. I forgive you.)

I’ve been working on this application combo since last November, a few hours here and there. The server piece is a Turbogears 2 application, while the client piece is an Android application. As a whole, they form the Bacon Rank application ecosystem. The idea is that whenever you eat bacon, you submit the number of strips of bacon you ate, using the Android client, to the server. The server returns your statistics, including your rank compared to other users of the system. It is clearly a not very serious application, but it presented some interesting programming challenges.

I’ve been going through various Python web frameworks, and this time I wanted to learn about Turbogears 2. There isn’t anything especially groundbreaking about it, but I think it marks the first time I am actually running a real service. Of course it is also tied to the Android application, which makes it interesting.

The Android application is a bit more ambitious from engineering point of view. In the UI the trickiest piece was a customized SeekBar: uncooked bacon that becomes cooked as you move a skillet over it. I was also able to finally figure out how to make a background network request survive screen orientation change gracefully.

I am also experimenting with Twitter for the first time as a communications channel for the project.

In the next two posts I will explore the server and client pieces in more detail.

New Adventures

This news is a couple of weeks old, but I thought better late than never… For the past couple of years I was working at SpikeSource, on a variety of things ranging from Pylons and CherryPy applications to designing RESTful APIs and client libraries and even CakePHP and Java web applications (horror of horrors ;) ). It was never a good fit culturally, though, so just before my two year anniversary came around I decided I needed a change.

I decided to be very focused on my search: Python web application development, startups, and ideally located from Sunnyvale to Palo Alto. I used mostly craigslist.org and startuply.com for my search, with a couple of hints from friends. I applied to eight jobs, and got five interviews. I was quite surprised that there were so many companies matching my preferences within such a small area hiring at the time when I was looking! I was also pleasantly surprised that I got into as many interviews as I did; last time around I had a bit worse success rate. Hint: requirements aren’t necessarily requirements in job postings.

Unfortunately I learned I am bad at interviews aimed at Python web application developers. For some reason I find coding questions a lot easier to answer when they are in C. I was also badly prepared to answer a few questions related to web development; having not thought about something for a while makes a bad interview impression. Note to my future self: start practicing at least a week before interviews, practice in Python on problems designed to be solved in Python (maybe Python challenges, Facebook programming puzzles and the like), and check with friends for some common web developer questions. Assuming I were to look for that kind of job next time around, of course.

To make long story short, I decided to join Aahz at Egnyte. Egnyte provides cloud storage, backup and sharing services. My first task involves integrating new UI design to a CherryPy application using Cheetah templates. I am also working on a Mac after many years on Linux.

Nexus One Radio Follow-up

As you have probably gathered by now, my earlier announcement was an April Fools’ prank. Unfortunately I had forgotten to adjust my blog settings for Daylight Saving Time, so the URL and time on the post refer to the previous day, even thought it was posted a few minutes into April 1st.

I got the idea for the prank out of the blue around 11 pm, and had the application ready a few minutes before midnight, so I waited for that to pass to create the .apk and post it to Android Market. Most of the development time went into finding a suitable image of a radio and scaling and cropping it (as you can guess, Gimp gives me trouble). I used the Creative Commons search engine to find the image.

I was pretty satisfied with the results. According to Android Market statistics, the application was installed 10741245 times (although the real number is somewhat higher since the statistics don’t update in real time), has 7787 ratings with average around 3.5. Not bad for less than 24 hours of exposure. Some of my favorite comments were from people who were fully on board with the prank:

  • Pretty good. Can’t seem to tune below 88.9
    anakin78z
  • OMG this best radio player ever. Pandora and Slacker don’t even come close.
    freddie
  • nice hack :) Will pre-sets be available in the future? :-p
    dbrowne
  • would be a 5 if the dialer was more accurate. great job dev! :)
    semeon

There were also others who seemed to have fully fallen for it without liking it ;) :

  • Wasted about 2 minutes of my life. . Don’t bother, feeble prank !
    Ian
  • I hate you.
    Tom

Of course there were also a number of spoilsports who just gave one star and mentioned it was a prank app. Shame on you.

I got one support email asking if it would work on HTC Touch. Also the comment in the original blog post about collaborating on a droid project makes me wonder if I fooled that person or if they were in on it.

Seems like I also fooled some people on reddit.com.

Since this was a joke app just for today, I’ve unpublished the app from Android Market. So if you are one of the 300+ people who still got the app installed, you are suddenly the owner of a rarity :)

Nexus One Radio

If you have been wondering why I haven’t posted in a while, it is because I have been hard at work on my most ambitious Android project to date. When Google came out with the Nexus One phone I was quick to grab one. But one thing about the hardware has always bugged me. The Nexus One contains an FM radio, but there wasn’t any way to use it from software. Until now! I have painstakingly tracked down the hardware details and reverse engineered the API needed to get the radio to appear. The UI is pretty primitive. Go grab yourself an early build of Nexus One Radio (see ratings on Cyrket). Search for it in the Android Market!

Update: Please see the follow-up!

GPS Still on After LocationManager.removeUpdates?

My most recent Caltroid update added map view with two location listeners: one coarse (=network) and one fine (=GPS) location listener. Or so I thought. Even though I was calling LocationManager.removeUpdates() for both location listeners, I could still see the GPS icon active at the top, and logcat showed GPS activity still going on. Users were reporting drained batteries. Not good.

It took me a few false starts until it occurred to me that I was also using MyLocationOverlay to automatically put the user’s location on the map. Well, this obviously requires location updates. I had somehow falsely assumed that as soon as the map view went away, MyLocationOverlay would stop listening to location updates. That is not the case. You must explicitly call MyLocationOverlay.enableMyLocation() to start updates, and MyLocationOverlay.disableMyLocation() to stop updates.

After figuring this out the fix was easy. In my map view’s onResume() I request location updates for my two location listeners and enable MyLocationOverlay, and in onPause() I do the opposite. No more drained batteries!

Caltroid with Map

My latest update to Caltroid added two notable new features: the next available train is highlighted and scrolled into view automatically, and the simple locate function was replaced with a custom Google Map view. The map has Caltrain stations as an overlay, and the map starts out centered and zoomed so that all stations should be visible. While the map is active, it will update the users current position (using GPS and/or network location), and showing the nearest Caltrain station (as the crow flies). It is possible to select this station as the starting station from the map. Additionally, it is possible to tap the directions button on the map to get driving directions to the nearest station.

Working on the map feature was a pleasure now that I actually have an Android device.

If you look at the map view carefully, you will notice the text is written in transparent grey boxes with rounded corners. A stackoverflow question showed me how to do this with custom shape resource. I also based the map overlay largely on this blog post.

I had agonized for the longest time about how to get highlighting for the the list view. Then I stumbled into a couple of stackoverflow questions that showed me the way. In the end the best example I found was the List14 sample in Android API demos. I just need to call convertView.setBackgroundDrawable() with the right drawable, and make sure to add the following attribute for the list view: android:cacheColorHint="#00000000"