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.
Related
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.
I need to submit some data as soon as there is an internet connection. Until now I've done this by registering a broadcast receiver in the manifest for the CONNECTIVITY_ACTION event. This works perfectly but now I'm worried about the performance.
I mean a CONNECTIVITY_ACTION broadcast is sent pretty often sometimes and the every time my app will be "started" just to try to submit some data, that might not even exist at that moment.
Is there a better way to do that? Or does it not really matter?
I mean I could register a receiver in every activity but that's not very neat I think. I know I could make a class derive from Activity (to override onResume and onPause) but as I'm also using FragmentActivity, that isn't the best option either.
Do you have some suggestions on how to do that? The data doesn't need to be sent immediately if a connection is available (I mean that would be very nice but not necessary).
I could also just try to send the data in the onResume method of every activity but again that's not as neat as I'd like it...
Many apps fire up receiving that broadcast. Check the logcat yourself. Some apps have a running service that check for a connection, vomiting out exceptions.
As many times stated by Google engineers, it's less taxing on the battery to do your tasks upon radio being in active mode and do some extra for caching, than to wind up radio every few minutes. Refer to 2012 Google I/O speech by Reto Meier. He outlines a bit how it should work and why.
What would be the best way to implement this. I have an Android app that will use my python server to allow communication between 2 phones in rounds. Rounds mean that they can't talk to each other until a round start and once they send a message they can't send another until the other person responds which will then start a new round.
I was thinking I would use the IntentService but it seems wrong to have the server constantly starting and stopping and I don't won't to have to worry about the issues with asynctask or is that the best way to handle it. How could I have a service that should receive and send messages to the client, seems services are more one way things?
Intent services are nothing more that worker threads that are triggered by intents, execute their actions in a separate thread and then get shut down. They are designed to be started and stopped.
If you need to perform stuff like an http get, or in any case interaction that do not require to stay connected to the server, use intent services and get your activities notified using broadcast events.
If your app needs to stay connected with the server (i.e. permanent tcp connection), the way I'd go for is to have a service (not an intent one) that performs the networking stuff using an asynctask or a more classic thread hosted in the service. You can then make the activity interact with the service using bindToService() .
I'd recommend not to use asynctasks inside an activity. You will risk to loose the server response in case of horizontal / vertical view changes, as oneilse14 stated in his reply.
I highly recommend the IntentService/Broadcast Receiver route. Avoiding the nasty configuration change issues associated with AsyncTask will make your life ten times easier.
As far as i understood your problem is of type worker-queue model Producer-consumer model). Intentservices are meant to do that. You should use services if and only you need to do multithreading. You do can communicate with Activity and Service by using IBinder interface.
Asynctask are just a specialized threads so that you can update your UI easily. But for your case IntentService seems to be best option.
I would use an Alarm, which is scheduled via the AlarmManager, as then it can be set to check if the round has started/turn. It has the advantages of a service but not the horrors of battery drain. It takes a frequency to how often the Alarm should run, which even includes enumerations of time (e.g. 1 hour/day/week).
When the Alarm runs it could poll to see what the current state is and react accordingly. For example a notification could go into the status bar and phone could make an audible noise and vibrate.The benefit of this is that the user does not have to keep the app running as the Alarm will trigger a broadcast receiver.
An example of the Alarm code: http://www.androidcompetencycenter.com/2009/02/android-basics-alarm-service/
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.
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