问题
I have a problem with Android service restart. I am building against API version 7 and running on a device with Android 2.3.3.
The problem is, that when my service is killed by the system and is later restarted, only the onCreate()
of my service is called. code in onStartCommand()
is not executed. If I start my application for the first time, the code in onStartCommand()
is normally executed and all works fine, until system kills my service, then the service will not restart correctly.
Documentation says that onStartCommand() is always called when a service is restarted. In the case of service restart, the onStartCommand()
should be called with null intent. This is not my case.
Any idea why this could happen?
回答1:
You might be seeing a bug in Gingerbread. There was a thread in the android-developers group about it: onStartCommand bug thread
See the post numbered 26 by Dianne Hackborn for details.
回答2:
This is a bug in Android 2.3 (API level 9), which got fixed in API level 10.
From Dianne Hackborns post regarding this issue:
Okay, this did indeed break in 3.3. [sic!] The change was from August of last year. This is the change that broke it:
https://android.googlesource.com/platform/frameworks/base/+/5474b0f8603ee66413c3e44600ca46f162f3089e
Note that the git commit link previously did not work. Click here for a working mirror link to the commit and line that is causing the bug.
Also she meant 2.3, but wrote 3.3. She later corrected it and provided a suggestion for a workaround:
Sorry yes I meant 2.3.
This has been out in the code base since the GB code was released, so there will be who knows what devices that ship with it.
The problem is not that services are not being restarted, just that their onStartCommand() is not called with null at that time. The onCreate() method is still called. As a work-around, you could probably just post a message in onCreate() and set a flag in onStartCommand(); if you haven't received an onStartCommand() by the time the message is processed, then you probably aren't going to get the null Intent call. (If you need to do this at all... generally for things like registering receivers, you really really want to do this in onCreate(), since that method is only called once.)
She also wrote that this behavior will be fixed in the next platform update (post-3.0):
I'll get this fixed in the next platform update (post-Android 3.0); unfortunately this code has been out in the source tree for a while, and in a couple releases now, so we'll need to live with the broken behavior on those versions. The service will still have its onCreate() called so you can do work there.
I assume the API level she meant was 10, and I can confirm that onStartCommand()
is called with null intents after a service restart when you switch from API level 9 to 10.
来源:https://stackoverflow.com/questions/5394983/no-call-to-onstartcommand-follows-the-restart-of-a-crashed-service-in-android