I want to create an application in which
- Create a listener which listens for outgoing/incoming messages and calls
- UI is shown/hide based on listener results
Shrini,
As dds stated, you will definitely need at least two BroadcastReceivers. You will need one BroadcastReceiver for each incoming call and message that you want to respond to, and one for each outgoing one as well. A BroadcastReceiver may only capture one BroadcastMessage at a time. You will specifically need to capture the Intents sent by the operating system and your Application will need to have the appropriate Permissions for each. That's just setting up the listeners.
Once the BroadcastReceiver has been called you will need to start an Activity for you UI and possibly a Service to do any other processing. In the cases of single-point events (like messages) an Activity is often enough. Calls, however, depend largely upon what you are doing. Since a call has two distinct events, in order to tie them together, many people prefer to use a Service just to hold and watch the call.
In order to best help you, I must inform you that your question is remarkably vague as to what you need to do. Does your custom UI display information about the calls? Does it allow the User to respond or change that information? What kind of messages is your app responding to? SMS? Email? IMs? These are important because each one has different considerations.
Given that the limitation of information provided here, I would recommend researching your topic by downloading and viewing some of the open source projects stored on Google. Here is a Here.
Fuzzical Logic
Create a listener which listens for
outgoing/incoming messages and calls -
UI
To achieve this I think you need to use broadcast receivers to catch the broadcast message when any message activity is going on. You may need 2 in BroadcastReceivers , one for incoming and one for outgoing messages.
In the receivers you need to call your related Activity (your UI) to interact with the user. But note that you should not do any time consuming work in BroadcastReceiver since in BroadcastReceivers are expected to be light weight and killed in 10 seconds after they are invoked. See Broadcast receivers at here
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.
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.
If you have a Service that frequently (every second or half a second) sends updates, are there pros/cons to using Broadcasts vs registering Listeners (an Interface you create) that get stored in some sort of List in the Service and sending out updates that way?
I'm thinking in terms of memory usage, battery consumption, etc. I know it's a little bit open ended, however, there's not much in terms of documentation so they can be equal, but if someone knows a definite answer or has some input, it would be appreciated.
In my experience, if you will send out notifications frequently, choose listeners. I've implemented some BroadcastReceivers for the same matter, but some messages got lost. I think this is because the BroadcastReceivers do not queue incoming intents but instead drop those arriving whilst still "doing work with the old one".
Of course broadcasting intents can be more relaxing, as you don't have to.. connect the service and every listening part of your application, but in my case (multiple messages per second) listeners were the right choice.
Do not think about this things, it is really small amount of energy and perfomanse. Main difference between Broadcasts and Listeners is a way there your messages will go. If it's Broadcasts your ivents will go throgh system othervise they will go directly to your class.
Anyway you should create a BroadcastReciever to get updates (so it's still a listener). But in this case os cares to call them instead of direct listener calls from service. Not sure about value of differance, but direct calls looks faster, and less memory/battery consumpting from this pov.
I am having some trouble creating a NON-IPC service that allows adding/removing multiple listeners at various times, for example, I would like to be able to contact the service and "subscribe" to its events any time, or "unsubscribe" from it. The service wakes up every once in a while and sends an event to all subscribed listeners.
I have been looking at stackoverflow examples, googling, etc, particularly I found something similar here:
android restful api
In that example, the suggestion is to use ResultReceiver to serve as a callback from a service. But in this approach, doesn't it mean that the service can only notify listeners sent to it as part of the first intent (i.e I cannot add/remove listeners whenever I want)?
Also, in that example, what happens if the activity gets destroyed by the OS for some reason, but the service still has a reference to the listener and tries to invoke it? The listener will try to perform some action on the activity, which no longer exists, right?
Maybe I am missing something... I'd appreciate some input if possible..
Tnx
First, 'sleeping' services are anti-pattern in Android. If you need to do something periodically, start your service using AlarmManager. Second, the service can be restarted at any time, so you cannot rely on 'subscribing' where you keep references to other components (activities mostly). If you need to send a notification to multiple activities, use a broadcast receiver. Activities can register for it statically (using AndroidManifest.xml), or dynamically (with code).
I started with a standard local android service, and used Binders with Listeners to communicate. Then: I began noticing some serious issues with handling orientation changes, so I decided to skip the whole binder thing, and just go with broadcasting intents (and using startService exclusively) that contain all the data/commands that need to be passed.
My question is: what are some of the pitfalls I have to look out for when using this approach?
Are there any disadvantages?
If you are supporting API Level 4 and above, use setPackage() to make your "broadcast" be a "narrowcast" -- keeping the broadcast within your app. By default, the broadcast is truly broadcast, to all apps, which may or may not be a good thing for your data.
Don't forget to unregister your BroadcastReceiver (i.e., don't register it and forget it). At the same time, you will need to consider what to do if the service wraps up and the activity is long gone (e.g., BACK button). One approach is to use an ordered broadcast with a low-priority manifest-registered receiver that will raise a Notification if no activity handles the broadcast -- this sample app demonstrates what I mean.
You might consider a Messenger instead of the broadcast approach, as it is intrinsically a "narrowcast", probably is a smidge less overhead, and can't be leaked. I am still working through the mechanics of using this with configuration changes, though.