m0skit0
m0skit0

Reputation: 25873

Debugging a Service main thread

If I set up breakpoints and the Service main thread stops there, the whole Service process is shut down by Android after some seconds (around 5). Also almost no operation is possible when this happens (cannot evaluate expressions, cannot see current context variables, etc...). If it's not the Service main thread, then there's no problem, debugging works just fine.

The Service is launched through an Activity.

So, is there a way to debug a Service main thread without Android killing it?

Thanks in advance!

Upvotes: 3

Views: 1024

Answers (1)

nickmartens1980
nickmartens1980

Reputation: 1593

No not if you MUST use the main thread. That said there are a few ways to make it not run on the main thread, depending on how you use the service.

in case you run from onStartCommand: Run you process in an executor (in a different thread) or use in intent service which will automatically do this for you. In case you are using onbind: The same applies, run it in the background, but intentservice can't help you with this. If this is the case let me know I'll show you how to do this.

Update:

There may be one development option that could help you, in the development options of your device, enable show all ANRs. This could potentially show an ARN when you block the services main thread instead of just killing it (this option exists on my phone running android 4.1.2)

If that doesn't work you could use this hack:

As you can't change the code of that service itself, you could try the following which is a bit messy and hackish. can't guarantee it'll work but it may be worth a shot.

Create a new service extending IntentService. Inside in onCreate create a wrapped service extending the service you want to debug. Like this. save this as a variable and call all your lifecycle methods on it. Except onStartCommand

mWrappedService = new YourServiceClass() {

    {
            attachBaseContext(WrappingService.this);
    }

    public IBinder onBind(Intent intent) {
        return super.onBind(intent);
    }

    @Override
    public Context getBaseContext() {
        return WrappingService.this;
    }        
}

In this example WrappingService is your new class and YourServiceClass is the service you are trying to debug.

Then in your onHandleIntent call the services onStartCommand method. This should work as long as the service class is not final.

Now you can at least debug this.

Upvotes: 5

Related Questions