一篇文章学会使用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()
相关推荐
tobias.b2 分钟前
计算机基础知识-数据结构
java·数据结构·考研
reembarkation17 分钟前
光标在a-select,鼠标已经移出,下拉框跟随页面滚动
java·数据库·sql
愣头不青31 分钟前
617.合并二叉树
java·算法
麦麦鸡腿堡2 小时前
JavaWeb_请求参数,设置响应数据,分层解耦
java·开发语言·前端
mygljx3 小时前
MySQL 数据库连接池爆满问题排查与解决
android·数据库·mysql
没有bug.的程序员3 小时前
Serverless 弹性扩容引发的全线熔断:Spring Boot 启动耗时从 1s 压缩至 0.3s 的物理级绞杀
java·spring boot·kubernetes·serverless·扩容·线上
bearpping3 小时前
java进阶知识点
java·开发语言
独自破碎E3 小时前
【面试真题拆解】你知道ThreadLocal是什么吗
java·jvm·面试
kkkkatoq3 小时前
JAVA中的IO操作
java·开发语言
深蓝轨迹4 小时前
@Autowired与@Resource:Spring依赖注入注解核心差异剖析
java·python·spring·注解