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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.