Warning: Coding ahead...
Releasing my own Android app has taught me an amazing amount about Java, Android and the state of commercial app libraries in general. I now have a deep and profound respect for what I considered "trivial" apps, just a few short months ago.
My first app, which still isn't in its final release form (though it's on the Android Market in beta form) had one pretty large problem: it loads images, and at times it would get stuck, forever downloading an image. The solution was to actively manage tasks, of course, but I'm new to Java, and I didn't know much about its task management facilities. I had assumed that it was fairly straightforward, and I would simply:
Alas, that's not it. as I quickly discovered, the AsyncTask class's cancel method is more of a hint. It tells the task that it should wrap up what it's doing, by setting a semaphore (or whatever the underlying mechanism is) and it's the job of the child task to check in with the isCanceled method and react accordingly.
This presented a great deal of complication for me. When the user presses the "back" button or clicks outside of the progress dialog to cancel a download, I don't want to leave a stranded download going, but the download code isn't mine, it's part of the BitmapFactory class. How can I tell it to stop what it's doing? The solution is fairly complicated, and I hope that I'll refine it or find there's a better way over time. Here's what I arrived at (after the break):