Create only one instance of Service (Android)

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-27 08:34:27

How can I make sure that only one instance of Service is created?

There can only be one instance of a given Service.

It gives different hash codes even when I am sure that the same function is running twice (downloading).

Then this is not the Service. Or, the service had been destroyed and recreated between logs.

And the service can run for minutes until it is completed, therefore the service can be binded to/created by many Activities

Then the Service is probably being destroyed and recreated. If you need the service to run for minutes, you need to use startService() and stopSelf() in addition to your bindService() and unbindService() calls. Or, perhaps you do not need to bind at all, in which case you might consider using an IntentService, since that automatically gives you a background thread on which to do your downloads.

I experienced situation similar.
If you have been written as follow, instance can be created over one .

bindService(new Intent(getApplicationContext(),  WeatherService.class), mServiceConnection, BIND_AUTO_CREATE);

Try to write once as follows.

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