miral
miral

Reputation: 131

sensor TYPE_STEP_DETECTOR is not working when screen is off

in my app i use the TYPE_STEP_DETECTOR. I want to detect steps when screen is off. But the sensor TYPE_STEP_DETECTOR does not work when the screen is off. So I use PowerManager/WakeLock to make the CPU not hibernate. But it STILL not work.

Upvotes: 0

Views: 270

Answers (1)

Nguyễn Minh Khoa
Nguyễn Minh Khoa

Reputation: 125

You did't show how is your code show, but I have small code worked on my devices so I will share for you. These case worked perfect with my phone: oppo a55 a12, redmi note 7 a11, poco x3 pro a13:

Worked when app is in background,

worked when app is in foreground then screen off

Worked when app is in background then screen off If you want work when app is killed. Let's use WorkManager, or create Notification to make your app always active

at Manifest:

android.permission.ACTIVITY_RECOGNITION

android.permission.BODY_SENSORS

android.permission.BODY_SENSORS_BACKGROUND

Ask permission first

if (ContextCompat.checkSelfPermission(
                    this,
                    android.Manifest.permission.ACTIVITY_RECOGNITION
                ) == PackageManager.PERMISSION_DENIED
            ) {
                requestPermissions(
                    arrayOf(
                        android.Manifest.permission.ACTIVITY_RECOGNITION
                    ), 200
                )
            }

Then use my class for listen code from sensor service

  inner class TestStep(private val context: Context) : SensorEventListener {
    private var test = 0
    override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {
        println("sensor: ${sensor}, accuracy: ${accuracy}")
    }

    override fun onSensorChanged(event: SensorEvent) {
        if (event.sensor.type == Sensor.TYPE_STEP_DETECTOR) {
            test++
            println("test: $test")
            resultText.text = "$test step(s)"
        }
    }

    fun registerSensor() {
        val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
        val stepDetectorSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR)
        sensorManager.registerListener(
            this,
            stepDetectorSensor,
            SensorManager.SENSOR_DELAY_NORMAL
        )
    }

    fun unregisterSensor() {
        val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
        sensorManager.unregisterListener(this)
    }
}

How to use code above:

val testStep = TestStep(this)
testStep.registerSensor()

Finally, shake you phone multiple time and see log . Hope this help.

Upvotes: 0

Related Questions