Since about Android 9 it throws an IllegalStateException if startService() was called from the background. I see this exception many times in my developer console:
java.lang.IllegalStateException:
at android.app.ContextImpl.startServiceCommon (ContextImpl.java:1666)
at android.app.ContextImpl.startService (ContextImpl.java:1611)
In these cases, Google recommends to call startForegroundService() and within 5 seconds startForeground(), instead. See "Background execution limits".
Anyway, calling startService() from foreground is perfectly ok. Now, I wonder how exactly Android recognizes/decides that an app is in the foreground to not wrongly throwing an IllegalStateException?
I was starting to dig the source code of Android9/10 and comparing it with 8/7 to discover how startService() was modified to recognize if it was called from foreground/background. But I'm convinced that many developers before me did this already, and I would be happy if they'd give an answer.
from How was the source code of startService() modified to recognize if it was called from background?
No comments:
Post a Comment