Jayy
Jayy

Reputation: 14798

Why can a local service not be accessed directly?

From what I can tell, a Service can only be accessed from an Activity via an IBinder, Messenger or AIDL.

Why can a service instance's methods not be directly called by, for example, an activity?

For example, when the service is started, have the service save its instance in a singleton which would then be accessed by Activitys, allowing them to directly call the service's methods?

Upvotes: 2

Views: 43

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007321

From what I can tell, a Service can only be accessed from an Activity via an IBinder, Messenger or AIDL.

That would depend upon what you define as "accessed". startService() can also be used to direct the service to perform some operation.

Why can a service instance's methods not be directly called by, for example, an activity?

Android's component model is designed around loose coupling and replaceable implementations, where the replacements may be local or remote.

Moreover, a service should only be running when it is actively delivering value to the user. As such, there will be plenty of times when the service is not yet running, and the activity would need to start or bind to the service anyway.

For example, an IntentService should only be interacted with via startService(), as the IntentService will only be running while there are commands (supplied via startService()) to be processed.

Finally, the primary role of a Service is as a marker to the OS, letting it know that the process is still doing work, even while it is in the background. A pattern of "let's stuff the Service into a singleton" suggests that you are using the service in cases where the object in question does not necessarily need to be a Service. Just because an object is a singleton does not mean that it needs to be a Service. Hence, you need to sit back and ensure you know exactly why you are using a Service in the first place and whether that is best for the user.

For example, when the service is started, have the service save its instance in a singleton which would then be accessed by Activitys, allowing them to directly call the service's methods?

There's nothing stopping you from doing this. I wouldn't -- I'll use startService() and event buses for communications. And, while it is technically possible to do what you want, whether it is sensible and reliable depends entirely upon the use case of the service and the communications with that service.

Upvotes: 1

Related Questions