一篇文章学会使用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()
相关推荐
0xDevNull3 分钟前
MySQL 别名(Alias)指南:从入门到避坑
java·数据库·sql
lv__pf7 分钟前
springboot原理
java·spring boot·后端
java1234_小锋8 分钟前
Java高频面试题:什么是可重入锁?
java·开发语言
云烟成雨TD43 分钟前
Spring AI Alibaba 1.x 系列【22】Agent 并行工具执行与超时 / 协作式取消实战
java·人工智能·spring
YF02111 小时前
Flutter 编译卡顿解决方案
android·flutter·ios
段小二1 小时前
服务一重启全丢了——Spring AI Alibaba Agent 三层持久化完整方案
java·后端
段小二1 小时前
Agent 自动把机票改错了,推理完全正确——这才是真正的风险
java·后端
itjinyin1 小时前
ShardingSphere-jdbc 5.5.0 + spring boot 基础配置 - 实战篇
java·spring boot·后端
丶小鱼丶2 小时前
Java虚拟机【JVM】
java·jvm
csdn2015_2 小时前
IDEA配置Continue
java·ide·intellij-idea