Wednesday, June 2, 2010

Headset Blocker

If you own a Nexus One, you may be familiar with this scenario: you load up your N1 with some rocking tunes. You plug in your headphones and go out exercising with it. Suddenly, the tunes start skipping. Why?

The problem is that the headset jack is interpreting what you are doing as a control signal. The exact cause hasn't been shown to me yet; there are a number of theories from a lack of software noise filtering to the difference between TRS and TRRS connectors. Regardless, it's a serious issue - some people can't even listen to music in their cars with the N1 because it skips so much.

Luckily, in the last few days I was shown an answer. The control commands from headsets are actually sent out as a chain broadcast, MEDIA_BUTTON. As with any chain broadcast, your receiver can abort the broadcast. So the simple solution is to make a BroadcastReceiver with an ultra-high priority that intercepts and aborts the MEDIA_BUTTON broadcast.

To that end, I've put a small app on the Market, Headset Blocker. It's a small, free widget that allows you to enable/disable blocking of the MEDIA_BUTTON broadcast. You can get it here:

QR code for Headset Blocker

The source code is here.

One interesting choice I had to make when writing this app was how to toggle the blocking. I had one of two options:

1. Use SharedPreferences to track when blocking is enabled. Capture all MEDIA_BUTTON broadcasts, but only abort when the preference is enabled.

2. Enable/disable my app's BroadcastReceiver. It will always abort when enabled, but is only enabled via the widget.

I went with the latter option, as I felt that would save just a little bit more battery when disabled (as the BroadcastReceiver itself would be disabled).

Sunday, May 23, 2010

Android: Serializable Considered Harmful

This is an old problem, but anyone I can convince not to use Serializable on Android will help the system as a whole.

There is some data saved between launches of my application - a list of complex objects. When I first learned Android I assumed that the fastest way to get the app up and running would be to slap Serializable on my data classes and call it a day. It certainly got things up and running quickly, but with some serious performance issues. I never noticed this in early testing because I only saved a few objects at a time. However, when I got up to 5+ objects the system started to slow down, and at 10+ it ran like molasses. There's not normally that many objects, but it's still something to be concerned about. It's not like I was doing anything complex, however - it was simply that Serializable is that slow.

Not only that, but I had to live in constant fear of changing the data structure. If enough things changed I would have to write my own serialization processes to work with backwards compatibility. Yuck.

I switched to using JSON to store all my data and this decision has made my life so much better. Android comes with a good JSON library and it's pretty simple to add JSON support to classes. JSON is much, much faster than serialization and comes out with much smaller results, too (you can even GZip the results to make them smaller still). To put it in perspective, the save time is now unnoticeable, whereas I could count the seconds using Serializable; and the file size was reduced by an order of magnitude.

Not only is it better for saving data, it's a very easy way to pass data between components. When I first started, I saw three ways to pass data between components: Serializing, parceling, or storing data in the Application context. Serializing was proving too slow, parceling is really a pain in the ass, and the last solution is harder to integrate with later on (no one else can call your component). JSON has proven a much better solution - it's fast enough to get by, but not nearly the pain in the ass that Parcels are.

Monday, May 3, 2010

ViewFlipper "Receiver not registered" Error

There is this error that plagued me for a few months. If you use a ViewFlipper, this error will pop up on Android 2.1 devices every once in a while:

java.lang.IllegalArgumentException: Receiver not registered: android.widget.ViewFlipper$1@44b6ab90


It does not affect any devices before 2.1, and so what was troubling at first was that the 2.1 source code wasn't yet released so I could't diagnose the issue. Everyone knew it had to do with orientation changes on an Activity with a ViewFlipper, but why exactly it happens isn't clear (I took my own stab at it, but was incorrect about the exact cause; it just seems to happen randomly).

Thankfully, the source has been available now for a while. Obviously, the problem is that onDetachedFromWindow() is somehow being called before onAttachedToWindow(); but how do we come up with a workaround until it is fixed at Google?

One simple solution is to override onDetachedFromWindow() and catch the error from super:

@Override
protected void onDetachedFromWindow() {
try {
super.onDetachedFromWindow();
}
catch (IllegalArgumentException e) {

}
}


The only problem with this is that the error is thrown before calling updateRunning(). A simple workaround for this is to call stopFlipping(), as that will kick off updateRunning() without any negative side effects:

@Override
protected void onDetachedFromWindow() {
try {
super.onDetachedFromWindow();
}
catch (IllegalArgumentException e) {
stopFlipping();
}
}


You should only use this version of the class on Android 2.1 phones, as they are the only ones requiring the fix.

EDIT May 25, 2010: ViewFlipper bug still occurs in Android 2.2. I sure hope you didn't filter based on apiLevel == 7; better to use apiLevel >= 7.

Why They Can't Find Your App

The Android Market is a mixed blessing; on the one hand, I much prefer the near-instantaneous publishing time for applications. It makes things a lot less stressful; if there's a terrible bug you can fix it quickly instead of having to go through Apple's approval process all over again. On the other hand, it has a number of bugs and limitations that are frustrating.

One of the most common support emails I get is "why can't I find your app on the Market?" This is a sad email, one of a customer lost; and over time (from contact with Google or perusing the net) I've come up with a good list of reasons why customers can't find my applications. Here it is, to help others diagnose the dreaded customer-who-would-be (in order of most likely to least likely):

1. The customer has an older version of Android that your app does not support; for example, if you support 2.x but the user is on a 1.5 phone.

2. Paid apps are only supported in some countries; if the customer is not in one of these countries, then you will not be able to find or purchase any paid applications. The list of supported countries can be found here.

Note that the customer can't simply move to a different country, either; this limitation is dependent on where your phone plan originally comes from. (Thanks to a European customer who confirmed this for me on a business trip!)

3. The customer is using a Google Apps account, rather than a gmail.com account. This can either cause the app not to appear at all, or in some cases make it unpurchaseable. More details can be found here.

4. The customer has a recently released phone and Google hasn't "fingerprinted" that device yet. This blocks all paid apps from that device. The only solution is to wait until Google fingerprints; it was kind of a pain with HTC Desire, at it took them a few weeks to get around to it.

5. The customer is using a non-standard build of Android (that is, rooted and installed a custom ROM). Some of these builds cause the Market to malfunction and fail to display paid apps.

6. The customer is using an Android Developer Phone and your application has copyright protection enabled. ADPs aren't allowed to view copyright protection applications. More info here.

7. This is by far the least likely situation, but you can't buy your own app under the same account as you published from!

Sunday, April 11, 2010

The Missing Manual - Android Drawables from XML

I have been fairly frustrated with a gap in the Android documentation recently - the file formats for creating Drawables from XML. Drawables XML has been pretty useful to me in the past in creating gradients; I'd rather use it than create 9-patches all the time. However, the Android documentation is strangely silent about the format; they provide a few samples, but as far as I know there's nothing beyond that.

I've taken it upon myself to study the source code and create a missing manual for all the possibilities for Drawable XMLs. The data was gathered from the Android source code, from the android.graphics.drawables package. I was surprised to find a lot of really useful code I wish I'd known about a long time ago; regardless, I was able to figure out all of how Drawables XML works.

Without further ado, here it is: the missing manual on Android Drawables via XML. I hope this lessens the pain someone else has slightly.

Wednesday, March 10, 2010

Uri and Android 1.5

I came across an interesting Android bug the other day that deserves some mention.

I was creating an Intent, setting some data for it, then calling startActivity(). The data Uri was created via Uri.Builder. Let's say, for example, the Uri I wanted was "http://google.com". The code would look like thus:

Intent intent = new Intent(context, TestActivity.class);
Uri.Builder builder = new Uri.Builder();
builder.scheme("http");
builder.authority("google.com");
intent.setData(builder.build());
startActivity(intent);

This works in 1.6+. But an interesting thing happens if you try this in 1.5... it blows up in your face with NullPointerExceptions! To answer why, I ended up digging around previous versions of the android.net.Uri class. It turns out that, previous to 1.6, Uri expects you to fill out every part of the Uri - including the query parameters (parts following ?) as well as the fragment (part following #).

The fix is to add dummy parameters for the sake of Android 1.5:

Intent intent = new Intent(context, TestActivity.class);
Uri.Builder builder = new Uri.Builder();
builder.scheme("http");
builder.authority("google.com");
builder.appendQueryParameter("ignore", "ignore");
builder.fragment("ignore");
intent.setData(builder.build());
startActivity(intent);

This isn't a problem if you already are using all parts of a Uri, or if you only support Android 1.6+.

Monday, January 18, 2010

ViewFlipper and Memory Leaks

Have you ever had a mysterious memory leak on Android when your code seemed clean as a whistle? I sure have, and I finally figured out why: ViewFlipper.

It turns out that when you call ViewFlipper.startFlipping(), it sets up a loop via messages which flips between its child Views. This is all well and good, but there's no code which detects that the ViewFlipper itself is no longer being displayed and should be canned. So the ViewFlipper keeps a hold on itself and its children, who inevitably keep a hold on their Context, and bam - gigantic memory leak. Depending on how much memory your Activity takes up, all you need to do is start changing the orientation of the ViewFlipper's containing Activity a few times and you could crash your application.

The solution to this is relatively simple: just call ViewFlipper.stopFlipping() in your Activity's onPause(), and then have it start flipping again in onResume().

There is, however, one small catch. Since ViewFlipper uses delayed messages, it's possible that a user can pause your activity then resume within the amount of time between flips (if they hit power then menu in quick succession, for example). The way ViewFlipper is setup, this means you can end up with multiple flip messages being passed around, resulting in faster flipping than intended. Unfortunately, the only solution I can think of to this is a real hassle (you would have to intentionally delay some time before resuming flipping in onResume()), so I'm just ignoring it for now.