一篇文章学会使用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()
相关推荐
sniper_fandc2 分钟前
SpringBoot系列—MyBatis(xml使用)
java·spring boot·mybatis
胚芽鞘68130 分钟前
查询依赖冲突工具maven Helper
java·数据库·maven
Charlie__ZS35 分钟前
若依框架去掉Redis
java·redis·mybatis
hsx6661 小时前
Android 内存泄漏避坑
android
whysqwhw1 小时前
OkHttp之okhttp-bom模块的分析
android
餐桌上的王子1 小时前
Android 构建可管理生命周期的应用(二)
android
咖啡啡不加糖1 小时前
RabbitMQ 消息队列:从入门到Spring Boot实战
java·spring boot·rabbitmq
玩代码1 小时前
Java线程池原理概述
java·开发语言·线程池
NE_STOP1 小时前
SpringBoot--如何给项目添加配置属性及读取属性
java
水果里面有苹果1 小时前
20-C#构造函数--虚方法
java·前端·c#