使用有序廣播

當你需要為廣播偵聽器指定優先順序時,將使用有序廣播。

在這個示例中,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();
}

在這種情況下,所有具有較低優先順序的接收器將不會接收廣播訊息。