英文:
How can I update the value I draw with Jetpack Compose?
问题
我正在尝试创建一个Android应用程序,用于获取并显示电池百分比,但我无法使其更新。
我尝试使用updateBatteryPct
函数,但由于它有延迟(否则会崩溃),它被注册为挂起,不能在onCreate
中使用,因为使onCreate
挂起会导致它不再是覆盖。
这是我多次尝试更新此值的其中一种方法,我甚至不确定updateBatteryPct
是否会起作用。如果有人能够深入解释一下这是如何工作的,我会很感激,因为我真的不太了解。我能够使用Kotlin编码并做一些事情,但我无法做出适用于Android的任何东西。
英文:
I am trying to do an android app that gets and displays the battery percentage, but I can't get it to update.
I tried using the function updateBatteryPct
but because it has a delay (else it crashes) it is registered as suspend it cannot be used in onCreate
because making onCreate
suspend causes it to not be an override anymore.
This is one of my many tries to update this value, I am not even sure that updateBatteryPct
will even work. I would appreciate if someone could explain me in depth how this works bc I dont understad really everything. I can code in Kotlin and do stuff but I can't do anything that works for android.
class MainActivity : ComponentActivity() {
var batteryStatus: Intent? = null
var batteryPct: MutableState<Int> = mutableStateOf(0)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(/* savedInstanceState = */ savedInstanceState)
setContent {
this.batteryStatus = getBatteryStatusReceiver()
this.batteryPct = remember {
mutableStateOf(0)
}
BatterySaverAppTheme {
// A surface container using the 'background' color from the theme
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background) {
getBatteryPct(this.batteryStatus, this.batteryPct)
DisplayBatteryPercentage(batteryPercentage = this.batteryPct)
}
}
}
}
suspend fun updateBatteryPct () {
while (true) {
getBatteryPct(this.batteryStatus, this.batteryPct)
delay(1000)
Log.d("customTest", "updateBatteryPct: Looping")
}
}
}
class BatteryManagerBroadcastReceiver(
private val onReceiveIntent: (Intent) -> Unit,
) : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
onReceiveIntent(intent)
}
}
@Composable
fun updateBatteryPct(batteryStatus: Intent?, batteryPct: MutableState<Int>) {
while (true) {
getBatteryPct(batteryStatus, batteryPct)
DisplayBatteryPercentage(batteryPercentage = batteryPct)
}
}
fun getBatteryPct(batteryStatus: Intent?, batteryPct: MutableState<Int>){
batteryPct.value = batteryStatus?.let { intent ->
val level: Int = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale: Int = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
level * 100 / scale
}!!
}
@Composable
fun getBatteryStatusReceiver(): Intent? {
val batteryStatus: Intent? = IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { ifilter ->
LocalContext.current.applicationContext.registerReceiver(null, ifilter)
}
return batteryStatus
}
@Composable
fun DisplayBatteryPercentage(batteryPercentage: MutableState<Int>) {
Column(Modifier.padding(16.dp)) {
Text("battery is at ${batteryPercentage.value}%") }
}
答案1
得分: 2
更好的方法是使用带有副作用的BroadcastReceiver
进行注册。
类似这样的:
@Composable
fun SystemBroadcastReceiver(
systemAction: String,
onSystemEvent: (intent: Intent?) -> Unit
) {
// 在 UI 树的这一部分获取当前的上下文
val context = LocalContext.current
// 安全地使用传递给函数的最新 onSystemEvent lambda
val currentOnSystemEvent by rememberUpdatedState(onSystemEvent)
// 如果上下文或者 systemAction 发生变化,注销并重新注册
DisposableEffect(context, systemAction) {
val intentFilter = IntentFilter(systemAction)
val broadcast = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
currentOnSystemEvent(intent)
}
}
context.registerReceiver(broadcast, intentFilter)
// 当效果离开 Composition 时,移除回调
onDispose {
context.unregisterReceiver(broadcast)
}
}
}
然后在你的 composable 中只需更新该值:
var battery by remember { mutableStateOf(0) }
SystemBroadcastReceiver(Intent.ACTION_BATTERY_CHANGED) { batteryStatus ->
val batteryPct: Float? = batteryStatus?.let { intent ->
val level: Int = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale: Int = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
level * 100 / scale.toFloat()
}
battery = batteryPct!!.toInt()
}
英文:
It is better to register the BroadcastReceiver
with a side effect.
Something like:
@Composable
fun SystemBroadcastReceiver(
systemAction: String,
onSystemEvent: (intent: Intent?) -> Unit
) {
// Grab the current context in this part of the UI tree
val context = LocalContext.current
// Safely use the latest onSystemEvent lambda passed to the function
val currentOnSystemEvent by rememberUpdatedState(onSystemEvent)
// If either context or systemAction changes, unregister and register again
DisposableEffect(context, systemAction) {
val intentFilter = IntentFilter(systemAction)
val broadcast = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
currentOnSystemEvent(intent)
}
}
context.registerReceiver(broadcast, intentFilter)
// When the effect leaves the Composition, remove the callback
onDispose {
context.unregisterReceiver(broadcast)
}
}
}
Then in your composable just update the value:
var battery by remember { mutableStateOf(0) }
SystemBroadcastReceiver(Intent.ACTION_BATTERY_CHANGED) { batteryStatus ->
val batteryPct: Float? = batteryStatus?.let { intent ->
val level: Int = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale: Int = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
level * 100 / scale.toFloat()
}
battery = batteryPct!!.toInt()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论