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!
Related
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 have an app with an auto log out feature where I was using a Timer to auto log out the user (where user is a static singleton object).
Recently I realized there were some other activities and I have to implement a global log out feature so I tried to implement different Timers to each Activities and tried to synchronize them, but it wasn't a good approach and it was a pain. Then I turned my face to the services.
What I need to know is a good way to control a single service within different applications. Any ideas will be appreciated.
You can implement bound service, start it, and bind it with two activities.
More information You can find in official developer docs this and this
you can implement a "Bound" service to interact it from different activities.
Here is complete example for Bound service with explanation.
http://developer.android.com/guide/components/bound-services.html
A broadcast is a message that any app can receive. The system delivers
various broadcasts for system events, such as when the system boots up
or the device starts charging. You can deliver a broadcast to other
apps by passing an Intent to sendBroadcast(), sendOrderedBroadcast(),
or sendStickyBroadcast().
All that you need to do is to create BroadcastReceiver. Add IntentFilter for it. Register it in your Service. And than send Intent with action that you add to IntentFilter from any of your Applications.
Go throw this article to get better understanding of Intents
Are there any use cases in which I would want to use a BroadcastReceiver for something other than cross-application communication?
After reading the documentation, it seems like they are targeted at cross-application communication, but the idea of using them with the LocalBroadcastManager is also mentioned. I also read this post, which addresses the general usage of broadcast receivers. Neither seem to hit clearly on why it would be useful to use broadcasts and receivers for anything other than cross-application communication.
Does it have anything to do with their asynchronous nature, or maybe they're just used to move some processing out of the main activity?
Clarification: I guess the term cross-application was too general. I was considering the built-in actions such as
android.hardware.action.NEW_PICTURE
to be coming from applications. What I would like to know is: when is it useful to use a BroadcastReceiver for communication within my app - I guess this would narrow it down to custom intent actions/categories. Sorry if the way I'm asking this is confusing. I've only just recently begun programming with Android and I still don't understand the OS very well.
As it quotes in the post you linked: "A broadcast receiver is a component that responds to system-wide broadcast announcements. Many broadcasts originate from the system."
Therefore, they are useful in "catching" system broadcasts, e.g., when the device has booted up, when the battery level changes, when your Wi-Fi has been turned on, etc.
Personally, I've used a BroadcastReceiver to start my app whenever the device receives a text message. In my case, this is preferred, as my app does not need to be running when the text message is received. Upon receipt, the system will broadcast an intent with an SMS_RECEIVED action. My BroadcastReceiver component, registered to accept this particular type ofbroadcast, will be notified and can then react as needed. In my case, it launches an Activity to notify the user of the text message and choose a particular reply text message.
This is just a specific example. There are many other broadcasts that the system transmits and your Receiver can get. Check this link and this post for more examples.
Clarification:
A LocalBroadcastManager is preferable in instances when you want rather simple way to communicate between app components without an intent being broadcast system-wide. Knowing this, you would want to go this route when the info you're passing is to be used only by your app. A LocalBroadcastManager is more efficient, generally simpler than using an IBinder interface, and can ensure that information isn't leaving your app.
For an example, suppose you have a Service that runs in the background to track and log some constantly changing data; let's say your battery level. The Service can run on its own without user interaction, saving the battery level to the disk as it changes. When you start your activity to view said data, it would use LocalBroadcastManager to register a receiver to accept the info the Service is sending, and update the Activity's UI in real time to reflect this. Since no other app needs the info from your Service, it's better to do this than broadcasting an intent to which any other app could have access.
To sum up, using a LocalBroadcastManager is:
More efficient.
More secure.
Simpler.
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 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.