【BroadcastReceiver】
class MainActivity : AppCompatActivity() {
lateinit var timeChangeReceiver: TimeChangeReceiver
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//首先,创建了一个IntentFilter的实例,并给它添加了一个值为android.intent.action.TIME_TICK的action
val intentFilter = IntentFilter()
intentFilter.addAction("android.intent.action.TIME_TICK")
timeChangeReceiver = TimeChangeReceiver()
registerReceiver(timeChangeReceiver, intentFilter)
}
override fun onDestroy() { super.onDestroy()
unregisterReceiver(timeChangeReceiver)
}
//内部类TimeChangeReceiver:继承BroadcastReceiver,并重写了父类的onReceive()
inner class TimeChangeReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Toast.makeText(context, "Time has changed", Toast.LENGTH_SHORT).show()
}
}
}
当系统时间发生变化时,系统发出的正是一条值为android.intent.action.TIME_TICK的广播。也就是说,我们的BroadcastReceiver想要监听什么广播,就添加相应的action.
最后要记得,动态注册的BroadcastReceiver一定要取消注册才行!比如,我们可以在
onDestroy()
方法中通过调用unregisterReceiver()
方法来实现的。