I am developping a MusicPlayer app, and I use a local Service to be make the MediaPlayer run in the background. It seems that we can either send intent to start a Service or bind a Service. I understand the point of for startService, we leave it running and send intent to stopService, and for bindService, we get back a IBinder to communicate with the service. However, I'm wondering what's the point of doing this? Do we have to send intents to make it work?
If I just retrieve an static instance of Service, and directly call its methods, I can also implement both start it and communicate with it.
I found an example of not using startService nor bindService, but it works well as a simple MusicPlayer.
The fragment calls Service:
https://github.com/zacharytamas/spotify-sampler/blob/master/app/src/main/java/com/zacharytamas/spotifysampler/ui/PlayerFragment.java
The Service class:
https://github.com/zacharytamas/spotify-sampler/blob/master/app/src/main/java/com/zacharytamas/spotifysampler/services/PlayerService.java
However, I'm wondering what's the point of doing this?
To have the service be running, to tell the OS "hey, we are doing work here on behalf of the user, please let my process live a bit longer".
This is covered in the documentation.
Do we have to send intents to make it work?
Yes.
If I just retrieve an static instance of Service, and directly call its methods, I can also implement both start it and communicate with it.
Then it is merely a Java object, and there is no point in inheriting from Service. Also, it means that your process will live for less time when your UI is not in the foreground.
I found an example of not using startService nor bindService, but it works well as a simple MusicPlayer.
The service is started, via startService(), in ArtistSearchActivity. Until this is done, the service does not exist, and the singleton will be null.
startService is used when you don't need to communicate with the service.
BindService is used when yout need to communicate with it.
In your app, I think you will communicate with the service (for example, if you have an activity where you choose the song, your will send data to the service to say: "this is the song which you have to play now") and I think you will need BindService instead startService.
I hope this will help you :D
Related
I'm developing an app that communicates with an embedded device via BLE (Bluetooth Low Energy). The app allows the user to send commands via an activity. Meanwhile the app needs to send location data in the background. The location data must be sent constantly, even if the activity is closed and opened multiple times over the day.
I cannot separate the continues location updates from the command requests. Because all BLE transmissions must be synchronized by one queue to prevent simultaneous transmissions which would cause package loss.
After reading the official guide (https://developer.android.com/guide/components/services#Basics), my first idea was to use a foreground service because the service must not be terminated when the activity is closed. That works fine for sending the location data. However, for sending the commands I have to communicate with the service after it has been started. I read that it's not recommended to use both startService() and bindService() but instead to decide for one way. As far as I understood a bound service can be destroyed when the referencing context (the activity in my case) is destroyed. So I guess binding to the service is not an option for me.
Another approach to talk to a started service is to send commands using broadcasts and receiving them in the service (sending commands from Activity to Service in android).
But I think there must be a better solution that I miss. What came to my mind is simply calling startService() every time I want to send a Bluetooth command. I guess that would work. But is it good practice? Effectively, I would call startService() dozens of times during a typical use case before calling stopService().
Oh wow... I read through the whole guide but overlooked this sentence in the method documentation:
startService()
Every call to this method will result in a corresponding call to the target service's onStartCommand(Intent, int, int) method, with the intent given here. This provides a convenient way to submit jobs to a service without having to bind and call on to its interface.
https://developer.android.com/reference/android/content/Context#startService(android.content.Intent)
Hope it helps in case that someone stumbles across it..
You don't have to bind the service to anything. It's enough to start it and then make sure you call startForeground on it. That will keep your process running without being killed by the system. You don't have to place your BLE code in the service class but can have it wherever you want.
I am trying to dive deep into service architecture.
Just for testing purpose I am creating music app.
Without doubts music should be played in service, but what kind of communication to use ?
As far as I know service can be bound or started (or both at the same time)
Firstly, I need to play/stop/pause/set source...
Secondly, I need to notify UI if music player is opened about events like progress, buffering...
Here my thoughts about this.
I think about mixing bound and started service.
As far as song can be set only from UI as well as paused/played/stopped/seek I choose communication with service from UI using binder. (Bound service inside activity and get binder back to communicate with service)
Notifications like track completed, next track , current track position coming from the service. I decided to use Broadcast receiver to send such notifications, because it can be multiple interested components.
So my question are
What is the best choice of communication (bound or broadcast) for music player service ?
How does System knows what kind of service is ? I mean that even if the service is bound I need to call startService method at first and than bind it. Does it mean that if even one bindService method was called it is considered as bound service and it would be killed when unbind method is called ?
Does LocalBroadcastManager make sense in communication with service ? As far as LocalBroadcastManager is local for each app, why not to use bound service than ? Global broadcast makes sense in case other apps are interested in events.
Please help to understand this mechanism.
Best choice of communication is using both LocalBroadcasts as well as Binder methods as per your requirement. If you want to do something in service from your bound component like activity then you should use binders. If you need to send result back to application you should use LocalBroadcast.
There is one more option available to use messaging. In this case both activity and service use same ibinder hence two way communication is easy. You can send message from activity to service and service to your activity
In this point you are wrong about starting bound service. You don't need to call startservice in this case. Just a call of bindservice method is required.
bindService(new Intent(this, MessengerService.class), mConnection,
Context.BIND_AUTO_CREATE);
you can bind multiple components to this service. When all of them are unbound then service will be stopped.
Yes LocalBroadcastmanagers make sense. Lets say you want to broadcast something in your app. There are 4-5 components that you want to update.How will you achieve this. Hence the use of localbroadcasts is a good feature.
For example lets say there are two services starting from different activities and second service starts its work when first service has done its work. So, only way to achieve this is send a broadcast and second service will be registering for this broadcast. Hence it will receive it.
Yeah. Services are pretty hard to understand.
There are some things that are easy. A bound service is always started with a bindService method. A started service is always started with a startService method. You do not need to start a bound service, or bind a started service.
A lot of what follows is gross generalization...
Started Service
A started service is nearly useless, unless it is an IntentService. IntentServices are pretty good tools for running asynchronous tasks. You send them a small bundle of parameters and they go off and do whatever those parameters indicate. They are like void methods in that one expects to use their side-effects, not a return value.
Bound Service
A bound service is harder to explain. Although the metaphor breaks down on careful examination, a bound service something like a singleton factory. It is, for instance, a way of providing a single object, with is single state, to all of the Activities in a application. Among its interesting features is that, as long as the service that provided the singleton object is bound, the hosting process is less likely to be killed off. Note that, the "singleton" object that the bound service provides has little to do with the service that provides it. Unbinding the service does not invalidate it.
Bound services are also the main means of doing inter-process communication, in Android.
What should you do?
Well, that's a pretty general question. Here's a thought. Putting your music player in a service makes a lot of sense. If the communication to it is mostly one way -- commands to the service -- there is a chance that you can do it with an IntentService. Until there's a specific reason to do something more complex, an IntentService has the advantage of being simpler.
I have two problems:
I know that for connection activity and remote-service I have to use AIDL.
I tried this and it's work but I can find only one way connections example. In simple words - reading something from service (by activity). But I need solve for sending some data to activity (by or from service). It's so important because the service have to send some information to activity immediatly after some its events (obtain data from the net).
Is it way to bring to front again closed application (activity) from the remote service?
Any suggestions would be greatly appreciated.
Regards
Artik
It's so important because the service have to send some information to activity immediatly after some its events (obtain data from the net).
You can use AIDL for two-way communication. You would need to expose not only the service interface, but a callback interface, via AIDL, with the client having the .Stub of the callback and supplying an instance of it in a parameter to a method on the service interface. This gets a bit complex -- here are a pair of sample apps from my book that demonstrate the technique:
Service
Client
Is it way to bring to front again closed application (activity) from the remote service?
Your service can call startActivity(), but generally that is a bad idea. The user may be in the middle of doing something else, when all of a sudden your activity pops into the foreground. Occasionally, the user may deem your activity to be more important, but not always. Consider using a Notification instead, to let the user know that there is something in your app that needs the user's attention.
First, create a private resultreceiver variable in your service. Then create a method to set this resultreceiver via a connected activity. Then use AIDL to pass on a resultreceiver to the running service from the activity via the method you just made. Then in the service use resultreceiver.send if the resultreceiver is not null.
A few examples to get you started
http://lalit3686.blogspot.com/2012/06/how-to-update-activity-from-service.html?m=1
http://chrisrisner.com/31-Days-of-Android--Day-28–Intents-Part-3--Service-Intents
I read some similar questions (for example at this link), but the problem I'm asking is a bit different. In fact, in my case the service is started manually by the startService method, then as a consequence it can not be started using the bindService method.
Suppose we have a package that contains the MainService service and MainServiceActivity activity. In the file "AndroidManifest.xml" this activity is declared with action MAIN and category LAUNCHER. This activity is used to configure the service via the SharedPreferences and start the service by invoking startService method. In other words, typically the user launches the MainServiceActivity and configures/starts the MainService.
Now consider another activity (Let's call it SecondActivity) that is part of another package. Depending on the configuration, the service starts this activity using the startActivity method, so this other activity is running on a separate process than the MainService. As soon as the activity is running, it should inform the service.
At this point, a communication request/reply begins between the MainService and the SecondActivity: the service sends a request and the activity sends a reply.
The communication via messaging might fit, but the MainService is started through startService method, so the bindService method can not be invoked by activities that want to bind to the service.
Then I had an idea that makes use of an additional service (Let's call it UtilityService), which is part of the same package of MainService: the UtilityService could be started using the bindService method. As a consequence:
as soon as the MainService is running, it might perform the bind to the UtilityService;
when the MainService launches an external activity (for example the above SecondActivity), this activity bind to the UtilityService.
In this way, both the MainService and the SecondActivity are connected to the UtilityService, where the latter acts as an intermediary for communication.
Are there alternatives to this idea?
In fact, in my case the service is started manually by the startService method, then as a consequence it can not be started using the bindService method.
You can both bind and start a service, if you wish. It's a bit unusual, but it can be done.
Are there alternatives to this idea?
Binding has nothing in particular to do with services being able to communicate with activities. Using some sort of callback or listener object via binding is a possibility, but it is far from the only one.
You can:
Have the service send a broadcast Intent, to be picked up by the activity
Have the activity send a PendingIntent (e.g., via createPendingResult()) to the service in an Intent extra on the command sent via startService(), to be used by the service to send information back to the activity (or wherever the activity wants it to go, such as a broadcast)
Have the activity pass a Messenger tied to its Handler to the service in an Intent extra on the command sent via startService(), to be used by the service to send information back to the activity
All of those work perfectly well between processes, as well as within a process.
You can use Android Interface Definition Language (AIDL).
You can find an easy to use guide here
I am currently writing an app, which consists of a service and an activity. The service is running in the background, doing some live audio processing. If the user want to get some information about the running service or want to change the settings of the service, the activity gets started and bind to the service.
Currently i am using the asynchronous messenger system to communicate between the service and the activity. For example, the service can send some results to the activity through a message and the activity can handle this message and show the results. This works fine, but it is stressful to write the messaging stuff for each communication. And it is not always needed. Sometimes i only want to ask the service, if a flag is set or not. If i do this asynchronous, i have to send a message to the service which asks for the value of the flag and the service has then to send a message back to the activity to answer the request.
So i want to have some getter and setter which can synchronously access the service. This can be done by using a binder, which works too.
The problem is, that i sometimes need synchronous communication to get the value of flags etc. and sometimes i need asynchronous communication to push the results from the service to the activity. So what i need is a binder and a messenger. But i dont know how this can be done, because the service can only return one object from the onBind() method, either a binder object or a messenger object.
Do you have any suggestions how this can be done or some other approach to realise asynchronous and synchronous communication between an activity and a service?
Thanks in advance!
Tobias
If you are already binding to the service, your activity can supply a listener object to the service, which the service will then call when events occur.
You just need to make sure that you unregister that listener object before unbinding from the service, and do both before the activity is destroyed, so your service does not wind up with a strong reference to a defunct activity.