一篇文章学会使用Broadcast

Broadcast ------传消息和事件的工具

1.注册一个广播

创建一个继承 BroadcastReceiver的类,重写onReceive()

Kotlin 复制代码
class PlayMusicReceiver(private val callback:(Boolean)->Unit):BroadcastReceiver() {

    override fun onReceive(context: Context?, intent: Intent?) {
     val isPlay = intent!!.getBooleanExtra("EXTRA",true)
     callback(isPlay)
    }
}

Service中获取刚创建的 BroadcastReceiver和传入了与之前Intent内部action相同的IntentFilter,进行判断可以注册后,调用registerReceiver()注册Broadcast

Kotlin 复制代码
fun createReceiver(){
      
        val intentFilter = IntentFilter("com.example.zj_action")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
            registerReceiver(mReceiver,intentFilter,Context.RECEIVER_EXPORTED)
        }else{
            registerReceiver(mReceiver,intentFilter)
        }
    }

2.发送广播

自带sendBroacast(),传入一个Intent(action)即可 ,悄悄说,action是自己取名字当标识符

Intent.putExtra()可以传递额外值给目标

Kotlin 复制代码
 fun playBroadcast(){
        val intent = Intent("com.example.zj_action")
        intent.putExtra("EXTRA",true)
        sendBroadcast(intent)
    }

3.接收广播

Receiver类中通过高阶函数callback回调了Blooean值,再传递给PlayMusicReceiver的实例化类中

Kotlin 复制代码
 mReceiver = PlayMusicReceiver{
            if (it){
                playMusic("音频的url地址")
            }else{
             player.stop()
            }
        }
      createReceiver()
相关推荐
白鸽(二般)1 天前
MinIO Java Client API
java·开发语言
软萌萌的11 天前
Java Spring Boot 修改yml配置&加载顺序规则
java·spring boot·python
IT小盘1 天前
13-企业Prompt模板-角色任务约束与输出格式
java·前端·prompt
爱敲键盘的猴子1 天前
Java并发编程 -- volatile
java·java并发
plainGeekDev1 天前
工厂模式 → Hilt
android·java·kotlin
雨白1 天前
深入理解 Kotlin 协程 (十):引而不发,探秘 Flow 冷流机制与异常透明性
android·kotlin
plainGeekDev1 天前
Application 单例 → Hilt Singleton
android·java·kotlin
888CC++1 天前
C语言与C++的区别:从面向过程到面向对象
java·c语言·c++
学者猫头鹰1 天前
分布式事务实战教程
java·分布式
程序员码歌1 天前
我全程用 AI开发了一款微信小游戏,上线了
android·前端·游戏开发