Debugger this! Debugging an Android Service

I recently found out that I couldn’t hit any breakpoints in an Android Service I was developing. I found that this was easily sorted by adding the following line:

android.os.Debug.waitForDebugger()

This approach was suggested on various websites including StackOverflow and HelloAndroid amongst many. Great.

I found out much later than when I ran the code “in the wild” i.e. in a production environment unattached to a debugger, my application was failing.

Long story short, this is caused by the waitForDebugger() call, which will cause any code following your invocation to not be executed if there is no debugger.

I suppose I should have realised, but I had assumed that maybe the runtime or the call itself would be clever enough to know whether the application was in debug mode at all, and ignore it if it wasn’t.

But thankfully, we can do that:

if (android.os.Debug.isDebuggerConnected)
{
    android.os.Debug.waitForDebugger()
}

So I’d recommend this is the approach you take over having to remember to take that call out.

1 thought on “Debugger this! Debugging an Android Service”

  1. It should be:
    if (android.os.Debug.isDebuggerConnected()) {
    android.os.Debug.waitForDebugger();
    }

    But I meet trouble that when I press F8 to step the procedure (Eclipse), the service freqently trashed.

Leave a Reply

Your email address will not be published. Required fields are marked *