【发布时间】:2018-03-04 15:59:32
【问题描述】:
【问题讨论】:
标签: android
【问题讨论】:
标签: android
在 Android O 中,我们有一个新的背景限制。当你尝试 startService() 时,你会得到 IllegalStateException,所以现在你应该使用 startForegroundService(),但是如果你用这个新方法启动服务,你会得到像你的截图一样的错误。为避免此异常,您有 5 秒的时间在 startForegroundService() 之后执行 startForeground(),以通知用户您正在后台工作。
那么,Android O 中只有一种方式:
context.startForegroundService(intent)
在服务 onCreate() 中做这样的事情:
startForeground(1, new Notification());
更新 所以我认为,一些制造商在 Android N 上向后移植了这些新的背景限制,这就是为什么你可以在 Android N 中获得相同的例外。
【讨论】:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(intent); } else { context.startService(intent); }
MainActivity 的onCreate 启动服务。并在Service 的onCreate 和onStartCommand 中调用startForeground。应用程序在调用onCreate 时应始终处于前台状态。但我仍然收到此错误。