Android onCreate Service called when Activity onDestroy called

五迷三道 提交于 2019-12-22 09:13:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!