一篇文章学会使用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()
相关推荐
jgbazsh19 分钟前
Redis6.2.6下载和安装
java
于先生吖22 分钟前
JAVA 本地生活服务项目实战 家政 5.0 系统前后端分离部署
java·开发语言·生活
左左右右左右摇晃29 分钟前
Java并发——锁的状态演变
java·开发语言·笔记
Roselind_Yi31 分钟前
排查Visual C++堆损坏(HEAP CORRUPTION)错误:从报错到解决的完整复盘
java·开发语言·c++·spring·bug·学习方法·远程工作
bing_15836 分钟前
spring Boot 3.0 和2.0的区别
java·spring boot·后端
Thomas.Sir37 分钟前
Shiro认证与授权:Java安全框架的核心机制
java·安全·shiro·权限控制
wuqingshun3141591 小时前
谈一下Daemon线程
java·开发语言
启山智软1 小时前
【对比了几家电商商城系统】
java·开源
大尚来也1 小时前
Java 线程池深度解析:ThreadPoolExecutor 七大参数与核心原理
java·python·算法
Mike_6661 小时前
百度云车牌调用识别-Java工程
java·百度云·车牌识别·在线调用