1.编写用户交互界面:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@drawable/stitch_one"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp"
android:onClick="send"
android:text="发送有序广播"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:background="#FBFBFF"
android:textSize="20sp"
/>
</RelativeLayout>
2.创建意图:
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");
//发送广播
sendBroadcast(intent,null);
}
}
3.创建广播接受者:
(1)public class MyBroadcastReceiverOne extends BroadcastReceiver {
public MyBroadcastReceiverOne() {
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i("MyBroadcastReceiverOne","自定义的广播接受者One,接受到了广播事件");
}
}
(2)public class MyBroadcastReceiverTwo extends BroadcastReceiver {
public MyBroadcastReceiverTwo() {
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i("MyBroadcastReceiverTwo","自定义的广播接受者Two,接受到了广播事件");
abortBroadcast();//拦截有序广播
Log.i("MyBroadcastReceiverTwo","我是广播接收者Two,广播被我终结了");
}
}
(3)public class MyBroadcastReceiverThree extends BroadcastReceiver {
public MyBroadcastReceiverThree() {
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i("MyBroadcastReceiverThree","自定义的广播接收者Three,接受到了广播事件");
}
}
4.创建过滤器:<receiver
android:name=".MyBroadcastReceiverOne">
<intent-filter android:priority="1000">
<action android:name="Intercept_Stitch"/>
</intent-filter>
</receiver>
<receiver
android:name=".MyBroadcastReceiverTwo">
<intent-filter android:priority="200">
<action android:name="Intercept_Stitch"/>
</intent-filter>
</receiver>
<receiver android:name=".MyBroadcastReceiverThree">
<intent-filter android:priority="600">
<action android:name="Intercept_Stitch"/>
</intent-filter></receiver>
数值越大,优先级越高,先被接受。我们希望是对发出的自定义的广播感兴趣,所以<intent-filter>的
<action>的name应该与构建的意图的setAction的name是一样的。这样,发出广播之后就会在清单文件的
意图过滤器中找<action>的名字和意图的action的名字一样的。观察Log输出是否是正确顺序。
5.运行项目:所得结果如图:
(1) 若将广播接受者MyBroadcastReceiverTwo优先级同样设置为1000,并将
MyBroadcastReceiverTwo注册在MyBroadcastReceiverOne前面,再运行程序,
所得结果是:
(2) 再修改MyBroadcastReceiverTwo如下图:
运行程序,所得结果是:
6.所需图片资源如下: