如何在 Kotlin / Android 中获取更新的可验证值

问题描述 投票:0回答:0

我有一个应用程序,我必须在其中显示设备的当前电池电量以及设备是否正在充电?

这是我的代码:-

电池信息模型

data class BatteryInfo(
val batterLevel:Float,
val isCharging:Boolean )

电池信息模块

class BatteryInfoModule (private val context: Context) {


   var batteryInfo  by mutableStateOf<BatteryInfo?>(null)


   fun registerReceiver(){

      context.registerReceiver(BatteryReceiver(), IntentFilter(Intent.ACTION_BATTERY_CHANGED))
   }

   fun unRegisterReceiver(){
       context.unregisterReceiver(BatteryReceiver())
    }

}

我的di(匕首柄)

@Provides
@Singleton
fun provideBatteryInfoModule(context: Context) = BatteryInfoModule(context)

我的广播接收器

  class BatteryReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent?.action == Intent.ACTION_BATTERY_CHANGED) {
            val status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
            val isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                    status == BatteryManager.BATTERY_STATUS_FULL
            val chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
//            val usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB
//            val acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC
            val batteryPct = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)
            val module = BatteryInfoModule(context!!)
            module.batteryInfo = BatteryInfo(batterLevel =  batteryPct.toFloat() , isCharging = isCharging)
        }
    }
}

我的视图模型

@HiltViewModel
class HomeScreenViewModel @Inject constructor(
    private val batteryInfoModule: BatteryInfoModule,
) : ViewModel() {

private val _uiEvents = Channel<UIEvents>()
val uiEvents = _uiEvents.receiveAsFlow()


var batteryInfo by mutableStateOf<BatteryInfo?>(null)

init {
    viewModelScope.launch {

        batteryInfoModule.registerReceiver()
        batteryInfo = batteryInfoModule.batteryInfo

    }
}

override fun onCleared() {
    super.onCleared()
    batteryInfoModule.unRegisterReceiver()
}
}

所以每当广播获得更新的电池值时,它应该被发送到 BatteryInfoModule 并且更新的值应该被接收到 viewModel 而我没有得到那个数据它总是空的而且我不知道如何解决这个问题。

注意:-

我试过像普通的可验证的和像 mutablestateflow 和观察者一样但它没有解决问题请让我知道我的错误并告诉我如何解决这个问题。

谢谢

android kotlin android-jetpack-compose broadcastreceiver viewmodel
© www.soinside.com 2019 - 2024. All rights reserved.