使用有序广播

当你需要为广播侦听器指定优先级时,将使用有序广播。

在这个示例中,firstReceiver 将始终接收广播而不是 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);
secondFilter.setPriority(lowPriority);
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);

此外,广播接收器可以中止有序广播:

@Override
public void onReceive(final Context context, final Intent intent) {
    abortBroadcast();
}

在这种情况下,所有具有较低优先级的接收器将不会接收广播消息。