DEV Community


Discussion on: Android Vitals - Why did my process start? 🌄

androiddeveloperlb profile image

I have a question about this:
Sometime in the past, Google added a weird new function to start a foreground service ("startForegroundService") , but it seems it should work only if it's not in the foreground, while the previous one should work fine when it's in the foreground ("startService").

I was told that if I want to always choose the correct one, no matter where I start the service, I can just check whether it's in the foreground or not:

val appProcessInfo = ActivityManager.RunningAppProcessInfo()
(appProcessInfo.importance == IMPORTANCE_FOREGROUND || appProcessInfo.importance == IMPORTANCE_VISIBLE)

This worked in almost all cases, but from time to time, I got crash reports (via Crashlytics) showing that it failed:
"IllegalStateException: Not allowed to start service is in background"

How could it be?
For now, I tried using try-catch in this case, and use the other function when this occurs. I hope this will help.

pyricau profile image
Py ⚔ Author • Edited

I'm not sure, but I do know we've stuck to only IMPORTANCE_FOREGROUND and didn't include IMPORTANCE_VISIBLE when starting a normal service.

This could also be an unfortunate race condition, ie right after you check the importance that importance changes... and yes there'd likely be nothing to do about it.

androiddeveloperlb profile image

I can't find where I got this code. I'm sure it was from Google though, somewhere in the issue tracker.
Why did Google even make this new function?