What is difference between BroadcastReceiver and ResultReceiver in android?
Result Receiver:
Generic interface for receiving a callback result from someone.
Broadcast Receiver:
Base class for code that will receive intents sent by sendBroadcast().
EDIT:
Background: All networking operations/long running operations should take place away from the main thread. Two ways to do this :
Async task - For Simple networking like say retreive an image/ do db
processing
Service - For Complex long running background process
If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service. For example, if you want to play some music, but only while your activity is running, you might create an Async Thread. But if you want the process to continue even after the user exits the app (say a download) then use a service
Lets say you pick 2. Now
You activity sends a web request to your service
Your service executes that using say DefaultHttpClient
It sends back data to your activity.
The third step of receiving data here can be done in two ways
1.) Broadcast receiver: Multiple receivers can receive your data. Used if you want to send data/notifications across applications(say you are also interacting with fb and twitter, multiple receivers for your web broadcast),
whenever you send broadcast its sent system wide.
2.) Result receiver: Your application is the only receiver of the data. It is an Interface you implement and pass it to the intentService through putExtra. IntentService will then fetch this object
and call its receiver.send function to send anything (in bundle) to
calling activity. Result receiver has
preference over broadcast receivers if your all communication is
internal to your application
EDIT: I should also mention this caution
Caution: A service runs in the main thread of its hosting process—the
service does not create its own thread and does not run in a separate
process (unless you specify otherwise). This means that, if your
service is going to do any CPU intensive work or blocking operations
(such as MP3 playback or networking), you should create a new thread
within the service to do that work. By using a separate thread, you
will reduce the risk of Application Not Responding (ANR) errors and
the application's main thread can remain dedicated to user interaction
with your activities.
A BroadcastReceiver is a receiver receiving broadcasts. Those are sent by someone in the intention that there can be many receivers receiving them (like radio broadcasts).
A ResultReceiver on the other hand is intended to receive a callback result from someone. So this could be compared with a walkie talkie, where you call someone and then are going to receive an answer (a result) from the one you called.
These two classes are completely different. It's actually quite the same difference as between Broadcast and Result.
what it Broadcast? In simple words it's some message which is visible to whole system and it can be consumed by every part of the system (which knows the contract), it wasn't originated by smb reuest;
what is Result? It's something we're expecting to receive from another part of the system. Usually there's only one receiver for result and usually that receiver has requested processing to obtain result (feel the difference - for broadcast nobody needs to do any 'request' to let it originated);
That was explanation from logic point of view. From the code perspective if You would compare BroadcastReceiver and ResultReceiver You could observe huge difference. Basically both classes are built on top of IPC but BroadcastReceiver is much more complex because of it's different nature (which I've tried to explain in first part).
Broadcast Receiver
A broadcast receiver is a component that responds to system-wide broadcast announcements. example, a broadcast announcing that the screen has turned off, the battery is low, or a picture was captured. Applications can also initiate broadcasts—for example, to let other applications know that some data has been downloaded to the device and is available for them to use. Although broadcast receivers don't display a user interface, they may create a status bar notification to alert the user when a broadcast event occurs. More, though, a broadcast receiver is just a "gateway" to other components and is intended to do a very minimal amount of work. For instance, it might initiate a service to perform some work based on the event.
Result Receiver
If your service is going to be part of you application then you are making it way more complex than it needs to be. Since you have a simple use case of getting some data from a Restful Web Service, you should look into ResultReceiver and IntentService.
This Service + ResultReceiver pattern works by starting or binding to the service with startService() when you want to do some action. You can specify the operation to perform and pass in your ResultReceiver (the activity) through the extras in the Intent.
Related
Once you return from onReceive(), the BroadcastReceiver is no longer
active, and its hosting process is only as important as any other
application components that are running in it. This is especially
important because if that process was only hosting the
BroadcastReceiver (a common case for applications that the user has
never or not recently interacted with), then upon returning from
onReceive() the system will consider its process to be empty and
aggressively kill it so that resources are available for other more
important processes.
This means that for longer-running operations you will often use a
Service in conjunction with a BroadcastReceiver to keep the containing
process active for the entire time of your operation.
The above text has been taken from android site. But I am unable to find how to use a Service in conjunction with a BroadcastReceiver. Can someone please share some link for this or any example?
I found this link - stackoverflow. Is this the correct way of doing it?
The BroadcastReceiver is one way you can set up communication between your service and your application/activity. Basically the service can send a broadcast to your activity, then your activity will handle whatever it needs to inside the onReceive().
Inside your service you would send a broadcast using an intent with a specific intent action, in your activity you would register a receiver with the same action. This way when you send a broadcast your activity will be able to receive it.
A good example / place to start: (Look at section 7 for full code example)
http://www.vogella.com/articles/AndroidServices/article.html
Good Luck!
What is difference between BroadcastReceiver and ResultReceiver in android?
Result Receiver:
Generic interface for receiving a callback result from someone.
Broadcast Receiver:
Base class for code that will receive intents sent by sendBroadcast().
EDIT:
Background: All networking operations/long running operations should take place away from the main thread. Two ways to do this :
Async task - For Simple networking like say retreive an image/ do db
processing
Service - For Complex long running background process
If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service. For example, if you want to play some music, but only while your activity is running, you might create an Async Thread. But if you want the process to continue even after the user exits the app (say a download) then use a service
Lets say you pick 2. Now
You activity sends a web request to your service
Your service executes that using say DefaultHttpClient
It sends back data to your activity.
The third step of receiving data here can be done in two ways
1.) Broadcast receiver: Multiple receivers can receive your data. Used if you want to send data/notifications across applications(say you are also interacting with fb and twitter, multiple receivers for your web broadcast),
whenever you send broadcast its sent system wide.
2.) Result receiver: Your application is the only receiver of the data. It is an Interface you implement and pass it to the intentService through putExtra. IntentService will then fetch this object
and call its receiver.send function to send anything (in bundle) to
calling activity. Result receiver has
preference over broadcast receivers if your all communication is
internal to your application
EDIT: I should also mention this caution
Caution: A service runs in the main thread of its hosting process—the
service does not create its own thread and does not run in a separate
process (unless you specify otherwise). This means that, if your
service is going to do any CPU intensive work or blocking operations
(such as MP3 playback or networking), you should create a new thread
within the service to do that work. By using a separate thread, you
will reduce the risk of Application Not Responding (ANR) errors and
the application's main thread can remain dedicated to user interaction
with your activities.
A BroadcastReceiver is a receiver receiving broadcasts. Those are sent by someone in the intention that there can be many receivers receiving them (like radio broadcasts).
A ResultReceiver on the other hand is intended to receive a callback result from someone. So this could be compared with a walkie talkie, where you call someone and then are going to receive an answer (a result) from the one you called.
These two classes are completely different. It's actually quite the same difference as between Broadcast and Result.
what it Broadcast? In simple words it's some message which is visible to whole system and it can be consumed by every part of the system (which knows the contract), it wasn't originated by smb reuest;
what is Result? It's something we're expecting to receive from another part of the system. Usually there's only one receiver for result and usually that receiver has requested processing to obtain result (feel the difference - for broadcast nobody needs to do any 'request' to let it originated);
That was explanation from logic point of view. From the code perspective if You would compare BroadcastReceiver and ResultReceiver You could observe huge difference. Basically both classes are built on top of IPC but BroadcastReceiver is much more complex because of it's different nature (which I've tried to explain in first part).
Broadcast Receiver
A broadcast receiver is a component that responds to system-wide broadcast announcements. example, a broadcast announcing that the screen has turned off, the battery is low, or a picture was captured. Applications can also initiate broadcasts—for example, to let other applications know that some data has been downloaded to the device and is available for them to use. Although broadcast receivers don't display a user interface, they may create a status bar notification to alert the user when a broadcast event occurs. More, though, a broadcast receiver is just a "gateway" to other components and is intended to do a very minimal amount of work. For instance, it might initiate a service to perform some work based on the event.
Result Receiver
If your service is going to be part of you application then you are making it way more complex than it needs to be. Since you have a simple use case of getting some data from a Restful Web Service, you should look into ResultReceiver and IntentService.
This Service + ResultReceiver pattern works by starting or binding to the service with startService() when you want to do some action. You can specify the operation to perform and pass in your ResultReceiver (the activity) through the extras in the Intent.
I'm in little bit confusion where in what case I need to use application components like Service, asyncTask and Broadcast Receiver.
Can any one explain what the exact difference between these there and where I need to use these components?
AsyncTask is a friendly way to create a new thread that performs some work asynchronusly.
A Broadcast Receiver is something like an Event Handler for system events. It can run in
background and perform an action when something happens, like turning the phone off or turning wifi on..
A Service is just an app that works in background (like a daemon) and serves information to an app or just performs tasks.
Sorry for my English, I try to let me understand but it is not my mother tongue
I will get straight to where I have applied these three in my projects so far:
1.Service:Something you want to perform in the background without any user interaction.For instance fetching location data continuously or sending some data continuously to your server.You can also use services to perform tasks every few time units.For example sending ten minute background updates.
2.AsyncTask:Making a new thread of execution.Best use I have encountered so far is calling a web service..I did the following using an AsyncTask for web service calls
1.Display Progress bar in onPreExecute()
2.Perform my web service calls in doInBackground(Params...)
3.In onPostExecute(Result) update the UI or do some other stuff with the response from the web service.
3.BroadCastRecievers are like global recievers for your app.They can listen for both System events like a phone restart or a custom event within your app.I used them for starting a service when the phone was restarted,which stopped when we switched off the phone.
Let me explain with a usecase, so you understand it better -
AsyncTask - Want to get something from the server, or post something to the server? If we do so on the main thread, the user won't be able to interact with the app. So Asynctask is used, and it performs the network activity in a different thread.
Service - Want to manage something in the background? Like get the users' location every 10 minutes or 1 hour, or alert the user when he is crossing a particular area based on the location. The Service makes the app run even when the app is not opened (the user might be doing something else, or the phone is locked, the Service still runs in the background).
Broadcast Receiver - Assume, you are tracking location and storing locally (when the internet is down). Not when the internet is up, you want to send all of them. So you register with the OS, that you want to listen for that specific event, and you get control.
Or when you want the server to know that the device is restarted, then we just have to implement it.
Clear?
A service and its local memory-variables are loaded into memory and is always running
A BroadCast receiver is only garanteed to be in memory and running while processing an event.
A Broadcastreceiver can be removed from memory by the operating system if the memory is low.
"Service" is a component which runs in the background, without interacting with the user. Every developer can create new Services in his application. Services support true multitasking for Android, as they can run in their own process.
"AsyncTask" encapsulates the creation of Threads and Handlers. An AsyncTask is started via the execute() method.the execute() method calls the doInBackground() and the onPostExecute() method.
Mostly main purpose to download something without user interaction.
"Broadcast receiver" is a class which extends BroadcastReceiver and which is registered as a receiver in an Android Application via the AndroidManifest.xml file(or via code).you can register a BroadcastReceiver dynamically via the Context.registerReceiver() method.
The class BroadcastReceiver defines the onReceive() method. Only during this method your BroadcastReceiver object will be valid, afterwards the Android system can recycle the
BroadcastReceiver.
We have a network client application, and we are trying to validate our approach to processing responses from the server in conjunction with device rotation. essentially, we do this,
activity registers a receiver for network responses
activity initiates a network operation by starting an intent service
service responds by broadcasting an intent it's finished
our (perceived) problem is that when the device is rotated, the activity is destroyed / recreated. during the time between when the activity's receiver is unregistered in onPause() and when it's re-registered in onResume(), we may have missed the intent that is broadcast by the service.
is this a real problem?
if so, we have hypothesized the following solution,
first, don't use intents to communicate between activity and service
create two blocking queues: network requests and responses in say the application class
service starts a thread that take()'s from the request queue
activity starts a thread that take()'s from the response queue
activity offer()'s to the request queue when it wants to start a network operation
service offer()'s to the response queue when post the result of a network operation
Yes this can happen in rare circumstances but it will happens for sure if the user receives a call. Again your activity will be paused and then resumed, If the user talks for a long time your activity will loose a bunch of broadcasts from the service.
My advice is that you must not use broadcasts to do two way communications between application's in situations that a response from a component such as a service, requires immediate attention. What mechanism you will use is depending from the situation. In my latest project I am using a service in order to update an app-widget, in this scenario I am using static code in the service in order to do some queries or to request some actions.
Your thinking sounds good but it may hides a complex implementation, If I was in your position I would consider to use the built in service mechanism called Bound Services. I have not used it so far but it seems that it is covering your needs.
EDIT
So based on the bound services concept I propose the following flow:
Activity starts, a so called, sticky service.
Service registers the receiver for network responces.
Service maintains an Ibinder object with the needed information based on the network responces.
Activity bounds to the service whenever it wants and retrieve the Ibinder object with the info and does the required actions.
When it's time to end the application, Activity stops the service and finishes itself.
Hope this helps...
I have a class that starts a Bluetooth reading thread and another that receives/decodes what's read from that port and produces some output logs depending on the information read.
In my design, those 2 components form a service for my application (multiple activities) from where I would like to start/stop getting the output logs on a continuous basis (typical frequency of 2-3 logs per second).
My questions:
1) Should I derive from Service or IntentService. The doc says about IntentService: "This is the best option if you don't require that your service handle multiple requests simultaneously". This may be my case since the main activity will start/stop the service...
2) What would be the appropriate way to catch the service events? Does the BroadcastReceiver is appropriate for this type of communication?
3) I may need to occasionally send some stuff to the Bluetooth port. So, I'll have to pass information from my application to the service. Does the PendingIntent should be used for that?
Thank you!
Should I derive from Service or IntentService
IntentService is designed for discrete tasks, not stuff that would run indefinitely until the user manually stops it. I would use Service.
What would be the appropriate way to catch the service events? Does the BroadcastReceiver is appropriate for this type of communication?
That is certainly one approach. You might use the LocalBroadcastManager from the Android Support package to reduce overhead and keep everything private to your app. Have your activities register a receiver in onResume() and remove it in onPause(). The foreground activity will then be notified of events.
I may need to occasionally send some stuff to the Bluetooth port. So, I'll have to pass information from my application to the service. Does the PendingIntent should be used for that?
No, I would have the activity simply send a command to the service via startService(), with the data to be passed included in extras on the Intent. If you have data that cannot be packaged as extras, you may need to consider binding to the service, so you can get a richer API, though this makes configuration changes more annoying.