一、首先创建xml文件界面代码如下:
<?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"
tools:context="cn.edu.bzu.test.MainActivity"
android:background="@drawable/stitch_one"
>
<Button
android:text="发送有序广播"
android:onClick="send"
android:background="#FFFFFFFF"
android:textSize="25sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="116dp"
android:id="@+id/button"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
二、在MainActivity中编写button按钮的点击事件send()
package cn.edu.bzu.test;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
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);
}
}
三、编写三个广播接收者:
package cn.edu.bzu.test;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MyBroadcastReceiverOne extends BroadcastReceiver {
public MyBroadcastReceiverOne() {
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Log.i("MyBroadcastReceiverOne","自定义的广播接受者one,接收到了广播事件");
}
}
其他两个和第一个一样将one改成two和three即可。
四、配置清单文件,代码如下:
<receiver
android:name=".MyBroadcastReceiverOne"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="Intercept_Stitch"/>
</intent-filter>
</receiver>
<receiver
android:name=".MyBroadcastReceiverTwo"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="Intercept_Stitch"/>
</intent-filter>
</receiver>
<receiver
android:name=".MyBroadcastReceiverThree"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="600">
<action android:name="Intercept_Stitch"/>
</intent-filter>
</receiver>
priority代表广播接收者的优先级,后面的数字越大,优先级越高。
运行结果如下图:
按照一二三依次显示我们输入的文字
再将广播接收者two的优先级改成1000运行结果如下图:
广播接收者two成了第一个
将广播接收者three加几行代码:
abortBroadcast()
Log.i("MyBroadcastReceiverOne","自定义的广播接受者one,接收到了广播事件");
运行结果如下图:
广播接收者就会被拦截。