一篇文章学会使用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()
相关推荐
一灯架构40 分钟前
90%的人答错!一文带你彻底搞懂ArrayList
java·后端
Y4090012 小时前
【多线程】线程安全(1)
java·开发语言·jvm
布局呆星2 小时前
SpringBoot 基础入门
java·spring boot·spring
风吹迎面入袖凉3 小时前
【Redis】Redisson的可重入锁原理
java·redis
w6100104663 小时前
cka-2026-ConfigMap
java·linux·cka·configmap
冬奇Lab3 小时前
MediaPlayer 播放器架构:NuPlayer 的 Source/Decoder/Renderer 三驾马车
android·音视频开发·源码阅读
语戚3 小时前
力扣 968. 监控二叉树 —— 贪心 & 树形 DP 双解法递归 + 非递归全解(Java 实现)
java·算法·leetcode·贪心算法·动态规划·力扣·
quxuexi4 小时前
网络通信安全与可靠传输:从加密到认证,从状态码到可靠传输
java·安全·web
hrhcode4 小时前
【java工程师快速上手go】二.Go进阶特性
java·golang·go