Android onCreate Service called when Activity onDestroy called

≡放荡痞女 提交于 2019-12-05 17:26:40

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.

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