Using a singleton to talk to an Android Service - android

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).

Related

Bound Service vs Unbound + singleton for communication

I have a service, I need to communicate to with it (one service - many fragments/activities). There are two options for this:
Have a singleton that controls the service - starts it and then binds to it (using the app context)
Have a singleton that controls the service - starts it, the service when ready registers back as a delegate to the singleton (in a WeakReference)
Solution no 2 seems simpler to me, but whenever I read about communication with services there is the concept of the bound service.
Is there any benefit of having a bound service instead of the service registering itself as a delegate (and unregistering with onDestroy)?
Edit 1: The service is to keep the communication alive, it's expensive to set up a new communication channel. Even if no one requested any data it should keep the channel alive (heartbeat).
The service is foreground, it should run even if the activity that requested the data gets killed by the system. The next time it is created the data will be there.
The data requested by one screen might be useful for some other (therefore has to be stored in a singleton).
Bound and unbound services are both usable patterns and you should pick whatever pattern is better for you use case.
You should pick bound service if you want your service to have the same lifecycle as the components that bind to it. If you need an independent service use an unbound version.
The only benefit of one approach versus another is the simplicity of implementation.
In you case, I think you need the service only while there are running activities and fragments, then the easiest way, in my opinion, would be to make a bound service and make every activity bind to it. With that, you'll get a simple communication interface between you activities (and fragments, since they have access to containing activity) and your service.
The benefits of this approach are:
the service will stop itself if all activities unbind and start itself when first activity binds to it.
you won't need to track all running activities in the singleton and manually unbind
you won't need to maintain a singleton manager, less code -> less bugs
sometimes onDestroy can be skipped by the system and you can leak the service with the 2 approach.
Since you need your service to be running the correct option will be to use a started service and make each activity bind to it when needed. It's a common pattern.
Started service will run until you explicitly stop it or it stops itself, you can have a singleton manager that will be responsible for that.
But at the same time you can communicate with the service from your activity using binding.
So basically comparing with the first suggested approach, you'll need some instance that will start and stop the service, but the communication between activities and service will be the same - using binding.
Yes, using a bound service in Android is a much better option when communicating with Views like Activities/Fragments. This is because of the following reasons,
It runs synchronously.
You can have more control on the service data when to show on UI thread of the view. You can choose when to call it in async/sync way.
LocalBroadcastManager only runs Asynchronously.

Should I extend the Binder class or use a Messenger?

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.

Starting Android services by intent vs. by instance creation

It's my understanding that Android services are supposed to be singletons - no more than one class instance running at a time. So you're supposed to start them via intents, as opposed to
MyService mse = new MyService();
However, in Google's in-app billing sample, that's exactly what they do in Dungeons.java, line 235. So it's obviously legal.
I'm wondering, if I start a service like this, will the framework later recognize that it's running? In other words, if I try to call startService() on the same service later on, will the framework recognize that an instance of the service already exists and dispatch startService() calls to it?
I don't know what example you are referring to. But you absolutely positively cannot instantiate an Android component (Activity, BroadcastReceiver, Service, Provider) yourself using the new keyword. These components can only be instantiated by the Android framework, as the framework needs to set up the Context of the component.
There is (unfortunately) nothing stopping you from writing Service s = new MyService();, but it will do you no good. Android will never call any of the lifecycle mathods on this Service and any calls you make to methods of the Service will probably fail spectacularly because the instance has no Context.
If you instantiate the service directly instead of using intents that guarantees the service will run within your Activities process. If that activity should be killed then down goes the service too. Is that a bad practice? Well it depends on what you wanted. If you need that service to live through potential shutdowns of activities then yes that's a bad thing to do. If you don't care or your app can tolerate those shutdowns then it's ok. However, I'd argue if you need a background job running that can be stopped when your Activity stops then you need to use AsyncTask and NOT a service.

Binding to Service from Activity or starting service in different process?

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).

Android ==> Service question?

I have a service running on my android application, the service is a socket class that has to run through the whole application, i create it when my first activity loads.
How can i get an instance of this socket class so that i can call a function in this class.
For example
//how can i get an instance of the running service?
MyService s = getService();
s.writeDataToServer("hello");
There's two ways you can go about doing this depending on if you want to keep the socket open when the user isn't actively using your UI.
The first is a LocalService it's the same as a regular Service except it runs in the same process as your Activitys UI thread and therefore you can gain a direct reference to it. This is a much lighter method of creating and using a Service than using AIDL. I only recommend using AIDL if you wish to create an out-of-process service that needs to be accessed either by different processes in your application or in different applications. This is most likely not what you need. The LocalService method will allow you to keep the service running in the background and in turn keep the socket open even when the UI isn't in use.
If you don't have the requirement of keeping the socket open and only wish to have access to it from multiple Activitys then you can extend the Application class and register it in your manifest. It allows you to manage global application state. You can put the socket creation and management functions into that class and then provide methods for your various Activitys to gain access to it. The Application class dies when the process dies so it is not suitable for keeping a socket open for long periods of time or during times when the user is not actively using your application.
There is the built in Activity#getApplication() method that helps with this process. You can specify your custom Application class in the AndroidManifest.xml via the android:name attribute.
The Android Interface Definition Language (AIDL) is the correct way to connect to a service.
Check out http://developer.android.com/guide/developing/tools/aidl.html
For information how to communicate with a service.
Check out Intents and the bindService method.

Categories

Resources