Android中的广播
2021-06-28 本文已影响0人
别看后面有人
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文件
<receiver android:name=".BootComplete"
android:exported="true"
android:enabled="true">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>