举例说明:
创建一个监听电池状态的广播接收器
class NetworkChangeReceiver : BroadcastReceiver() {
private var listener: ((Boolean) -> Unit)? = null
fun register(context: Context, callback: (Boolean) -> Unit) {
listener = callback
val intentFilter = IntentFilter()
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
context.registerReceiver(this, intentFilter)
}
fun unregister(context: Context) {
try {
context.unregisterReceiver(this)
} catch (e: Exception) {
e.printStackTrace()
}
listener = null
}
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == ConnectivityManager.CONNECTIVITY_ACTION) {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
val isConnected = activeNetwork?.isConnectedOrConnecting ?: false
listener?.invoke(isConnected)
}
}
}
使用:
//定义全局变量
val batteryChangeReceiver by lazy {
BatteryChangeReceiver()
}
//在onCreate()中注册
batteryChangeReceiver.register(content) {
//接受到广播后的处理
}
//在onDestroy()中注销
batteryChangeReceiver.unregister(content)