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. A service can queue up multiple requests and run them in order or otherwise manage requests as it sees fit. This is the method we recommend. A service has a much longer window it can use to perform work, but it may still be stopped if it runs for long periods. (This threshold varies by OS version and device, but it is generally on the order of several minutes on newer devices.) You can also choose to run a service in the foreground to remove all limits on how long your work can run, which is ideal for tasks like backing up photos, playing music, or giving turn-by-turn navigation.

The second option is to use the BroadcastReceiver.goAsync() function. This function 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 functions on PendingResult.

There is one downside to using the goAsync() function: 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
18.191.132.194