在Android系统中,根据广播的执行顺序不同,可将其分为有序广播和无序广播。
无序广播:当无序广播发送一条广播消息时,所有的广播接收器都可以接收到,不会被拦截。
有序广播:有序广播是一种同步执行的广播,在广播发出之后,同一时刻只会有一个广播接收器能够接收到这条消息,当这个广播接收器中的逻辑执行完毕后,广播才会继续传播,所以这时的广播接收器是有先后顺序的,并可以被拦截。
布局非常简单,就是一个背景图片加上一个按钮而已,重点是主函数以及广播BroadcastReceiver,
在主函数中需要添加一个send类,用来发布有序广播
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void send(View view){
Intent intent=new Intent();
intent.setAction("Intercept_Stitch");
sendOrderedBroadcast(intent,null);
Toast.makeText(this,"发送成功",Toast.LENGTH_SHORT).show();
}
}
另外,我创建了三个广播类
用来区分不同的优先级收到的顺序不同
public class MyBroadcastReceiverOne extends BroadcastReceiver {
public MyBroadcastReceiverOne() {
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i("MyBroadcastReceiverOne","自定义的广播接收者One,接受到了广播事件");
}
}
public class MyBroadcastReceiverTwo extends BroadcastReceiver {
public MyBroadcastReceiverTwo() {
}
public void onReceive(Context context, Intent intent) {
Log.i("MyBroadcastReceiverTwo","自定义的广播接收者Two,接受到了广播事件");
}
}
public class MyBroadcastReceiverThree extends BroadcastReceiver {
public MyBroadcastReceiverThree() {
}
public void onReceive(Context context, Intent intent) {
Log.i("MyBroadcastReceiverThre","自定义的广播接收者Thre,接受到了广播事件");
}
}
在AndoidManifest.xml中
规定三个广播类的优先级不同
<receiver
android:name=".MyBroadcastReceiverOne"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="Intercept_Swtitch" />
intent-filter>
receiver>
<receiver
android:name=".MyBroadcastReceiverTwo"
android:enabled="true"
android:exported="true" >
<intent-filter android:priority="200">
<action android:name="Intercept_Swtitch" />
intent-filter>
receiver>
<receiver
android:name=".MyBroadcastReceiverThree"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="600">
<action android:name="Intercept_Swtitch" />
intent-filter>
receiver>
问题1::若将广播接收者MyBroadcastReceiverTwo优先级同样设置为1000,并将MyBroadcastReceiverTwo注册在MyBroadcastReceiverOne前面,再来运行程序,观察结果为:
问题二:修改MyBroadcastReceiverTwo为:
public class MyBroadcastReceiverTwo extends BroadcastReceiver {
public MyBroadcastReceiverTwo() {
}
public void onReceive(Context context, Intent intent) {
Log.i("MyBroadcastReceiverTwo","自定义的广播接收者Two,接收到了广播事件");
abortBroadcast();
Log.i("MyBroadcastReceiverTwo","我是广播接收者Two,广播被我终结了");
}
}