一篇文章学会使用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()
相关推荐
qq_27049009613 分钟前
SpringBoot药品管理系统设计实现
java·spring boot·后端
、BeYourself42 分钟前
SpringAI-ChatClient Fluent API 详解
java·后端·springai
星辰_mya1 小时前
reids哨兵集群与选主
java·开发语言
BD_Marathon1 小时前
SpringBoot快速入门
java·spring boot·后端
期待のcode1 小时前
Java的多态
java·开发语言
xq95271 小时前
带你玩转kakao登录 接入教程
android
2501_946233891 小时前
Flutter与OpenHarmony应用设置页面完整开发
android·flutter
证能量少女2 小时前
2026大专Java开发工程师,考什么证加分?
java·开发语言
FPGAI2 小时前
Java学习之基础概念
java·学习
芒克芒克2 小时前
Java集合框架总结(面试八股)
java·开发语言·面试