Question

I am investigating if there are any ways to prevent an android service being killed because of uncaught exception.
We have 10 UI apps talking to 5-6 services. The platform is Android 2.2.
Because of unforeseen conditions, some of the logic in the services are throwing exceptions now and then. That is causing those services getting killed with those annoying ANR popups. While we work on a solution that fixes the root cause of those exceptions, I like to prevent Android from killing the offending service.

It looks like I can register Uncaught default exception handler for all the threads in the services. That just gives me an opportunity to log something about the exception. That is good. I came across many postings that used this technique to log the crash info to a file for later use. People suggested not to throw the original exception to prevent the ANR popup. I also found some articles that suggested it can leave your service in half dead state. The right thing to do is kill the service and restart. Killing and restarting is not an option I am interested in.

I didn't quite understand the half dead state part if you don't throw exception. I am going to investigate further. Meanwhile I am wondering if people have suggestions.
My goal is to prevent ANR popups. I want my code to make the decision whether to restart a service or not instead of Android framework deciding it for me.

What I am curious to find are:
1) Is there any flag in manifest you can change to prevent services from getting killed by framework code?

2) Are there any methods you can override in a Service that lets you handle uncaught exceptions, but still let the service thread to go back to waiting state for the next request from a client?

Thanks for suggestions.

Videoguy

Update:
The Uncaught default exception handler doesn't help here. It gives you an opportunity to log something, but the service thread still exits.

You need to change android framework so that it doesn't kill processes. ActivityManagerService.java in android framework has different thresholds how long a service can run without any clients, how many background activities/services you can have, timeouts for service and ui initialization. We bumped those values up.

Was it helpful?

Solution

One common way that developers help keep their services from being killed is to use a persistent notification (in the notification bar), which is usually toggled on through settings. So, if the user is having problems with the system killing the service, they can toggle on the notification.

OTHER TIPS

Is there any flag in manifest you can change to prevent services from getting killed by framework code?

No.

Are there any methods you can override in a Service that lets you handle uncaught exceptions, but still let the service thread to go back to waiting state for the next request from a client?

No.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top