If you've been programming on the Android platform for more than a day, you've probably experienced an Application Not Responding (ANR) dialog (Figure A). An ANR occurs when Android detects the system is unable to respond to user input for more than a few seconds, and the result is the dreaded your-app-has-stopped-responding dialog. If you're interested in the nuts-and-bolts of what causes an ANR and techniques for avoiding them in your own apps, Google has a great article on these subjects.
Fortunately, for most developers, it doesn't take long to master the techniques required to keep the user interface responsive. But even after doing professional Android development for five years, I still occasionally find myself trying to ferret out an ANR that managed to sneak into my code base.
There are a number of ways to find the bottleneck in your code that causes an ANR. One technique I've begun to use recently is the trace file that the system generates on the device whenever an ANR occurs. What's that you say? You didn't know the device was logging all the ANRs? Well, read on my friend, and I'll show you just how easy it is to get your hands on the trace file.
1. Open a command window and find the platform-tools directory of your Android SDK.
$ pwd /Applications/adt-bundle-mac-x86_64-20130917/sdk/platform-tools
2. Connect the device you received the ANR on via USB and issue an ADB pull command.
./adb pull /data/anr/traces.txt
./adb pull /data/anr/traces.txt 3538 KB/s (200372 bytes in 0.055s)
3. At this point the file should be on your local drive.
You can open the file in any text editor. You'll have to dig through the time stamps to find out exactly what was going on when your application hung. The log seems to get appended to continuously, so there may be quite a bit of trace data to filter through. Still, it's a relatively quick and painless way to begin narrowing down an ANR, especially in instances where the exact circumstances that cause the ANR are tough to reproduce on the debugger.
William J Francis began programming computers at age eleven. Specializing in embedded and mobile platforms, he has more than 20 years of professional software engineering under his belt, including a four year stint in the US Army's Military Intelligence Corps. Throughout his career William has published numerous technical articles, as well as the occasional short story.