0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Androidでスマホの方向や角度(傾き)を取得する

0
Posted at

Androidでスマホの向きや傾き角度を取得する方法メモします。今回はスマホの向きや角度を取得するので、TYPE_ROTATION_VECTOR を利用します。精度は搭載しているスマホのセンサーの品質に依存します。

サンプルコード

class MainActivity : AppCompatActivity(), SensorEventListener {

    private lateinit var sensorManager: SensorManager
    private var rotationSensor: Sensor? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        sensorManager = requireContext().getSystemService(Context.SENSOR_SERVICE) as SensorManager
        rotationSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)
    }

    override fun onResume() {
        super.onResume()

        rotationSensor?.let {
            sensorManager.registerListener(this, it, SensorManager.SENSOR_DELAY_UI)
        }
    }

    override fun onPause() {
        super.onPause()
        sensorManager.unregisterListener(this)
    }

    override fun onSensorChanged(event: SensorEvent) {

        if (event.sensor.type != Sensor.TYPE_ROTATION_VECTOR) {
            return
        }

        val rotationMatrix = FloatArray(9)

        SensorManager.getRotationMatrixFromVector(
            rotationMatrix,
            event.values
        )

        val orientation = FloatArray(3)

        SensorManager.getOrientation(
            rotationMatrix,
            orientation
        )

        val azimuth = Math.toDegrees(orientation[0].toDouble()).toFloat()

        val pitch = Math.toDegrees(orientation[1].toDouble()).toFloat()

        val roll = Math.toDegrees(orientation[2].toDouble()).toFloat()

        Log.d("方向", "azimuth=$azimuth")
        Log.d("ピッチ", "pitch=$pitch")
        Log.d("ロール", "roll=$roll")
    }

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

取得できる値

SensorManager.getOrientation() は3つの値が取得できます。

Azimuth(方位)

スマホを向けている方角です。

Pitch(前後の傾き)

スマホを前後に傾けた角度です。

Roll(左右の傾き)

スマホを左右に傾けた角度です。

一部の端末ではジャイロセンサーや特定のセンサーが搭載されていない場合があります。使用前に getDefaultSensor() の返り値が nullになっているかどうかで判断できます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?