1.布局文件
activity_main.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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/stitch_one"
tools:context=".MainActivity">
<Button
android:text="发送有序广播"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="send"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:background="#FBFBFF"
android:textSize="20sp"
/>
</RelativeLayout>
2.在布局文件中定义了一个Button按钮,并为按钮注册一个点击事件send,当点击这个按钮时,会发送一条有序广播。
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);
}
}
3.创建三个广播接收者
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* Created by Administrator on 2017/6/1.
*/
public class MyBroadcastReceiverOne extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("MyBroadcastReceiverOne"," One接收到广播");
}
}
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* Created by Administrator on 2017/6/1.
*/
public class MyBroadcastReceiverTwo extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Log.i("MyBroadcastReceiverTwo"," Two接收到广播");
}
}
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* Created by Administrator on 2017/6/1.
*/
public class MyBroadcastReceiverThree extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("MyBroadcastReceiverThree"," Three接收到广播");
}
}
运行效果如图:
注意广播接收者需要在清单文件中配置,由于priority的值不同,执行顺序不同,代码如下
<receiver
android:name=".MyReceiverOne"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="Intercept_Stitch" />
</intent-filter>
</receiver>
<receiver
android:name=".MyReceiverTwo"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="500">
<action android:name="Intercept_Stitch" />
</intent-filter>
</receiver>
<receiver
android:name=".MyReceiverThree"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="300">
<action android:name="Intercept_Stitch" />
</intent-filter>
</receiver>