Android BroadcastReceiver之自定义无序、有序广播

时间:2021-05-25 15:26:29

广播的两种类型
* 无序广播:所有跟广播的intent匹配的广播接收者都可以收到该广播,并且是没有先后顺序(同时收到)
* 有序广播:所有跟广播的intent匹配的广播接收者都可以收到该广播,但是会按照广播接收者的优先级来决定接收的先后顺序
* 优先级的定义:-1000~1000
* 结果接收者:所有广播接收者都接收到广播之后,它才接收,并且一定会接收
* abortBroadCast:阻止其他接收者接收这条广播,类似拦截,只有有序广播可以被拦截

发送自定义广播

无序广播

  • 所有与广播中的intent匹配的广播接收者,都可以收到这条广播,并且不分先后顺序,视为同时收到

有序广播

  • 所有与广播中的intent匹配的广播接收者,都可以收到这条广播,但是是分先后顺序的,优先级高的先收到,优先级低的后收到
 public void click(View v){
Intent intent = new Intent();
intent.setAction("a.b.c");
//发送自定义无序广播
sendBroadcast(intent);
}
   <receiver android:name="com.cy.receivecustombroadcast.MyReceiver">
<intent-filter >
<action android:name="a.b.c"/>
</intent-filter>
</receiver>
public class MyReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
System.out.println("接收到自定义广播");
}

}
 public void click(View v){
Intent intent = new Intent();
intent.setAction("com.center.fdm");
//发送自定义有序广播
//resultReceiver:在所有广播接收者都收到广播之后,才会收到,一定是最后一个收到,并且一定能收到
sendOrderedBroadcast(intent, null, new MyReceiver(), null, 0, "每人发100斤大米", null);
}

class MyReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
String order = getResultData();
System.out.println("反贪局收到文件:" + order);

}

}
  <receiver android:name="com.cy.local.ShengZF">
<intent-filter android:priority="1000">
<action android:name="com.center.fdm"/>
</intent-filter>
</receiver>
<receiver android:name="com.cy.local.ShiZF">
<intent-filter android:priority="800">
<action android:name="com.center.fdm"/>
</intent-filter>
</receiver>
<receiver android:name="com.cy.local.XianZF">
<intent-filter android:priority="600">
<action android:name="com.center.fdm"/>
</intent-filter>
</receiver>
public class ShengZF extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
//获取*的红头文件
String order = getResultData();
System.out.println("省*收到文件:" + order);
//无序广播不能修改广播内容
setResultData("每人发80斤大米");
}

}
public class ShiZF extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
//获取*的红头文件
String order = getResultData();
System.out.println("市*收到文件:" + order);
//无序广播不能拦截
abortBroadcast();
}

}
public class XianZF extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
//获取*的红头文件
String order = getResultData();
System.out.println("县*收到文件:" + order);
}

}

参考:Android BroadcastReceiver