仅限Android 9(Pie):Context.startForegroundService()没有调用Service



我们调整了正在进行的奥利奥通知,效果很好。现在,在Pie上(奥利奥设备上没有(,我们得到了标题错误。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设备(像素、像素xl、像素2、像素2 xl(上

编辑:我们在清单中确实有前台权限

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

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

有一些可能性:

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

Pie的前台服务有什么变化吗?

看看这里的Android 9/Pie 迁移说明

更改

前台服务许可

摘要

想要使用前台服务的应用程序现在必须首先请求foreground_SERVICE权限。这是一个正常的权限,因此系统会自动将其授予请求应用程序。在没有权限的情况下启动前台服务会引发SecurityException。

更新

Google issue Tracker上下文中的相关问题。startForegroundService((没有调用Service.startForeground

  1. 我恢复到startService((,而不是使用startForeground((解决了我的问题

ONCREATE中实现以下代码后,我停止了获取错误

Intent intent1 = new Intent(this, YourActivity.class);
try {
startService(intent1);
}catch ( Exception e1){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
this.startForegroundService(intent1);
}else {
Crashlytics.log("crash for first time, trying another.");
this.startService(intent1);
}
}

对我来说,这听起来很奇怪,但我工作得很好,没有崩溃。

最新更新