一篇文章学会使用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()
相关推荐
Sirens.5 分钟前
Java核心概念:抽象类、接口、Object类深度剖析
java·开发语言·github
Meteors.5 分钟前
23种设计模式——中介者模式 (Mediator Pattern)详解
java·设计模式·中介者模式
望获linux7 分钟前
【实时Linux实战系列】使用 u-trace 或 a-trace 进行用户态应用剖析
java·linux·前端·网络·数据库·elasticsearch·操作系统
焰火199914 分钟前
[Java]基于Spring的轻量级定时任务动态管理框架
java·后端
Seven9722 分钟前
Springboot 常见面试题汇总
java·spring boot
程序员阿鹏32 分钟前
49.字母异位词分组
java·开发语言·leetcode
云中隐龙41 分钟前
mac使用本地jdk启动elasticsearch解决elasticsearch启动时jdk损坏问题
java·elasticsearch·macos
CodeLongBear42 分钟前
苍穹外卖 Day12 实战总结:Apache POI 实现 Excel 报表导出全流程解析
java·excel
爱学习 爱分享1 小时前
mac idea 点击打开项目卡死
java·macos·intellij-idea
漠北七号1 小时前
有加密机,电脑贼卡顿怎么办
java