sidon
sidon

Reputation: 1482

Invalid Android accelerometer sensor values, X and Y axes are switched on Samsung

I'm trying to get orientation change info when displaying portrait only activity. Using android.view.OrientationEventListener works flawlessly on most devices. However on some devices the reported angle is shifted by 90 degrees.

I already checked the device natural orientation because the doc for OrientationEventListener says

...orientation is 0 degrees when the device is oriented in its natural position...

I'm checking the natural orientation with following code:

private fun getLandscapeDefault(): Boolean? {
  return getDisplay()?.let { display ->
    val orientation = context.resources.configuration.orientation
    if (orientation == Configuration.ORIENTATION_UNDEFINED) return@let null
    when (display.rotation) {
      Surface.ROTATION_180, Surface.ROTATION_0 -> orientation == Configuration.ORIENTATION_LANDSCAPE
      else -> orientation == Configuration.ORIENTATION_PORTRAIT
    }
  }
}

All the devices report that they have natural orientation portrait (all are phones).

To debug the issue I tried to use accelerometer sensor data directly (that is what OrientationEventListener is doing internally).

This is the code logging raw data from accelerometer:

sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
sensorEventListener = object : SensorEventListener {
    override fun onSensorChanged(event: SensorEvent?) {
        val values = event?.values ?: return
        Log.v(TAG, "onSensorChanged: ${values.joinToString(", ")}")
    }
    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
    }
}
sensorManager.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL)

It logs accelerometer values for x, y, and z axes. When holding the phone upwards in front of my face, the x axis value is ~ -9 and y and z are ~ 0. But on that particular device (it doesn't work on) it is y axis which has the -9 value and x is 0. That explains why is orientation reported with a 90 degree rotation shift.

This is happening on Samsung Galaxy S20+, Android 10.

I'm quite surprised that googling doesn't show any relevant results as if no one else is having the same problem as I do...

Upvotes: 0

Views: 290

Answers (0)

Related Questions