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

问题描述 投票:9回答:2

我们调整了我们对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" />
android android-9.0-pie
2个回答
4
投票

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

有一些可能性:

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

1
投票

Pie中的前台服务有什么变化我错过了吗?

是看看这里migration notes of Android 9 / Pie

更改

前台服务许可

摘要

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

UPDATE

Google Issue Tracker Context.startForegroundService() did not then call Service.startForeground中的相关问题

© www.soinside.com 2019 - 2024. All rights reserved.