发送自定义广播
发送标准广播
新建一个MyBroadcastReceiver,在onReceive()方法当中编写具体逻辑
class MyBroadcastReceiver : BroadcastReceiver ( ) {
override fun onReceive ( context: Context, intent: Intent) {
Toast. makeText ( context, "received in MyBroadcastReceiver" , Toast. LENGTH_SHORT) . show ( )
}
}
当MyBroadcastReceiver接收到自定义的广播的时候,就会弹出"received in MyBroadcastReceiver"提示 然后在AndroidManifest.xml文件中对BroadcastReceiver进行修改
在这里让MyBroadcastReceiver接收一条值为"com.zb.broadcasttest.MY_BROADCAST"的广播 现在来发出一条广播 在activity_main.xml当中编写代码
<?xml version="1.0" encoding="utf-8"?>
< LinearLayout xmlns: android= " http://schemas.android.com/apk/res/android"
android: layout_width= " match_parent"
android: layout_height= " match_parent"
android: orientation= " vertical" >
< Button
android: id= " @+id/button"
android: layout_width= " match_parent"
android: layout_height= " wrap_content"
android: text= " Send BroadCast" />
</ LinearLayout>
在setPackage()方法当中需要注意的是,静态注册的BroadcastReceiver是无法接收隐式广播的,而默认情况下我们发出的自动逸广播恰恰都是隐式广播.因此我们要调用setPackage()方法
发送有序广播
和标准广播不同的是有序广播是同步执行的,并且是可以被截断的. 创建一个新的BroadcastReceiver来进行验证 新建一个AnotherBroadcastReceiver
class AnotherBroadcastReceiver : BroadcastReceiver ( ) {
override fun onReceive ( context: Context, intent: Intent) {
Toast. makeText ( context, "received in AnotherBroadcastReceiver" , Toast. LENGTH_SHORT) . show ( )
}
}
在AndroidManifest.xml中对这个BroadcastReceiver的配置进行修改
可以看到AnotherBroadcastReceiver仍然接收的是com.zb.broadcasttest.MY_BROADCAST广播,现在重新点击按钮,可以看到两次信息被弹出,但是目前发送的都是标准广播. 尝试一下发送有序广播 修改MainActivity当中的代码
只需要修改一行代码即可将发送标准广播改成发送有序广播 此时我们发送的是有序广播我们就可以设置广播的顺序了 在AndroidManifest.xml文件当中设置顺序
通过android:priority属性可以给BroadcastReceiver设置优先级,优先级比较高的BroadcastReceiver就可以先进行接收广播了. 在上述的代码中,我们设置了MyBroadcastReceiver的优先级为100,那么他肯定会在AnotherBroadcastReceiver之前接收到广播 既然AnotherBroadcastReceiver获得了接收广播的优先权,那么他就可以选择是否允许广播继续传递了 修改MyBroadcastReceiver当中的代码
在onReceive()方法当中调用abortBroadcast()方法就意味者将这条广播进行截断,后面的BroadcastReceiver将无法接收到这条广播