基础介绍
我们可以把广播的相关问题分为3个部分分别为:
注册,发送,接收(可以这样理解广播发送出去,注册了此action的·广播会回调 onReceiver() 方法)。
注册
静态注册
<receiver
android:name=".Brocade_Receive"
android:exported="true">
<intent-filter android:priority="100">
<action android:name="动态注册"/>
</intent-filter>
</receiver>
BroadcastReceiver 在Manifest中写为 receiver
android:name 实现 BroadcastReceiver 类的类名
android:exported 设置是否接收其他APP相同的action广播;
false 表示不接受其他APP的广播;
true 表示接受其他APP的广播
intent-filter 过滤器,定义receiver被外部唤醒的属性
android:priority 优先级,同为静态注册的监听者,当 action 有众多接收者时,此数值越大,监听者收到action越早(广播接收者注册的方式相同)
action 我们监听的 Action,可以在我们的 OnReceiver() 中回调
动态注册
代码内注册:
val intentFilter=IntentFilter().apply {
addAction("动态注册")
}
registerReceiver(Brocade_Receive(),intentFilter)
实现与静态注册相同的功能
发送
广播分为全局广播和本地广播:
全局广播:可以跨进程接受广播
本地广播:当前APP内部可以接受
广播发送方式分为有序,无序(标准广播)
有序广播:广播接收者排队接受
无序广播:同时接受到广播
全局广播:
sendBroadcast(intent),发出的都是全局广播
本地广播:
val intentFilter=IntentFilter().apply {
addAction("动态注册")
}
LocalBroadcastManager.getInstance(this).apply {
registerReceiver(Brocade_Receive(),intentFilter)
sendBroadcast(intent)
}
注意:发送本地广播时,注册也要用本地广播注册
有序广播:
sendOrderedBroadcast(intent,null)
无序广播:
sendBroadcast(intent)
接收
我们注册完成后,重写OnReceiver() 即可
相关问题
如何让未运行但已设置接收者的APP作出反应?
val intent=Intent("动态注册")
intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
sendBroadcast(intent)
在Intent中加上Flag即可
动态注册与静态注册的相关问题
- 动态注册的优先级高于静态注册对于同一个Action
- 本地广播可以提高效率以及安全性
- 前台10s,后台60s 无反应就会产生ANR