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

April 28, 2022, at 01:10 AM

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 Context.startForegroundService() did not then call Service.startForeground() at$H.handleMessage( at android.os.Handler.dispatchMessage( at android.os.Looper.loop( at at java.lang.reflect.Method.invoke(Native Method) at$ at

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,


Answer 1

Android O you can set the background limitation as below;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    } else {
Answer 2

The reason for this crash is :

-> From Android 9 Pie if your service does not call startForeground within 5 seconds after it has been started with the command startForegroundService ... then it produces an ANR + Crash.

Solution : After starting the service with startForegroundService, call startForeground() in the service’s onCreate method.

Rent Charter Buses Company
Dowload Media in Download directory in android app

Dowload Media in Download directory in android app

Am trying to download media file from server to android default Downloads directory,but on storing the media in downloads i got exception javaio

Fixing header (navbar) in webview flutter

Fixing header (navbar) in webview flutter

I am currently working on a project where I need to convert a website to a mobile app using flutter I did it with the widget WEBVIEW but the header of the webview in my mobile is not fixed when i scroll the page the header (navBar) of my website scroll...

Transparent or Invisible

Transparent or Invisible

I'm trying to use an ImageView without any backgroundI know that I can use