I have an Activity that starts and binds to a service. It sends an intent with a List of data and the service is responsible for periodically updating that data. This is done in the handleIntent (Intent) method. What I want to do is send the updated data back to the activity. Both the activity and the service are in the same application. How can I "listen" for requests from my service? Do I have to use a Messenger and/or Broadcast Receiver? what's the cleanest, easiest, most efficient way of doing this? Thanks.
I suggest you check EventBus. it will allow you to send events like local broadcast receiver. And from that in activity you can listen specific event and display result. you can even use interface to get callback from service also.
Without any library you can achieve this with LocalBroadcastManager.
http://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html
For this problem, you can use a ResultReceiver. If both the service and activity share the same ResultReceiver object then you can "push" data to the Activity from the Service using the "send(int, Bundle)" method and on the Activity side receive it with "onReceiveResult(int, Bundle)".
ResultReceiver | Android reference
Related
In my android app I have a broadcast receiver that listens for network related intents(android.net.conn.CONNECTIVITY_CHANGE).
Whenever there is a change in the network connection the broadcast receiver receives the intent and it needs to pass on the new connection state to a service. This service keeps track of the connection state of the device.
Next I have an activity that will have to communicate with the service to find the connection state of the device and do some action based on the connection state.
What will be the best way to handle the communications with the broadcast receiver with the service and next the activity with the service.
There are many ways to do this and there is no "best way". It all depends on what other communication is going on between these components.
Activity can send data to Service using extras in an Intent on startService().
Service can send data to an Activity using extras in an Intent on startActivity()
Service can send data to any component using extras in a broadcast Intent. Other components (activities, broadcast receivers, etc.) can register BroadcastReceivers to listen for the data from the Service.
Activity can also bind to a Service which will allow 2 way communication between the Activity and Service using method calls (AIDL). These method calls can be synchronous or asynchronous.
If the components are all running in the same process, you can store state in static variables and share data that way.
You need to look at your whole application and see what data needs to move from component to component and then choose a method that satisfies those requirements.
I have a Activity and a Service. I am using bindService to get the Binder object which gives my activity access to the service. So I am able to execute commands on the service easily. What I need is a way to have the service communicate back to the activity. Is the best way to handle this to make calls directly from my activity to the service via the service instance returned from the binder. Then use a local broadcast receiver to send messages back from the service to the activity?
Thanks,
Nathan
There are several ways to achieve this.
1.You can pass a handler object to the service, and have it implement the handler callback
2. You could send a broadcast
3. You could pass a listener object.
variant number 1 is usually best if you know exactly the activity you pass the reference to.
If you want several activities to handle it, better send a broadcast
I am trying to make 2 applications which will interact with each other using AIDL.
Application 1: Will be a service.
Application 2: Will be Activity(with a button) which will show some data which will be fetched by Application 1 service.
Now to start this interaction I know we can make one AIDL file in both applications and when user presses the button in application 2 we can involve the function of service from application one. That is lets say application 2 requests the current time then application 1(Service) will fetch the current time and return it to application 2.
My doubt is that I want to interact the other way round. I want to inform the activity from service when some particular digit occurs in time(or some other event). I am not sure how to proceed with this way of communication ie from Service to Activity.
Some pointers will be really helpful.
You know you can send message from Activity to service, Reference Bound Service
By Following above tutorial You should Consider Sending Handler from Activity to Service using Messenger Class in Intent.
So now Service and Activity can send message to each other which will execute corresponding Handlers
Use Broadcast receiver in Activity and let Service broadcast messages (with same Intent as used by Broadcast receiver in Activity). These messages which are broadcasted from Service will be received by broadcast receiver in the Activity.
I start a service from my main activity using startService(). The service checks for sockets on localhost. When it receives a socket, it reads data from it. I would like to hide the notification bar when it receives socket with specific data. I already coded a function hideNotificationBar() which is located in my main activity. The problem is I don't know how to call this function in main activity from service.
Thanks for any help!
Send a Broadcast from Service. Register your Activity to receive this broadcast and act upon it.
This approach solves the problem of storing/acquiring the reference to Activity, which might become inactive during the lifetime of your Service.
The downside is that you can only send simple types, Bundle or classes implementing Parcelable via a broadcast Intent.
I suggest you have a look at MessengerService and MessengerServiceActivities from API Demos application.
Basically, idea is to have Handler class inside both your activity and service that handles communication between the two. Use ServiceConnection in the activity to establish connection with the service.
Common scenario - Activity with a background Service to poll server.
The Service will run periodically via AlarmManager and also perform tasks for the Activity (user hits a button, go fetch something from server).
I'd like to know the best practices here. I think the best design would be the Android LocalService example:
http://developer.android.com/reference/android/app/Service.html#LocalServiceSample
However in the example the Activity has a reference to the activity mBoundService but there is no reverse connection (the Service has no way to call the Activity).
What is the best way for the Service to call the Activity?
Do I use Intents, BroadcastReceivers, Messages? How?
I think the best design would be the Android LocalService example: http://developer.android.com/reference/android/app/Service.html#LocalServiceSample
I wouldn't. Use the loosest possible coupling you can stand. Hence, on average, aim for the command pattern with startService() instead of the binding pattern with bindService(). Notably, binding is a bit of a pain when it comes to dealing with configuration changes (e.g., screen rotations).
What is the best way for the Service to call the Activity? Do I use Intents, BroadcastReceivers, Messages? How?
See Notify activity from service
If you need tight coupling between your activity using bindService(), the way you communicate depends on who is originating the communication.
If the Service is originating (due to say an Alarm that has some new information to share), it would typically send a broadcast.
If the Activity is originating (due to say your example "go fetch something from server"), it could be handled asynchronously using AsyncTask or similar. That is, you could fetch from the server in the AsyncTask.doInBackground(), and post the results back to the activity in AsyncTask.onPostExecute. This scenario be a bit more complicated if the requested operation is expected to take a very long time - in which case I would de-couple it, and send a broadcast back from the Service instead.
As written here
When you want to communicate from service to an Activity or Fragment
which did NOT started the service or to communicate from service to multiple activities/fragments then you can use Event Bus or
Broadcast Intents since they can receive callback for an event in any
activity or fragment wherever they are implemented.If you want to
communicate from service to an activity/fragment which started the
service then you can use Pending Intent or Messenger as they can be
put into an Intent extra and passed to Service.
Pending Intent
We can use createPendingResult() which creates a new PendingIntent
object which you can hand to service to use and to send result data
back to your activity inside onActivityResult(int, int, Intent)
callback.
Event Bus
You can have the service raise events which activities or fragments
can listen for and respond to using Event Bus.
Messenger
Messenger is parcelable ,and can therefore be put into an Intent
extra,so your activity can pass this Messenger to the service.Service
will populate Message object with whatever data needs to be
send.
Broadcast Intents
Service can send a broadcast which can be responded by the activity.