如何在Kotlin中使用注册并在Android中创建广播接收器。任何建议.... 在Java中,您可以通过将其声明为广播接收器来创建它。但是在Kotlin中没有广播接收器功能......如果它在那里,那么我无法找到它或如何使用它。
答案 0 :(得分:42)
you can do it in the following way
Create a broadcast receiver object in your activity class
val broadCastReceiver = object : BroadcastReceiver() {
override fun onReceive(contxt: Context?, intent: Intent?) {
when (intent?.action) {
BROADCAST_DEFAULT_ALBUM_CHANGED -> handleAlbumChanged()
BROADCAST_CHANGE_TYPE_CHANGED -> handleChangeTypeChanged()
}
}
}
Register broadcast receiver in onCreate() function of your activity
LocalBroadcastManager.getInstance(this)
.registerReceiver(broadCastReceiver, IntentFilter(BROADCAST_DEFAULT_ALBUM_CHANGED))
unregister it in ondestroy function of your activity
LocalBroadcastManager.getInstance(this)
.unregisterReceiver(broadCastReceiver)
答案 1 :(得分:5)
Kotlin中的匿名类语法是这样的:
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
}
}
答案 2 :(得分:4)
我创建了一个BroadcastReceiver Kotlin extension,您可以在任何地方复制/粘贴。 它没有比已经提到的更多,但它减少了一些样板。
使用此扩展程序,您应该注册/取消注册,如下所示:
{{1}}