Android Using ordered broadcasts


Ordered broadcasts are used when you need to specify a priority for broadcast listeners.

In this example firstReceiver will receive broadcast always before than a secondReceiver:

final int highPriority = 2;
final int lowPriority = 1;
final String action = "action";

// intent filter for first receiver with high priority
final IntentFilter firstFilter = new IntentFilter(action);
first Filter.setPriority(highPriority);
final BroadcastReceiver firstReceiver = new MyReceiver();

// intent filter for second receiver with low priority
final IntentFilter secondFilter = new IntentFilter(action);
final BroadcastReceiver secondReceiver = new MyReceiver();

// register our receivers
context.registerReceiver(firstReceiver, firstFilter);
context.registerReceiver(secondReceiver, secondFilter);

// send ordered broadcast
context.sendOrderedBroadcast(new Intent(action), null);

Furthermore broadcast receiver can abort ordered broadcast:

public void onReceive(final Context context, final Intent intent) {

in this case all receivers with lower priority will not receive a broadcast message.