Android 9 (Pie) 只有 : Context. startForegroundService() 然后没有调用 Service.startForeground() - 在 Oreo 上工作正常

标签 android android-9.0-pie

我们调整了针对奥利奥的持续通知,效果很好。现在,仅在 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 的 Pixel 设备(pixel、pixel xl、pixel 2、pixel 2 xl)上

编辑我们的 list 中确实有前台权限

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

最佳答案

如此处所述Background Service Limitations ,应用程序/服务有五秒时间调用startForeground(),如果应用程序没有在时间限制内调用startForeground(),系统停止服务并声明应用程序为ANR。

有一些可能性:

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

关于Android 9 (Pie) 只有 : Context. startForegroundService() 然后没有调用 Service.startForeground() - 在 Oreo 上工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53014866/

相关文章:

android - 为什么屏幕上的位置总是返回 0?

android - 确定是否存在生物识别硬件以及用户是否已在 Android P 上注册生物识别

android - 使用 google play 游戏服务在用户之间共享数据?

java - 部分解密废话

android - 获取屏幕曲线、角和切口的物理形状

API 28 (P) 的 Android 设计支持库不起作用

android - 由 : android. database.sqlite.SQLiteException 引起:没有这样的表:BOOK(代码 1 SQLITE_ERROR)

安卓 P : `NotificationManager.cancel` does not work if user has replied to notification

java - 是否可以打包一个泛型类?

Android - 按钮的边框