Receivers execution

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

Get Mastering Android Development with Kotlin now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.