What is more efficient Broadcast Receiver or Handler?

Rohit Rokde picture Rohit Rokde · Aug 11, 2014 · Viewed 11.9k times · Source

I know that onReceive() of the Broadcast receiver and handleMessage() of Handler run on the same UI thread. Suppose I want to communicate between two services, within the same app (process) . I can extend a broadcast receiver class and register an event

OR

a Handler and then pass its instance to the other service to be used for sendMessage() calls. In both the cases I would need to add some new switch case. But which approach is more efficient ? Lets assume that the code is thread safe (no UI updations).

Answer

Xaver Kapeller picture Xaver Kapeller · Aug 11, 2014

You should not use normal broadcasts to communicate between Activities and Services inside of your own app. You should use local broadcasts instead! First you have to define a BroadcastReceiver like for normal broadcasts:

private static final String ACTION_EXAMPLE = "ACTION_EXAMPLE";

private final BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if(ACTION_EXAMPLE.equals(intent.getAction())) {
            ...
        }  
    }
};

After that you can get the LocalBroadcastManager like this:

LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getActivity());

And you can register the BroadcastReceiver like this (normally you register a BroadcastReciever in onResume()):

@Override
public void onResume() {
    super.onResume();

    LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getActivity());
    IntentFilter filter = new IntentFilter(ACTION_EXAMPLE);
    manager.registerReceiver(this.receiver, filter);
}

Don't forget to unregister the BroadcastReceiver later on (in onPause()):

@Override
public void onPause() {
    super.onPause();

    LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getActivity());
    manager.unregisterReceiver(this.receiver);
}

And finally you can send local broadcasts like this:

LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getActivity());
manager.sendBroadcast(intent);