Does BroadcastReceiver.onReceive always run in the UI thread?

AndroidBroadcastreceiver

Android Problem Overview


In my App, I create a custom BroadcastReceiver and register it to my Context manually via Context.registerReceiver. I also have an AsyncTask that dispatches notifier-Intents via Context.sendBroadcast. The intents are sent from a non-UI worker thread, but it seems that BroadcastReceiver.onReceive (which receives said Intents) always runs in the UI thread (which is good for me). Is this guaranteed or should I not rely on that?

Android Solutions


Solution 1 - Android

> Does BroadcastReceiver.onReceive always run in the UI thread?

Yes.

Solution 2 - Android

Since you dynamically register the receiver you can specify that another thread (other than the UI thread) handles the onReceive(). This is done through the Handler parameter of registerReceiver().

That said, if you did not do specify another Handler, it will get handled on UI thread always.

Solution 3 - Android

> Does BroadcastReceiver.onReceive always run in the UI thread?

Usually, it all depends how you register it.

If you register your BroadcastReceiver using:

registerReceiver(BroadcastReceiver receiver, IntentFilter filter)

It will run in the main activity thread(aka UI thread).

If you register your BroadcastReceiver using a valid Handler running on a different thread:

registerReceiver (BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)

It will run in the context of your Handler

For example:

HandlerThread handlerThread = new HandlerThread("ht");
handlerThread.start();
Looper looper = handlerThread.getLooper();
Handler handler = new Handler(looper);
context.registerReceiver(receiver, filter, null, handler); // Will not run on main thread

Details here & here.

Solution 4 - Android

As the previous answers correctly stated onReceive will run on the thread it's registered with if the flavour of registerReceiver() that accepts a handler is called - otherwise on the main thread.

Except if the receiver is registered with the LocalBroadcastManager and the broadcast is via sendBroadcastSync - where it will apparently run on the thread that calls sendBroadcastSync.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHannes StrußView Question on Stackoverflow
Solution 1 - AndroidCommonsWareView Answer on Stackoverflow
Solution 2 - AndroidTommyThView Answer on Stackoverflow
Solution 3 - AndroidCanerView Answer on Stackoverflow
Solution 4 - AndroidMr_and_Mrs_DView Answer on Stackoverflow