Prevent multiple copies of an Android service

蹲街弑〆低调 提交于 2019-11-30 08:17:58

It all depends on which method you're putting the code in.

When you call startService only one service will be created at a given time. If the service already exists it will be reused. So the code in onCreate() will only be called if a service did not already exist.

However, each time you call startService the code in onStartCommand() will be run no matter what.

So yes only one instance of a service ever exists at a given time, but calling startService can have an effect.

The problem was I had declared my myService class to extend IntentService, not Service! Once I fixed that, it all worked as per the book!

IntentService stops immediately (automatically) after work is performed, BUT if you start it again till work finishes you are reused existing service instance and onCreate isn't called. So please be careful with IntentServices.

You are extending IntentService which will work as a worker thread. The service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work. So in your case your service stop itself after completing the task so it creates multiple times. You should use Service class and bind with the component.

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