In my app I've designed it to have a Service that gets data constantly (for good reason, it's from some sensors) and provides it to two clients:
A UI Activity to display the live data
Another service that logs the data
At any time, both, one or neither of these clients may be running.
I think that this service should be a Bound service, whereas the logging service is a Started service.
The Android documentation for this says I should extend the Binder class, or use a Messenger if I want to access the service from another process.
This service, the logging service and the UI Activity will all be in the same apk, so they'll presumably be in the same process - but what is going to be the best solution here? I suspect the documentation might not be taking into account the possibility that I could have two clients in the same process as the service.
Thanks
The Android documentation clearly says
Extending the Binder class
If your service is private to your own application and runs in the same process as the client (which is common), you should create your interface by extending the Binder class and returning an instance of it from onBind(). The client receives the Binder and can use it to directly access public methods available in either the Binder implementation or even the Service.
This is the preferred technique when your service is merely a background worker for your own application. The only reason you would not create your interface this way is because your service is used by other applications or across separate processes.
Using a Messenger
If you need your interface to work across different processes, you can create an interface for the service with a Messenger. In this manner, the service defines a Handler that responds to different types of Message objects. This Handler is the basis for a Messenger that can then share an IBinder with the client, allowing the client to send commands to the service using Message objects. Additionally, the client can define a Messenger of its own so the service can send messages back.
This is the simplest way to perform interprocess communication (IPC), because the Messenger queues all requests into a single thread so that you don't have to design your service to be thread-safe.
So, the best option is to use a service by extending IBinder class when this service is a local service. When both services are created by using Messenger and AIDL, they are remote services.
imrankhan's preferred solution (Binder) did seem to work, but in the end I opted for a Messenger as in practise I found this solution more flexible and logical to code.
Related
The Android docs give information about how to implement a started service and how to deal with a bound service. However they are not really precise about hybrid services.
Let's assume I have a local service which I start and later bind to. I want to keep the service alive all times (maybe it is collecting location information).
The idea behind the hybrid service is that at some point in my app I must communicate with the service to maybe pull data from it.
What's the advantage of implementing a Binder for that purpose? According to the docs this binder would store a reference to my service or expose public methods which talk to the service.
Why would I not simply have a static variable in my service and assign the service (this) to it in the constructor? I could return null from onBind(), and not bother about ServiceConnection.
I get the Binder requirement for pure bound services but what about the hybrid local ones? What do I miss here?
My Android app runs a service instance that is not accessible from other apps. I know that the service runs in the same process the app's Activity, because I can read and write to a static variable on the Service class from the activity and the Service sees the changes.
Communicating with the service via static variables/methods (or more properly singletons), is much, much simpler than communicating with it using a Handler or an Intent, which requires making all passed parameters Parcelable. It seems like these two communication methods are really designed for services running in a separate process, and are unnecessary overhead for an in-process service.
It seems like I must be missing something big. What is wrong with using a singleton to talk to a service if you know it is local to your app?
Communicating between a Service and an Activity is one of the main reasons to use a bound service: you can build a Binder class that defines the interface between your Service and Activity and pass any objects you want between them without having to worry about parcelling them (as binders require both to be on the same process).
What are the ways to communicate between an Activity and a Service on android?
Today I learnt how to communicate by sending an Intent from Activity and replying back using BroadcastRecevier.
Which are my other options? Does anyone have a tutorial/reference regarding this?
Answer to this question is:
There are several way for an activity to communicate with an service and vice versa. This section dicusses the different ways and gives recommendation which to use.
5.1. Activity binding to local service
If the Service is started in the same process as the Activity, the Activity can directly bind to the service. This is a relatively simple and efficient way to communication.
5.2. Using receiver
You can also use dynamically registered receivers for the communication. For example your activity can dynamically register a receiver and the service sends outs corresponding events.
5.3. AIDL for services in a different process
To bind to a service which runs in a different process you need to use Inter Process Communication (IPC) as the data needs to be send between different processes. For this you need to create a AIDL file which looks similar to an Java interface but ends with the .aidl file extension and is only allowed to extend other AIDL files.
This approach is required if your service should be provided to other applications, otherwise you should prefer a local service.
5.4. Sending Intent data and bundle to the services
The service receives data from the starting Android component and can use this data.
5.5. Handler and Messenger
If the service should be communicating back to the activity it can receive an object of type Messenger via the Intent data it receives from the Activity. If the Messenger is bound to a Handler in the activity the service can send objects of type Message to the activity.
A Messenger is parcelable, which means it can be passed to another process and you can use this object to send Messages to the Handler in the activity.
Messenger provides also the method getBinder() which allows to pass a Messenger to the activity. The Activity can therefore send Messages to the service.
Thanks to http://www.vogella.com/articles/AndroidServices/article.html
Ways to connect Activity to service:
Broadcasts: easiest way, implement a BroadcastReciever in each to listen to actions of others.
Messengers: Very good for multiple types of clients, Both service and client have a Messenger , service provides it Messenger in onBind(), clients sends a register/unregister message with its own messenger in replyTo() of message. Service saves client messenger. Now both can send/recieve messages.
IBinder: If you need full fledged remote IPC . Define an Interface for service with AIDL and pass Implementations to clients in onBind().
Android online reference has explanations of each.
The guys are right, you should really google for answers!
However, I recently learned a neat way to send intents to a service. You can simply call startService(myIntent) to send an intent to your service. If the service is not running, it will be started. If the service is running, you have the possibility to react on the new information.
I have a service that communicates through AIDL with other services. I want that service to be bound by activities in my application. Can the service define two binders\interfaces? I've tried yo use a messenger for communicating with the activities, overriding "onBind" method so that it returns a different binder according to the intent it gets (one for the other services and one for the activities).
But when the activities (that use the same binder) unbind from the service, I have an error "myService has leaked ServiceConnection ... that was originally bound here", which I believe is about the binder the service use to communicate with the other services.
If a service cant use two interfaces, how can I implement the communication between the activities and that service?
thank you,
-Liron
If by
"overriding "onBind" method so that it returns a different binder
according to the intent it gets "
You mean, that you set an extra to your Intent, indicating what to do it won't work.
According to the Docs in onBind(Intent):
Intent: The Intent that was used to bind to this service, as given to
Context.bindService. Note that any extras that were included with the
Intent at that point will not be seen here.
Try to give your intent a custom action and check if that works
AIDL and Messenger are used for IPC with other applications/processes. From the Android API Guide:
Note: Using AIDL is necessary only if you allow clients from different applications to access your service for IPC and want to handle multithreading in your service. If you do not need to perform concurrent IPC across different applications, you should create your interface by implementing a Binder or, if you want to perform IPC, but do not need to handle multithreading, implement your interface using a Messenger. Regardless, be sure that you understand Bound Services before implementing an AIDL.
If your activities are in the same process as the service, you just need to extend Binder.
Extending the Binder class
If your service is private to your own application and runs in the same process as the client (which is common), you should create your
interface by extending the Binder class and returning an instance of
it from onBind(). The client receives the Binder and can use it to
directly access public methods available in either the Binder
implementation or even the Service. This is the preferred technique
when your service is merely a background worker for your own
application. The only reason you would not create your interface this
way is because your service is used by other applications or across
separate processes.
This graphic regarding the bound service lifecycle may help with how you are binding/unbinding (http://developer.android.com/guide/components/bound-services.html#Lifecycle):
I want to do Bluetooth connection in Service. And there needs to be interaction between Activities and Services. The service should be started as soon as the app is started and should be able to communicate with UI Activities on certain situations.
What should be the appropriate way of doing it? If I bind the service from only one Activity then that service will be communicating only with that Activity. So, do I need to take AIDL based approach or is there any other way out for this?
Otherwise, can I have a class that extends Application class and then start the service from there and bind the Application class instead?
This is quite a broad question, so I'll answer as best as I can. From what I know of services, multiple activities can bind a single service, all having access to it. Only once all activities that bound the service end their connections (by unbinding), does the service actually stop.
The android documentation on services tells us:
... the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service's onDestroy() method is called and the service is effectively terminated
So my recommendation would be to bind the service from all activities that need to communicate with it. When binding with a service an IBinder is returned, which you can use to communicate with the service. Again according to the Android documentation on services:
Usually the IBinder returned is for a complex interface that has been written in aidl.
Although if you only need to perform simple communication with the service, you could use the Messenger class instead of writing full AIDL files. A sample of this can be found here.
Hope this answers your question!
You could bind directly to the Service as the above answer states, however there is no need for Messengers. Your service will be running in the same process as your activity 99.9% of the time. Messengers are designed for inter-process communication (IPC). Also no need for AIDL - that was designed for advanced IPC.
Instead, you should use: BroadcastReceivers and Intents. This is what they were designed for (communication between components in an app).