Android service interruption
I am developing a location tracking app. I have the mechanics of the app that periodically detects location change in a service.
My service runs consistently which is what I want 开发者_开发知识库but occasionally I find the service has stopped. In my manifest, I set android:configChanges="orientation|keyboardHidden"
on my main activity so it does not get re-created each time the orientation changes but do I need to do that for each activity and service?
Also, potentially it's the operating system killing my service. In that case, is there a way to force the system to overlook my service or to automatically restart the service after a set number of minutes?
Thanks!
My service runs consistently which is what I want
Your users may well disagree.
but do I need to do that for each activity and service?
You probably should not be doing that for any component. This is mostly for cases where the UI is too complex to successfully re-render in a new activity (e.g., some games, video playback) or where the activity is also being locked to a specific orientation. Regardless, there is no android:configChanges
attribute for services.
potentially it's the operating system killing my service
The OS will shut down leaked services, such as yours, to prevent excessive battery drain.
is there a way to force the system to overlook my service
You can use startForeground()
.
or to automatically restart the service after a set number of minutes?
Return START_STICKY
(or possibly START_REDELIVER_INTENT
) from onStartCommand()
.
Even better would be to reconsider your approach. Keeping location tracking on -- particularly GPS -- is a significant battery drain. There are fairly few applications that should be continuously monitoring location in the background. If you only really need location fixes every so often (e.g., every 15 minutes), use AlarmManager
to kick off your service to get a fix, then have the service call stopSelf()
to go away until the next alarm.
精彩评论