首页 > 解决方案 > 仅限 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" />

标签: androidandroid-9.0-pie

解决方案


正如这里提到的Background Service Limitations,应用程序/服务有五秒钟的调用时间startForeground(),如果应用程序在时间限制内没有调用 startForeground() ,系统将停止服务并声明应用程序为 ANR。

有一些可能性:

  1. 在调用该 startForeground()方法之前,您的前台服务会被销毁/完成。
  2. 或者如果前台服务已经实例化并且它被再次调用,那么该onCreate方法将不会被调用,而是onStartCommand会被调用。然后将您的逻辑移动onStartCommand到调用startForeground()方法。
  3. 你的通知 idstartForeground 不能为 0,否则也会导致崩溃。

推荐阅读