James Riordan
James Riordan

Reputation: 1172

Android says startForeground isn't being called even though it's the first line of onCreate()

I have a service that tracks the state of a delivery to the user.

It has an onCreate method like this:

    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)
    }

However I'm still seeing the following crash in firebase crashlytics:

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)

What on earth do I have to do to stop this crashing? This used to set the notification inside the coroutine scope, but I've moved it to be at the top of the onCreate function to avoid this issue, but we're still seeing crashes.

EDIT: this only seems to be on Huawei devices, so perhaps that's something to do with it.

Upvotes: 2

Views: 216

Answers (1)

Silence
Silence

Reputation: 126

it's not sync,it may be because your app do too much work on main thread,and let the oncreat call too slow. this error happen after call startForegroundService 5s(or other seconds).

it's easy to check the reason,if this error happen 100%,it's your code error. if it's happen low percent,it's about machine state.

Upvotes: 2

Related Questions