Miguel Botón Miguel Botón - 4 months ago 19
Android Question

Avoid Android service getting killed?

I have an application that implements a remote background service. This service is implemented to download files in threads (I would say this service works as a download manager).

When I want to download a file, I send the url to the service, and the service starts a thread (I was using AsyncTask but it only worked in Android 4.1) where it actually downloads the file. But sooner or later the download stops, and I was able to know that because the notification I show doesn't get updated anymore. When I click the notification to cancel the download, a pending intent is sent to the service to tell it to cancel the download, but not download is cancelled as the service is re-created (onCreate gets called).

Edit: Forgot to say that I return START_STICKY in onStartCommand()

What solutions do I have? Any way to avoid the service getting killed?

I was looking also into startForeground(), and that would be ok if the service target is to download only one file but I want support to download multiple file simultaneously.

Thank you.

Answer

About the only way to prevent your service from being killed is to use startForeground(). Even this won't guarantee that Android won't kill your service, but there isn't anything better. We've had good success using foreground services.