Receivers and Long-Running Tasks

So what do you do if you want a broadcast intent to kick off a longer-running task than the restrictions of the main run loop allow?

You have two options. The first is to put that work into a service instead and start the service in your broadcast receiver’s small window of opportunity. This is the method we recommend. A service can take as long as it needs to service a request. It can queue up multiple requests and service them in order or otherwise manage requests as it sees fit.

The second is to use the BroadcastReceiver.goAsync() method. This method returns a BroadcastReceiver.PendingResult object, which can be used to provide a result at a later time. So you could give that PendingResult to an AsyncTask to perform some longer-running work and then respond to the broadcast by calling methods on PendingResult.

There is one downside to using the goAsync method: It is less flexible. You still have to service the broadcast within 10 seconds or so, and you have fewer architectural options than you do with a service.

Of course, goAsync() has one huge advantage: You can set results for ordered broadcasts with it. If you really need that, nothing else will do. Just make sure you do not take too long.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.185.180