How to run Broadcast Receiver on Worker Thread?


When you Register for any Broadcast receiver by Default onReceive() method will be called on the Main Thread( UI Thread). But If we want to do any heavy operations or if your broadcast is calling multiple times, then so much load will be accumulated on Main Thread which is not recommended. To overcome this, the ideal solution is to move the entire operation on the worker Thread. To achieve this while registering the Broadcast receiver itself, we can provide the scheduler to registerReceiver() variant.


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

broadcastPermission allows you to apply for permissions on who can broadcast intents to your receiver and scheduler allows the receiver to run in a different thread.

The below snippet of code is to create a Handler by using the HandlerThread and register a Broadcast using that.


HandlerThread broadcastHandlerThread = new HandlerThread("BroadcastRegisterThread"); broadcastHandlerThread.start(); Looper looper = broadcastHandlerThread.getLooper(); Handler broadcastHandler = new Handler(looper);

registerReceiver (receiver, intentFilter, broadcastPermission, broadcastHandler);

this is how we can register the receiver in the context of the scheduler.

Leave A Comment

Your email address will not be published. Required fields are marked *