汽车网站flash模板,oa系统网站建设方案,采购软件,小白如何做网站大部分隐式广播无法通过静态注册接收#xff0c;除了以下白名单广播#xff1a;
ACTION_BOOT_COMPLETED
ACTION_TIMEZONE_CHANGED
ACTION_LOCALE_CHANGED
ACTION_MY_PACKAGE_REPLACED
ACTION_PACKAGE_ADDED
ACTION_PACKAGE_REMOVED
需要以动态注册方案替换#xff1a;
cl…大部分隐式广播无法通过静态注册接收除了以下白名单广播
ACTION_BOOT_COMPLETED
ACTION_TIMEZONE_CHANGED
ACTION_LOCALE_CHANGED
ACTION_MY_PACKAGE_REPLACED
ACTION_PACKAGE_ADDED
ACTION_PACKAGE_REMOVED
需要以动态注册方案替换
class MainActivity : AppCompatActivity() {private val receiver object : BroadcastReceiver() {override fun onReceive(context: Context, intent: Intent) {// 处理广播}}override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)// 使用动态注册替代静态注册registerReceiver(receiver, IntentFilter().apply {addAction(your.custom.action)})}
}
后台应用发送广播受到限制
// 后台应用发送广播限制
// 解决方案
// 1. 使用前台服务
startForegroundService(intent)// 2. 使用 LocalBroadcastManager
LocalBroadcastManager.getInstance(this).sendBroadcast(intent)// 3. 使用显式广播
Intent(this, MyReceiver::class.java).also { intent -sendBroadcast(intent)
}
性能优化建议
// 使用有序广播替代多个广播
sendOrderedBroadcast(intent, null)// 使用粘性广播替代定时轮询
sendStickyBroadcast(intent)// 使用 EventBus 等替代方案
implementation org.greenrobot:eventbus:3.2.0
LocalBroadcastManager 的实现原理
// LocalBroadcastManager 核心实现原理
class LocalBroadcastManager private constructor(private val context: Context) {// 1. 使用 Handler 处理消息private val handler Handler(Looper.getMainLooper())// 2. 广播接收器的注册表private val receivers HashMapString, ArrayListReceiverRecord()// 3. 待处理的广播队列private val pendingBroadcasts ArrayListBroadcastRecord()// 4. 注册广播接收器fun registerReceiver(receiver: BroadcastReceiver, filter: IntentFilter) {synchronized(receivers) {// 记录接收器和过滤器val record ReceiverRecord(filter, receiver)filter.actionsIterator().forEach { action -// 按 action 分类存储接收器receivers.getOrPut(action) { ArrayList() }.add(record)}}}// 5. 发送广播fun sendBroadcast(intent: Intent) {synchronized(receivers) {// 查找匹配的接收器val matchingReceivers ArrayListReceiverRecord()// 根据 action 找到对应的接收器receivers[intent.action]?.forEach { record -if (record.filter.match(intent)) {matchingReceivers.add(record)}}if (matchingReceivers.isEmpty()) return// 将广播加入队列synchronized(pendingBroadcasts) {pendingBroadcasts.add(BroadcastRecord(intent, matchingReceivers))// 通过 Handler 发送消息handler.post {executePendingBroadcasts()}}}}// 6. 执行广播private fun executePendingBroadcasts() {while (true) {val broadcast synchronized(pendingBroadcasts) {if (pendingBroadcasts.isEmpty()) nullelse pendingBroadcasts.removeAt(0)} ?: break// 在主线程分发广播broadcast.receivers.forEach { receiver -receiver.receiver.onReceive(context, broadcast.intent)}}}
}
核心原理
单例模式管理Handler 消息机制同步队列处理主线程分发内存级别通信
实现特点
不经过 AMS 无进程间通信效率更高安全性好同步执行
优化设计
避免广播风暴减少内存占用 保证顺序执行 线程安全控制生命周期管理