https://kotlinlang.org logo
#android
Title
# android
c

Colton Idle

12/07/2023, 7:49 PM
I've got an android app that's essentially running on a kiosk and I need it to perform some action every ~4 hours (does not have to be exact) when the app is in the foreground. I know work manager exists, but this work isn't in the background at all. It's just for when the app is in the foreground. I suppose launching a coroutine with a loop with
delay(4.HOURS)
wouldn't be too terrible, right?
x

xoangon

12/07/2023, 9:20 PM
I'd say it depends on whether that action needs to be performed even if the Activity goes to the STOPPED state. Here is how I think: • If the action needs to be performed anyway, I'd use WorkManager • If the action is strictly bound to some Activity, you could use a
CoroutineScope
bound to the Activity lifecycle • If the action is bound to the app process, you could start a coroutine in the
GlobalScope
6
f

flosch

12/08/2023, 6:08 PM
Consider using
ProcessLifecycleOwner.get().lifecycleScope
c

Colton Idle

12/08/2023, 8:05 PM
@xoangon so coroutineScope bound to activity makes sense. But in that case I would just have to do a delay(4.hours), right?
x

xoangon

12/08/2023, 8:14 PM
Yup. I don't anticipate any problems for doing that. And as you're suspending and not blocking, you could even run that coroutine in the
Main
dispatcher without worrying about blocking it
👍 2
2 Views