missing broadcast intents when the device is rotated? - android

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...

Related

BroadcastReceiver and ResultReceiver in android [duplicate]

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.

How to self stop a service started with BIND_AUTO_CREATE?

There is some long processing that need to be completed, so I put it in a service. The activity must be able to connect to the service, show the user current results from the service. So I start the service with start Service and later call bind Service (with BIND_AUTO_CREATE) as in LocalService from http://developer.android.com/reference/android/app/Service.html#ServiceLifecycle. I want it to run until its job is done, and then self stop, even if client is still connected to it. (or determine the client to unbind) Is any way to do it with the sample LocalService?
I was considering passing a handler to the service so that it can send messages back to the activity, but I don't want the activity to get leaked. I am just getting used with services, so maybe I am misusing something.
EDIT: The workload consists of several threads, synchronized and run in parallel, so I guess is not a good candidate for intent service. Some data analysis is done in background service, and when the user restarts the activity that started the service, it should display some graphics according to current values computed by background service. All background processing is triggered at the beginning, and need only inspection later on, when activity connects to it. Android should not be able to stop the service. When the job is finished, the service should be able to terminate even if the activity is connected to it.
I just recorded a callback with the service. If the activity is not connected to service, it sets the callback to null. In this callback I call stopService() and then finish() on the activity. I am not sure that it is the best method, but it works fine for me.
If you want a service to be stopped when it is finished, I think what you are looking for is IntentService, they work as services, but run in another thread and when they are completed they dissappear.
Check this out
EDIT: NickT link is better, check that out! :)

Broadcast Receiver and ResultReceiver in android

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.

Is it possible that an IntentService will be killed before the Activity using it?

I have an application that has an IntentService to provide background processing - specifically it fetches data from the net and stores it in an Sqlite database.
My Activities use Context.startService() to request the service to update data, and the service sends a local broadcast message when the update is complete.
The IntentService uses a thread pool to do the work - primarily in case a new Activity is opened before a request is complete, so a new request for a different resource won't block waiting for the previous one to finish.
That all works fine, but in order to prevent multiple simultaneous requests for the same resource, I set a flag in the activity after it has sent a request which stops it sending new requests until it gets back a DONE message from the service.
Now if the IntentService was killed off in the middle of an operation it will never send the DONE message, and the Activity will never know that the request is unfulfilled, and will not re-request the resource. Is this possible? And if it happens is there any way for the Activity to be informed?
Is this possible?
So long as you are catching all possible unhandled exceptions, no. Components are not "killed" individually for, say, memory reclamation -- that is done on a process-by-process basis.
If you are concerned about this then send a broadcast flag in the onDestroy of the IntentService (or just set a breakpoint so you can see if it is being hit). The IntentService is intended as a simplified service which handles its own lifecycle so if you are passing work from the service to a thread pool it's possible the IntentService believes it finishes its work - you can catch this in onDestroy.
Obviously can't say if that is happening without looking at the code but this mechanism will let you check if it is.

using synchronous and async communication between Activity and Service on Android

I am currently writing an app, which consists of a service and an activity. The service is running in the background, doing some live audio processing. If the user want to get some information about the running service or want to change the settings of the service, the activity gets started and bind to the service.
Currently i am using the asynchronous messenger system to communicate between the service and the activity. For example, the service can send some results to the activity through a message and the activity can handle this message and show the results. This works fine, but it is stressful to write the messaging stuff for each communication. And it is not always needed. Sometimes i only want to ask the service, if a flag is set or not. If i do this asynchronous, i have to send a message to the service which asks for the value of the flag and the service has then to send a message back to the activity to answer the request.
So i want to have some getter and setter which can synchronously access the service. This can be done by using a binder, which works too.
The problem is, that i sometimes need synchronous communication to get the value of flags etc. and sometimes i need asynchronous communication to push the results from the service to the activity. So what i need is a binder and a messenger. But i dont know how this can be done, because the service can only return one object from the onBind() method, either a binder object or a messenger object.
Do you have any suggestions how this can be done or some other approach to realise asynchronous and synchronous communication between an activity and a service?
Thanks in advance!
Tobias
If you are already binding to the service, your activity can supply a listener object to the service, which the service will then call when events occur.
You just need to make sure that you unregister that listener object before unbinding from the service, and do both before the activity is destroyed, so your service does not wind up with a strong reference to a defunct activity.

Categories

Resources