Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does BroadcastReceiver.onReceive always run in the UI thread?

People also ask

Is broadcast receiver on main thread?

When you Register for any Broadcast receiver by Default onReceive() method will be called on the Main Thread( UI Thread).

What is the role of the onReceive () method in the BroadcastReceiver?

Retrieve the current result extra data, as set by the previous receiver. This can be called by an application in onReceive(Context, Intent) to allow it to keep the broadcast active after returning from that function.

Does broadcast receiver run in background?

A broadcast receiver will always get notified of a broadcast, regardless of the status of your application. It doesn't matter if your application is currently running, in the background or not running at all.

On which thread broadcast receiver will work in Android?

Broadcast Receiver by default runs on Main Thread only.


Does BroadcastReceiver.onReceive always run in the UI thread?

Yes.


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.


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.


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.