androidkotlinserviceandroid-8.0-oreo

service crash with "Context.startForegroundService() did not then call Service.startForeground()"


Hello friends. I use this code inside the service for the pedometer service and I will encounter the following error. Thank you for your help.

*error android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground() at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2220) at android.os.Handler.dispatchMessage(Handler.java:109) at android.os.Looper.loop(Looper.java:166) at android.app.ActivityThread.main(ActivityThread.java:7555) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)

class MyService : Service(), SensorEventListener {
private var sensorManager: SensorManager? = null
private var running = false
private var totalStep = 0f
private var previousTotalStep = 0f

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    try {
        running = true
        val stepSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
        sensorManager?.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_UI)
    } catch (e: Exception) {

    }
    return START_STICKY

}

override fun onBind(p0: Intent?): IBinder? {
    return null
}

override fun onSensorChanged(event: SensorEvent?) {
    if (running) {
        totalStep = event!!.values[0]
        val currentSteps = totalStep.toInt() - previousTotalStep.toInt()
        Constant.editor(this).putFloat(STEPNUMBER, previousTotalStep).apply()
    }
}

override fun onAccuracyChanged(p0: Sensor?, p1: Int) {

}

override fun stopService(name: Intent?): Boolean {
    return super.stopService(name)
}

override fun onDestroy() {
    val intent = Intent(this, MyPhoneReciver::class.java)
    sendBroadcast(intent)
    super.onDestroy()
}

}


Solution

  • Android O you can set the background limitation as below;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context!!.startForegroundService(Intent(context, MyService::class.java))
        } else {
            context!!.startService(Intent(context, MyService::class.java))
        }