一篇文章学会使用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()
相关推荐
Lyyaoo.5 分钟前
【JAVA网络面经】应用层协议
java·开发语言·网络
2501_937145416 分钟前
TV 影视大全:多品类聚合 稳定播放优化版
android·源码·源代码管理
無限進步D10 分钟前
Java 面向对象高级 继承
java·开发语言
云烟成雨TD12 分钟前
Spring AI Alibaba 1.x 系列【37】ReactAgent 构建、执行流程分析
java·人工智能·spring
是宇写的啊21 分钟前
MyBaties
java·开发语言·mybatis
followYouself24 分钟前
Gradle、AGP、Plugin插件基本知识
android·gradle·plugin·agp
钝挫力PROGRAMER24 分钟前
程序中事件机制的实现
java·后端·python·软件工程
程序员威哥28 分钟前
Java调用YOLO模型性能优化实战:CPU/GPU加速与内存优化全指南
java·人工智能·后端
Xpower 1734 分钟前
OpenClaw Token 优化的技术方案与实践:OpenSpace 自进化 Skill 引擎
java·开发语言·人工智能
杨凯凡34 分钟前
【022】JVM 运行时数据区与对象创建
java·jvm·后端