There are several ways to connect to Service to Activity. I am only interested in local service and my LocalService
will stand there untill user stops it(which also means end of app). I might know things wrong, if so please correct me.
On the reference page, it is stated that in order to use methods of local service directly, we should use ServiceConnection
. After binding, we can have a reference to LocalService
class, and we can use methods of this LocalService
directly. AFAIK the methods we call using this reference run on main thread with relevant Activity.
The thing that confuses me, what if I use skeleton structure and access LocalService
's methods by directly its static reference (ie. by LocalService.getInstance()
). Well, I have already used it and did not face any problem, but still I am not sure which one is better, and why.
Thanks in advance. I might add additional info if requested.
edit:
In my previously mentioned solution, no activity is keeping a reference to the LocalService
.
It is used to
LongRunningAsyncTasks
(which are all halted and reference-nullified before service stop),Notification
,getFilesDir()
,aware of static references of activities and services because they can be a reason of memory leak. if you don't want your service run in main process, then extract it into another process and work with service connection.
If you don't need any feedback from service, then just don't use connection and simply use startService()
with several commands which will be executed in onStartCommand()
method of the service.
If you need feedback from service, but not frequently, then use startService()
and feedback from service with sendBroadcast()
or through Handler class.
If you need feedback frequently (for example update slider of media player), then it's better to use service connection.
Remember that your service can be killed anytime without executing method onDestroy()
and without any notification, that's why keeping static reference is not good idea.