服务崩溃,并显示“Context.startForegroundService() 没有调用 Service.startForeground()”

问题描述 投票:0回答:3

朋友们大家好。我在计步器服务的服务中使用此代码,我将 遇到以下错误。谢谢您的帮助。

*错误 android.app.RemoteServiceException:Context.startForegroundService() 然后没有调用 Service.startForeground() 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:2220) 在 android.os.Handler.dispatchMessage(Handler.java:109) 在 android.os.Looper.loop(Looper.java:166) 在 android.app.ActivityThread.main(ActivityThread.java:7555) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469) 在 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()
}

}

android kotlin service android-8.0-oreo
3个回答
5
投票

这次崩溃的原因是:

-> 从 Android 9 Pie 开始,如果您的服务在使用命令 startForegroundService 启动后 5 秒内没有调用 startForeground ...那么它会产生 ANR + 崩溃。

解决方案:使用startForegroundService启动服务后,在服务的onCreate方法中调用startForeground()。


0
投票

Android O 您可以如下设置后台限制;

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

0
投票

这个bug太烦人了。就我而言,问题是我启动了服务并在操作系统向用户显示通知之前立即停止了它。通过避免立即停止服务,您可以解决此问题。另外,您可以通过重写服务的 onDestroy 方法来检查这一点。

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