Code we execute in the onReceive() implementation is considered a foreground process. The broadcast receiver is active until we return from the method. The system will always run your code defined in the implementation, except if extreme memory pressure occurs. As we mentioned, you should perform short operations only! Otherwise, ANR can occur! A good example of executing a long running operation when a message is received is by starting AsyncTask and performing all the work there. Next, we will show you an example demonstrating this:
class AsyncReceiver : BroadcastReceiver() { override fun onReceive(p0: Context?, p1: Intent?) { val pending = goAsync() val async = object : AsyncTask<Unit, Unit, Unit>() { override fun doInBackground(vararg p0: Unit?) { // Do some intensive work here... pending.finish() } } async.execute() }
}
In this example, we introduced the use of the goAsync() method. What does it do? The method returns an object of the PendingResult type, which represents a pending result from calling an API method. The Android system considers the receiver alive until we call the finish() method on this instance. Using this mechanism, it's possible to do asynchronous processing in a broadcast receiver. After we finish our intensive work, we call finish() to indicate to the Android system that this component can be recycled.