Broadcast
Android系统提供了两种广播类型,有序广播和无序广播,开发者可根据需求为程序设置不同的广播类型。
无序广播
无序广播是完全异步执行,发送广播时所有监听这个广播的广播接收者都会接收到此消息,但接收的顺序不确定。
写一个用来发送广播的Button按钮
<Button
android:id="@+id/btn_help"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送广播"
android:textSize="20dp"
android:onClick="send"
android:layout_centerInParent="true"/>
在Activity下,写send()方法,用于发送广播
public void send(View view){
Intent intent = new Intent();
//自定义广播事件类型
intent.setAction("cn.edu.jszz.Help");
//发送广播
sendBroadcast(intent,null);
}
创建一个子类Receiver继承父类BroadcastReceiver,输出日志
public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("Receiver","自定义广播,收到广播");
Log.i("Receiver",intent.getAction());
}
}
在AndroidManifest.xml中添加意图过滤器,用于接收"cn.edu.jszz.Help"的广播
<receiver
android:name=".Receiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="cn.edu.jszz.Help"/>
</intent-filter>
</receiver>
有序广播
按照接收者的优先级接收,只有一个广播接收者能接收消息,在此广播接收者中逻辑执行完毕后,才会继续传递。
写一个用来发送广播的Button按钮
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送有序广播"
android:textSize="20dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:onClick="send"/>
在Activity下,写send()方法,用于发送广播
sendOrderedBroadcast(intent,null,myReceiverThree,null,0,null,null);要向MyReceiverThree发送广播
public void send(View view){
Intent intent = new Intent();
intent.setAction("cn.edu.jszz.STITCH");
MyReceiverThree myReceiverThree = new MyReceiverThree();
sendOrderedBroadcast(intent,null,myReceiverThree,null,0,null,null);
}
创建三个子类MyReceiver继承父类BroadcastReceiver,分别为MyReceiverOne、MyReceiverTwo、MyReceiverThree,输出日志
abortBroadcast();这个是拦截广播,不让后面日志输出。
public void onReceive(Context context, Intent intent) {
Log.d("Receiver","接收自定义广播One");
}
public void onReceive(Context context, Intent intent) {
abortBroadcast();
Log.d("Receiver","接收自定义广播Two");
}
public void onReceive(Context context, Intent intent) {
Log.d("Receiver","接收自定义广播Three");
}
在AndroidManifest.xml中添加意图过滤器,用于接收"cn.edu.jszz.STITCH"的广播
android:priority=“1000”,这是优先级,范围在-1000至1000内
如果两个广播接收者的优先级相同,则先注册的组件优先接收到广播。如果两个应用程序监听了同一个广播事件并设置了优先级,则先安装的应用的优先接收到广播
<receiver
android:name=".MyReceiverOne"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="cn.edu.jszz.STITCH"/>
</intent-filter>
</receiver>
<receiver
android:name=".MyReceiverTwo"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="800">
<action android:name="cn.edu.jszz.STITCH"/>
</intent-filter>
</receiver>
<receiver
android:name=".MyReceiverThree"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="500">
<action android:name="cn.edu.jszz.STITCH"/>
</intent-filter>
</receiver>