发送广播
Intent intent = new Intent();
// 这个action对应的事现实生活中的广播频道
intent.setAction("
com.example.broadcast.music");
//通过intent传值
intent.putExtra("msg", data);
sendBroadcast(intent);
接受广播
public
class MyReceiver extends BroadcastReceiver {
// 接受广播后的回调函数
@Override
public void onReceive(Context context, Intent intent) {
int i=intent.getIntExtra("msg", 0);
System.out.println("接收到广播了"+intent.getAction()+"__"+i);
}
}
注册广播
方法一:
//如果是独立的广播接受类可以在manifest.xml中配置
<receiver android:name="com.example.android_server.broadcast.MyReceiver" >
<intent-filter android:priority="200">
//android:priority 优先级(值越大优先级越高)
<action android:name="com.example.broadcast.myreceiver" />
</intent-filter>
</receiver>
方法二:
MyReceiver receiver=new MyReceiver();
IntentFilter filter=new IntentFilter();
filter.addAction("
com.example.broadcast.music");
//注册广播接收者
registerReceiver(receiver, filter);
接受短信
public class SMSReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("接收到短信了");
Bundle bundle = intent.getExtras();
Object[] plus = (Object[]) bundle.get("pdus");
SmsMessage message = SmsMessage.createFromPdu((byte[]) plus[0]);
System.out.println(message.getDisplayOriginatingAddress());
System.out.println(message.getDisplayMessageBody());
//终结广播,拦截
abortBroadcast();
}
}
//配置
<receiver android:name="com.example.android_server.broadcast.sms.SMSReceiver" >
<intent-filter android:priority="800" >
<action android:name="
android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
//权限
<uses-permission android:name="android.permission.RECEIVE_SMS" />
/****************************************************************************************/
•Normal BroadCast
异步的,同一时刻被所有接受者接收到。不能把处理结果传给下一个接收者,不能终止BroadCast Intent的传播
•Ordered BroadCast
根据优先级进行传播,可以将数据传递给下一个接收者(SetResultExtras(Bundle)),可以终播(abortBroadcast())。