Reputation: 49
Can a receiver be registered with LocalBroadcastManager
to execute in a different thread?
We register for an intent with LocalBroadcastmanager using
void registerReceiver (BroadcastReceiver receiver, IntentFilter filter)
Suppose I want the onReceive
method to be called on a different thread other than the main thread then how do I achieve it?
I don't see any API like
Intent registerReceiver (BroadcastReceiver receiver,
IntentFilter filter,
String broadcastPermission,
Handler scheduler)
Upvotes: 1
Views: 315
Reputation: 729
I have forked LocalBroadcastManager and enhanced it to be able broadcast on an arbitrary java thread. Essentially I keep a map of Handers derived from a new Looper param in the registerReceiver method. The handler is invoked when it is time to broadcast. Synchronous behavior is unchanged. I have used it extensively but would appreciate any constructive criticism. The code is here:
public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter, Looper looper)
https://github.com/sorenoid/LocalBroadcastManager
I hope it is helpful.
Upvotes: 0
Reputation: 39853
The direct answer is no.
You'd have to handle the threading yourself. You have sendBroadcast()
and sendBroadcastSync()
. The first calls schedules the events to run on the main thread. The second one blocks the current thread and sends all pending broadcasts there.
Therefore calling sendBroadcastSync()
might have unintended side-effects on other events which might require the main thread. So you could better wrap your receiver in one which is aware of the other threads to reschedule the event there again.
public class HandlerBroadcastReceiver extends BroadcastReceiver {
private final Handler handler;
private final BroadcastReceiver receiver;
HandlerBroadcastReceiver(Handler handler, BroadcastReceiver receiver) {
this.handler = handler;
this.receiver = receiver;
}
@Override public void onReceive(Context context, Intent intent) {
handler.post(() -> receiver.onReceive(context, intent));
}
}
Upvotes: 1