2

I have a foreground monitoring class that registers as a LifecycleObserver to the ProcessLifecycleOwner's Lifecycle. When I receive an ON_START event, I am starting a Service to run while the app is in the foreground. I am seeing IllegalStateExceptions every so often on app launch stating that starting a service in the background is not allowed. Is this not a reliable way to check if the app is in the foreground? I thought ProcessLifecycleOwner was suppose to be the answer to the old, hacky way of counting activities with Application.ActivityLifecycleCallbacks. I didn't have this problem using that solution.

kyhule
  • 651
  • 2
  • 6
  • 12
  • "When I receive an ON_START event, I am starting a Service to run while the app is in the foreground" -- why? What value is a service giving you, as opposed to some ordinary Java/Kotlin object? After all, you are in the foreground, so the service is not helping to keep your process around. – CommonsWare Mar 20 '19 at 14:29
  • @CommonsWare That is a valid point. That part of it is really old, legacy code that can and probably should be refactored but I was not ready to take that effort on. Even taking the service out of the equation, I think my question is still valid. Why does the system think the application is running in the background when we are in the foreground but after rereading the docs again, it is more of a "your app is coming to the foreground" event vs "your app is in the foreground" event. – kyhule Mar 20 '19 at 18:49
  • One possibility, I suppose, is that the app went back to the background before your `startService()` call took effect. Or, perhaps there is a scenario where you `finish()` your activity rapidly, before the `startService()` call took effect. There is obviously some correlation between activity lifecycle events and the not-in-foreground error, but since we're talking about different processes, I don't think those things are tightly coupled. – CommonsWare Mar 20 '19 at 21:33
  • I have the same issue (see here https://stackoverflow.com/questions/55318949/app-seems-to-be-in-background-when-activity-onstart-is-called). I noticed that the crash seems to appear when locking and then unlocking the phone while in the app. It seem like a bug to me, honestly. I'll try to move starting the service to the onResume method to see if this helps. – Jeyhey Mar 23 '19 at 23:24

0 Answers0