android - 仅限 Android 9 (Pie):Context.startForegroundService() 没有调用 Service.startForeground() - 在 Oreo 上工作正常
问题描述
我们调整了对奥利奥的持续通知,效果很好。现在,仅在 Pie 上(不在 Oreo 设备上发生),我们得到了标题错误。我缺少的 Pie 中的前台服务有什么变化吗?
这是前台服务的 onCreate 代码 ->
override fun onCreate() {
super.onCreate()
val notification: Notification = NotificationCompat.Builder(this, packageName)
.setSmallIcon(R.drawable.status_notification_icon)
.setContentTitle(getString(R.string.ongoing_notify_temp_title))
.setContentText(getString(R.string.ongoing_notify_temp_message))
.setGroup(AppConstants.NOTIFICATION_GROUP_ONGOING)
.setColor(ContextCompat.getColor(this, R.color.custom_blue))
.build()
startForeground(ONGOING_NOTIFY_ID, notification)
appSettings = AppSettings(this)
weatherLookUpHelper = WeatherLookUpHelper()
MyRoomDatabase.getInstance().invalidationTracker.addObserver(onChange)
retrieveCurrentLocation()
createAlarmManager()
}
如您所见,我们只是创建通知,然后调用 startForeground。关于为什么此代码会生成标题错误的任何想法?
旁注:Fabric Crashlytics 显示此崩溃仅发生在运行 Pie 的像素设备(像素、像素 xl、像素 2、像素 2 xl)上
编辑:我们的清单中确实有前台权限
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
解决方案
正如这里提到的Background Service Limitations,应用程序/服务有五秒钟的调用时间startForeground()
,如果应用程序在时间限制内没有调用 startForeground() ,系统将停止服务并声明应用程序为 ANR。
有一些可能性:
- 在调用该
startForeground()
方法之前,您的前台服务会被销毁/完成。 - 或者如果前台服务已经实例化并且它被再次调用,那么该
onCreate
方法将不会被调用,而是onStartCommand
会被调用。然后将您的逻辑移动onStartCommand
到调用startForeground()
方法。 - 你的通知 id
startForeground
不能为 0,否则也会导致崩溃。
推荐阅读
- graphql - 如何过滤 GraphQL 查询?
- java - JavaFX switch case控制台,当输入选项时窗口被冻结?
- orm - 如何在棱镜中搜索 M 到 N 的关系?
- python-3.x - AWS S3 generate_presigned_url vs generate_presigned_post 用于上传文件
- java - 观察者模式:独立观察属性
- html - 手机上的日文垂直文本显示问题
- mongodb - 如何根据 mongo 文档数组中的最大日期获取记录
- javascript - 如何在Javascript中映射对象数组
- android - 是否可以在图片上叠加图标
- go - uber-go/ratelimit 算法如何工作?