一篇文章学会使用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()
相关推荐
Makoto_Kimur22 分钟前
Java 打印模板大全
java·开发语言·排序算法
程序员榴莲25 分钟前
Java(十)super关键字
java·开发语言
HAPPY酷31 分钟前
Python高级架构师之路——从原理到实战
java·python·算法
ybwycx1 小时前
SpringBoot下获取resources目录下文件的常用方法
java·spring boot·后端
PrDf22Iw81 小时前
CPU ↔ DRAM(内存总线)的可持续数据传输带宽
java·运维·网络
代码改善世界1 小时前
【matlab初阶】matlab入门知识
android·java·matlab
java1234_小锋1 小时前
Java高频面试题:如何编写一个MyBatis插件?
java·开发语言·mybatis
卓怡学长1 小时前
m315基于java的水果网上商城的开发与设计
java·数据库·spring·tomcat·maven·intellij-idea
执笔画流年呀2 小时前
7大排序算法
java·算法·排序算法
zdl6862 小时前
springboot+全局异常处理
java·spring boot·spring