一篇文章学会使用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()
相关推荐
冬奇Lab11 分钟前
Android 15 显示子系统深度解析(一):显示框架总览与SurfaceFlinger核心机制
android·性能优化
MonkeyKing_sunyuhua14 分钟前
ES文档序号写错的问题的修复
java·数据库·elasticsearch
小豪GO!16 分钟前
Spring-八股
java·spring boot·spring
王干脆23 分钟前
ConcurrentHashMap禁止null键值的原因
java·开发语言
代码煮茶君27 分钟前
MySQL 数据库死锁及核心机制全解析
android·数据库·mysql
牧小七28 分钟前
Java注解(Annotation)全面学习指南
java
开开心心就好30 分钟前
PDF密码移除工具,免费解除打印编辑复制权限
java·网络·windows·websocket·pdf·电脑·excel
咕噜企业分发小米41 分钟前
豆包大模型在药物研发中的知识检索效率如何?
java·开发语言·数据库
Remember_99341 分钟前
【LeetCode精选算法】二分查找专题一
java·数据结构·算法·spring·leetcode·哈希算法
BlockChain88844 分钟前
Web3 后端面试专用版
java·面试·职场和发展·go·web3