How to use "goAsync" for broadcastReceiver?
You can find short explanation here.
Use goAsync()
if you want to handoff the processing inside of your BroadcastReceiver
's onReceive()
method to another thread. The onReceive()
method can then be finished there. The PendingResult is passed to the new thread and you have to call PendingResult.finish()
to actually inform the system that this receiver can be recycled.
For example:
final PendingResult result = goAsync();
Thread thread = new Thread() {
public void run() {
int i;
// Do processing
result.setResultCode(i);
result.finish();
}
};
thread.start();
In kotlin you can write an extension function on BroadcastReceiver:
/**
* Run work asynchronously from a [BroadcastReceiver].
*/
fun BroadcastReceiver.goAsync(
coroutineScope: CoroutineScope,
dispatcher: CoroutineDispatcher,
block: suspend () -> Unit
) {
val pendingResult = goAsync()
coroutineScope.launch(dispatcher) {
block()
pendingResult.finish()
}
}
After that inside your broadcast receiver you can do the following:
class AlarmBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
// Code here runs on the main thread
goAsync(GlobalScope, Dispatchers.Default) {
// The code here will run on the background by the default dispatcher on the global scope
// If your code here touches the IO, then you can use Dispatchers.IO instead
}
}