问题
I have an activity that starts a service. If I exit to home screen and then from the recent apps list manually close the activity, onCreate is called again in the service.
So when the activity is destroyed, onCreate is called again (even though the service was running at the time onDestroy was called in the activity)
I don't want onCreate in the service to be called again. I know its a possible duplication of this: Android service onCreate is called multiple times without calling onDestroy BUT the solution suggested here of putting the service in another process doesn't work (at least on Android 4.4 kit kat)
Any suggestions?
回答1:
This is because upon killing the application from the "recently used apps" list, you're killing the service by force. There are two ways to avoid restart. The not so great way is to put the service in different process than the activity in the Android Manifest.
For example:
<activity ...
process:"com.example.activity.process" />
<service ...
process:"com.example.service.process" />
So upon killing the application the service is also not killed and restarted. The service will be terminated by Android as it sees fit if you go by this method.
The more correct way would be to use the onStartCommand()
method.
Simply add the following code to your service:
@Override
public int onStartCommand(Intent intent, int flags, int startID) {
return START_NOT_STICKY;
}
This will prevent the service from being restarted if improperly terminated i.e onDestroy()
is not called.
来源:https://stackoverflow.com/questions/23713882/android-oncreate-service-called-when-activity-ondestroy-called