如何在Jetpack Compose中检测用户处于空闲或不活动状态?

huangapple go评论58阅读模式
英文:

How to detect user is idle or inactivity in jetpack compose?

问题

Suppose I have an action to be executed after a certain amount of time without the user touching the screen. How can I implement a timer that executes an action when it times out, but starts over when the user triggers a switch?

英文:

Suppose I have an action to be executed after a certain amount of time without the user touching the screen. How can I implement a timer that executes an action when it times out, but starts over user trigger a switch

如何在Jetpack Compose中检测用户处于空闲或不活动状态?

答案1

得分: 1

使用 LaunchedEffect

LaunchedEffect(key = <您的开关状态>) {
   delay(<指定的毫秒延迟时间>)
   executeAction() // 要执行的操作
}

LaunchedEffectkey 更改时重新启动其 Lambda 表达式。因此,只有在 key 保持不变的情况下,此代码才会在指定的延迟时间后调用 executeAction()。如果用户切换开关,其状态会更改,LaunchedEffect 会重新启动,delay() 将再次被调用。

英文:

Use LaunchedEffect:

LaunchedEffect(key = &lt;your switch state&gt;) {
   delay(&lt;certain amount of time in milliseconds&gt;)
   executeAction() // action to be executed
}

LaunchedEffect restarts its lambda when key changes. So this code will call executeAction() after specified delay only if the key remains the same. If User toggles Switch, its state changes and LaunchedEffect restarts and delay() will be called again.

huangapple
  • 本文由 发表于 2023年3月7日 17:49:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75660329.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定