Search code examples
androidandroid-serviceandroid-8.0-oreoandroid-anr-dialogforeground-service

Context.startForegroundService() ANR without actually calling it


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?


Solution

  • 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.