Reputation: 9794
After updating my app to target API 27 (previously 25) I'm encountering many ANR's from users, which I can't reproduce. They seem related to the Oreo background execution limits, with the ANR message
Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{73bc351 u0 com.xxx.xxxx/.player.PlayFileService}
However I do not call Context.startForegroundService()
anywhere in my code. What are some reasons this ANR could be generated that are not a result of a direct call to this method?
Upvotes: 2
Views: 3234
Reputation: 9794
In my case, even though I didn't call Context.startForegroundService()
directly, it was being called because my music app would go into the background and the service would be destroyed by the system. Then, when the user pressed a media button to resume playback after a couple minutes, the service would get restarted by the system, with that call since the app was in the background. I did call startForeground()
eventually but it was after a bunch of configuration. I added a call to startForeground()
at the beginning of onCreate()
of my service with a blank notification and all my ANR's have disappeared.
Upvotes: 3
Reputation: 24947
Based on the documentation:
Prior to Android 8.0, the usual way to create a foreground service was to create a background service, then promote that service to the foreground. With Android 8.0, there is a complication; the system doesn't allow a background app to create a background service. For this reason, Android 8.0 introduces the new method
startForegroundService()
to start a new service in the foreground.After the system has created the service, the app has five seconds to call the service's startForeground() method to show the new service's user-visible notification. If the app does not call startForeground() within the time limit, the system stops the service and declares the app to be ANR
You can follow this SO which describes the approach to properly start the foreground service with Notification Channel.
Upvotes: 2