Android Context.startForegroundService()ANR,而不实际调用它
在将我的应用程序更新为目标API 27(以前是25)后,我遇到了许多来自用户的ANR,我无法重现。它们似乎与Oreo后台执行限制有关,带有ANR消息Android Context.startForegroundService()ANR,而不实际调用它,android,android-service,android-8.0-oreo,android-anr-dialog,foreground-service,Android,Android Service,Android 8.0 Oreo,Android Anr Dialog,Foreground Service,在将我的应用程序更新为目标API 27(以前是25)后,我遇到了许多来自用户的ANR,我无法重现。它们似乎与Oreo后台执行限制有关,带有ANR消息 Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{73bc351 u0 com.xxx.xxxx/.player.PlayFileService} 但是,我不会在代码中的任何地方调用Context.startFor
Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{73bc351 u0 com.xxx.xxxx/.player.PlayFileService}
但是,我不会在代码中的任何地方调用
Context.startForegroundService()
。生成此ANR的原因有哪些不是直接调用此方法的结果?根据文档:
在Android 8.0之前,创建前台服务的常用方法是
创建后台服务,然后将该服务升级到
前景Android 8.0存在一个复杂问题;系统
不允许后台应用程序创建后台服务。对于
因此,安卓8.0引入了这种新方法
startForegroundService()
在前台启动新服务
系统创建服务后,应用程序有五秒钟的时间
调用服务的startForeground()方法以显示新服务的
用户可见的通知如果应用程序未调用startForeground()
在时间限制内,系统停止服务并声明
应用程序将成为ANR
您可以按照下面描述的方法使用通知频道正确启动前台服务。在我的例子中,即使我没有直接调用
Context.startForegroundService()
,调用它是因为我的音乐应用程序将进入后台,服务将被系统破坏。然后,当用户在几分钟后按下媒体按钮恢复播放时,系统会重新启动服务,因为应用程序在后台。我确实最终调用了startForeground()
,但这是在一系列配置之后完成的。我在我的服务的onCreate()
开头添加了一个对startForeground()
的调用,通知为空,我所有的ANR都消失了。我是用老方法做的。我只在应用程序位于前台时调用startService(),在活动进入后台并在通道中发出通知时调用startForeground()。我在我的应用程序中没有地方调用新的startForegroundService()。@SteveM当你的应用程序在后台时,你不能用context.startService()启动服务。您需要使用startForegroundService()
I不在后台启动应用程序服务()。若我这样做了,我会得到非法状态异常。@史蒂文,我只是想澄清一下,当应用程序在前台时,你们正在启动服务,当应用程序进入后台时,你们只需将其置于前台即可?是的,我在暂停时调用startforeground