广播
一、自定义广播
- 首先定义Intent,广播要把Intent发送出去。
- 然后,定义Action,为了和接收广播的Action进行匹配。
- 数据存储在Intent中,最后通过sendBroadcast把Intent广播出去。
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent=new Intent();
intent.setAction("com.lyjs.sendBroadcast");
sendBroadcast(intent);
}
二、广播的分类
- 无序广播:好比老师在讲台上讲话,所有的同学同时听到讲话的内容,这就是有序广播。
- 有序广播:好比国家发布文件,从国家政府机关,到省机关,到市机关。层层传达,这就是有序广播。广播内容有可能被劫持。
有序广播发送广播时候要使用sendOrderedBroadcast()方法。
void android.content.ContextWrapper.sendOrderedBroadcast(Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)
BroadcastReceiver resultReceiver :第三个参数接收一个广播接受者。该广播接收者不需要再清单文件中配置,这个广播接收者只接受该条有序广播,肯定可以接收到广播(即使广播中断),并且是最后一个收到该广播。
sendOrderedBroadcast(intent, null, new MyReceiver(), null, 0, "没人发100斤大米", null);
class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
String text=getResultData();
System.out.println("发改委收到的通知:"+text);
}
}
在有序广播中,可以设置各个接收者的优先级,android:priority="300",最高级是1000
<receiver android:name="com.lyjs.difang.DiZF">
<intent-filter android:priority="300">
<action android:name="com.lyjs.fdm"/>
</intent-filter>
</receiver>
在任何一个广播接收者中,都可以终止广播,同时可以修改接收到的数据
setResultData("下发八十斤大米"); //更改接收到的数据
abortBroadcast(); //终止广播的传播
注意:setResultData()、abortBroadcast() 这两个方法只对有序广播有效果,对无序广播无效。

浙公网安备 33010602011771号