广播有两种不同的类型:普通广播(normal broadcasts)和有序广播(ordered broadcasts)。普通广播是完全异步的,可以被所有的接收者接收到,并且接收者无法终止广播的传播。然而有序广播是按照接收者声明的优先级别,被接收者依次接收到。优先级别声明在 intent-filter 元素的 android:priority 属性中,数越大优先级别越高,取值范围:-1000到1000,优先级别也可以调用IntentFilter对象的setPriority()进行设置。有序广播的接收者可以终止广播Intent的传播,广播Intent的传播一旦终止,后面的接收者就无法接收到广播。
发送普通广播,所有订阅者都有机会获得并进行处理:
Context.sendBroadcast()
发送有序广播,系统会根据接收者声明的优先级别按顺序逐个执行接收者:
Context.sendOrderedBroadcast()
本示例将smsReceiver的优先级设为1000,拦截短信
public class MsgReceiver extends BroadcastReceiver { public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED"; static String tag = "SmsDemo"; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (SMS_RECEIVED_ACTION.equals(action)) { Bundle bundle = intent.getExtras(); if (bundle != null) { Object[] pdus = (Object[]) bundle.get("pdus"); for (Object pdu : pdus) { SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu); String msg = "拦截到短信:\n来自:" + message.getOriginatingAddress() + "\n内容:" + message.getMessageBody(); Toast.makeText(context, msg, Toast.LENGTH_LONG).show(); abortBroadcast(); } } } } }
注册MsgReceiver
MsgReceiver receiver = new MsgReceiver(); IntentFilter filter = new IntentFilter(); filter.setPriority(1000); filter.addAction(MsgReceiver.SMS_RECEIVED_ACTION); registerReceiver(receiver, filter);