Android中的广播

时间:2021-7-21 作者:qvyue

Android中的广播分为两种:标准广播和有序广播,标准广播是一种完全异步的广播,在广播发出之后,所有的BroadCastReceiver几乎在同一时间收到这条广播信息,因此他们没有先后顺序之分,这种广播的效率比较高,但是也无法被截断,有序广播是一种同步的广播,在广播发送之后,同一时刻只有一个BroadcastReceiver能收到广播消息,而且是有先后顺序的,优先级高的先执行,并且可以截断正在传递的广播
1、动态注册监听时间变化:定义一个TimeChangeReceiver,这个类继承自BroadcastReceiver的,并且重写父类onReceive()方法,这样当系统时间发声变化时就会得到执行。具体代码如下:

class BroadcastActivity:AppCompatActivity() {

    lateinit var timeChangeReceiver:TimeChangeReceiver
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.broadcast_activity)

        val initentFilter=IntentFilter()
        initentFilter.addAction("android.intent.action.TIME_TICK")
        timeChangeReceiver=TimeChangeReceiver()
        registerReceiver(timeChangeReceiver,initentFilter)

    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(timeChangeReceiver)
    }

    inner class TimeChangeReceiver:BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            Log.d("TAG", "onReceive: changed")
            Toast.makeText(context,"time changed",Toast.LENGTH_LONG).show()
        }

    }

}

打印结果:
06-28 05:06:00.534 17933-17933/com.app.activitytest D/TAG: onReceive: changed
06-28 05:07:00.534 17933-17933/com.app.activitytest D/TAG: onReceive: changed
06-28 05:08:00.534 17933-17933/com.app.activitytest D/TAG: onReceive: changed
06-28 05:09:00.534 17933-17933/com.app.activitytest D/TAG: onReceive: changed
06-28 05:10:00.534 17933-17933/com.app.activitytest D/TAG: onReceive: changed
06-28 05:11:00.534 17933-17933/com.app.activitytest D/TAG: onReceive: changed

2、静态注册实现开机启动

class BootComplete :BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
       
        Log.d("TAG", "onReceive: finish")
    }
}

manifest文件

 
声明:本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:qvyue@qq.com 进行举报,并提供相关证据,工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。