广播分为有序广播和无序广播
- 有序广播
所有与广播中的action匹配的广播接收者都可以收到这条广播,但是是有先后顺序的,按照广播接收者的优先级排序.
- 无序广播
所有与广播中的action匹配的广播接收者都可以收到这条广播,并且是没有先后顺序的,视为同时收到
有序广播
- sendOrderedBroadcast发送
- 可以添加最终广播接收者,最终广播接收者resultReceiver:不需要在清单文件中配置,这个广播接收者只接收该条有序广播,并且是最后一个收到该广播,并且一定可以接收到,即便被拦截
发出广播
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View v) {
Intent intent = new Intent();
intent.setAction("orderlyBroadcast");
//发送有序广播
//sendOrderedBroadcast(intent, null, null, null, 0, "每人发100W", null);
//最终广播接收者resultReceiver:不需要在清单文件中配置,这个广播接收者只接收该条有序广播,并且是最后一个收到该广播,并且一定可以接收到,即便被拦截
sendOrderedBroadcast(intent, null, new MyResultReceiver(), null, 0, "每人发100W", null);
}
class MyResultReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String str = getResultData();
System.out.println("最终结果:" + str);
}
}
}
接收者
- 优先级 android:priority="300" 范围-1000 至 1000 1000为最高
- 阻止广播 abortBroadcast(),对于最终接收者来说,无效.
<receiver
android:name=".LevelOneReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="orderlyBroadcast"></action>
</intent-filter>
</receiver>
<receiver
android:name=".LevelTwoReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="600">
<action android:name="orderlyBroadcast"></action>
</intent-filter>
</receiver>
<receiver
android:name=".LevelThreeReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="300">
<action android:name="orderlyBroadcast"></action>
</intent-filter>
</receiver>
public class LevelOneReceiver extends BroadcastReceiver {
public LevelOneReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
String str = getResultData().toString();
System.out.println("LEVEL ONE:" + str);
//修改广播内容
setResultData("每人发80W");
}
}
public class LevelTwoReceiver extends BroadcastReceiver {
public LevelTwoReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
String str = getResultData().toString();
System.out.println("LEVEL TWO:" + str);
//阻止广播后,优先级低的则收不到了,但最终广播接收者一定会收到.
abortBroadcast();
}
}
public class LevelThreeReceiver extends BroadcastReceiver {
public LevelThreeReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
String str = getResultData().toString();
System.out.println("LEVEL THREE:" + str);
}
}