一篇文章学会使用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()
相关推荐
happymaker06267 小时前
Nexus私服的使用(配合Maven)
java·maven
JAVA学习通7 小时前
本地知识库接入大模型时的权限隔离与安全设计
java·人工智能·安全·spring
AbandonForce7 小时前
C++ 多态(多态定义 多态应用 多态底层||final override关键字||抽象类)
java·开发语言·c++
Bat U7 小时前
JavaEE|多线程(三)
java·前端·java-ee
卷到起飞的数分8 小时前
JVM探究
java·服务器·jvm
Geek攻城猫8 小时前
Java生产环境问题排查实战指南
java·jvm
OtIo TALL15 小时前
redis7 for windows的安装教程
java
90后的晨仔16 小时前
Android Studio 项目模板完全指南
android
summerkissyou198716 小时前
Android-SurfaceView-投屏-常见问题
android·surfaceview
uNke DEPH16 小时前
Spring Boot的项目结构
java·spring boot·后端