一篇文章学会使用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()
相关推荐
JJay.10 小时前
Android BLE 稳定连接的关键,不是扫描,而是 GATT 操作队列
android·服务器·前端
一 乐10 小时前
电影院|基于springboot + vue电影院购票管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·电影院购票管理管理系统
恼书:-(空寄10 小时前
JVM GC 日志分析 + 常见 GC 场景 + 实战参数调优
java·jvm
消失的旧时光-194310 小时前
Spring Boot 实战(五):接口工程化升级(统一返回 + 异常处理 + 错误码体系 + 异常流转机制)
java·spring boot·后端·解耦
忒可君10 小时前
C# winform 自制分页功能
android·开发语言·c#
summerkissyou198710 小时前
Android-线程安全-volatile
android·线程
杨凯凡11 小时前
【012】图与最短路径:了解即可
java·数据结构
比特森林探险记11 小时前
【无标题】
java·前端
椰猫子12 小时前
Javaweb(Filter、Listener、AJAX、JSON)
java·开发语言
朝新_12 小时前
【Spring AI 】核心知识体系梳理:从入门到实战
java·人工智能·spring