Android表示没有调用startForeground,即使它是onCreate()的第一行。



我有一个服务来跟踪交付给用户的状态。

它有一个onCreate方法,像这样:

override fun onCreate() {
super.onCreate()
job = Job()
// We must always start foreground as otherwise we can get crashes
startForeground(
NOTIFICATION_ID,
createNotification(deliveryTrackerUseCase.statusData.value)
)
deliveryTrackerListener.setListeningIfNecessary(true)
wakeLock =
powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DeliveryTrackerService::lock")

combine(
deliveryTrackerUseCase.statusData,
orderUpdatesRepository.orderUpdatesEnabled
) { trackerStatus, updatesEnabled ->
if (updatesEnabled) {
notificationManager.notify(NOTIFICATION_ID, createNotification(trackerStatus))
}
}.launchIn(coroutineScope)
}

然而,我仍然看到以下崩溃在firebase崩溃分析:

Fatal Exception: android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{4f65483 u0 com.example.engine.DeliveryTrackerService}
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2389)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:219)
at android.app.ActivityThread.main(ActivityThread.java:8393)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1055)

我到底要怎么做才能阻止这个崩溃?这用于在协程范围内设置通知,但我已将其移动到onCreate函数的顶部以避免此问题,但我们仍然看到崩溃。

编辑:这似乎只在华为设备上,所以也许这与它有关。

这不是同步的,这可能是因为你的应用程序在主线程上做了太多的工作,让oncreate调用太慢了。此错误发生在调用startForegroundService 5秒(或其他秒)后。

很容易检查原因,如果这个错误100%发生,这是你的代码错误。如果发生低百分比,则与机器状态有关。

最新更新