传感器事件侦听器在后台服务中不起作用

时间:2019-03-07 13:28:11

标签: android kotlin event-listener background-service firebase-job-dispatcher

我创建了一个计步器服务,以使用Firebase作业分配器定期记录计步数。当我的应用程序运行并记录步数时,传感器事件正在运行,而当应用程序关闭时,它未记录。

如何在后台服务中侦听传感器事件?

class MyJobService : JobService(), SensorEventListener {

        val TAG = "MyJobService"

        var sensorManager: SensorManager? = null
        var stepsSensor: Sensor? = null

        override fun onStartJob(job: JobParameters): Boolean {

            sensorManager = applicationContext.getSystemService(Context.SENSOR_SERVICE) as SensorManager

            stepsSensor = sensorManager!!.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
            if (stepsSensor != null) {
                sensorManager!!.registerListener(this, stepsSensor, SensorManager.SENSOR_DELAY_FASTEST)
            } else {
                Log.e(TAG, "sensor not available")
            }

            return true // wait for sensor event
        }

        override fun onAccuracyChanged(theSensor: Sensor?, accuracy: Int) {

        }

        override fun onSensorChanged(event: SensorEvent?) {

            val latestSensorCount = event!!.values[0].toLong()
            Log.e(TAG, "Steps count $latestSensorCount") // works when App / activity is running

        }

        override fun onStopJob(job: JobParameters): Boolean {
            return false
        }

    }

从主要活动中通过活动开始服务

 val dispatcher = FirebaseJobDispatcher(GooglePlayDriver(this))
 val myJob = dispatcher.newJobBuilder()
            .setService(MyJobService::class.java)
            .setTag("my-jobservice-tag")
            .setRecurring(true)
            .setTrigger(Trigger.executionWindow(10,20))
            .setReplaceCurrent(true)
            .build()

 dispatcher.mustSchedule(myJob)

1 个答案:

答案 0 :(得分:0)

如果您正在使用Android Pie在Android设备上进行测试

请通过Android Pie进行以下行为更改:

  

使用连续报告模式的传感器(例如加速度计和陀螺仪)不会接收事件。

Android Pie Changes

希望这对您有帮助