Android 四大组件 之一 BroadcastReceiver
Android 四大组件 之一 BroadcastReceiver
在现代化Android开发当中广播一般只接收系统广播不做他用,不要滥用,不要使用LocalBroadcastManager。
在现代化Android开发当中如何使用BroadcastReceiver呢?
定义
/**
* 只能使用于接收系统广播,不建议瞎jb使用广播和类似的EventBus这种框架
*/
internal fun Context.broadcastAsFlow(vararg actions: String): Flow<Intent> = callbackFlow<Intent> {
val receiver = object : BroadcastReceiver(){
override fun onReceive(context: Context?, intent: Intent?) {
if (intent != null){
val result: ChannelResult<Unit> = this@callbackFlow.trySendBlocking(element = intent)
Log.i(TAG, "onReceive -> result: $result")
}
}
}
val filter: IntentFilter = IntentFilter().apply {
actions.forEach { action ->
addAction(action)
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
} else {
registerReceiver(receiver, filter)
}
awaitClose {
Log.i(TAG, "broadcastAsFlow awaitClose ...")
unregisterReceiver(receiver)
}
}.buffer(capacity = Channel.UNLIMITED)
使用
方式1
coroutineScope.launch {
context.broadcastAsFlow(Intent.ACTION_SCREEN_OFF, Intent.ACTION_SCREEN_ON)
.collect { intent: Intent ->
Log.i(TAG, "StoreScreen -> 屏幕关闭开启 intent: $intent")
}
}
方式二
val intents: Intent by context.broadcastAsFlow(Intent.ACTION_SCREEN_OFF, Intent.ACTION_SCREEN_ON).collectAsStateWithLifecycle(initialValue = Intent())

Android 四大组件 之一 BroadcastReceiver
浙公网安备 33010602011771号