Hinge angle sensor API
The hinge angle is a value from 0 to 360:
- 0 - device is closed (screens are facing each other, and not visible)
- 90 - device is an "L" shape, also known as the laptop posture or book posture depending on orientation
- 180 - device is flat
- 360 - device is folded so that the screens are facing away from each other and only one screen is operating
Tip
This code sample is written for the hinge angle sensor on the Surface Duo.
The Jetpack Window Manager has a DeviceState
API that provides information about posture (eg. closed, open, half-open) that works on devices from multiple manufacturers.
The hinge angle can be measured using Android's sensor manager configured with the Hinge Angle
sensor name.
private val HINGE_ANGLE_SENSOR_NAME = "Hinge Angle"
private var mSensorManager: SensorManager? = null
private var mHingeAngleSensor: Sensor? = null
private var mSensorListener: SensorEventListener? = null
// call setupSensors from onCreate
private fun setupSensors() {
mSensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
val sensorList: List<Sensor> = mSensorManager!!.getSensorList(Sensor.TYPE_ALL)
for (sensor in sensorList) {
if (sensor.getName().contains(HINGE_ANGLE_SENSOR_NAME)) {
mHingeAngleSensor = sensor
}
}
mSensorListener = object : SensorEventListener {
override fun onSensorChanged(event: SensorEvent) {
if (event.sensor == mHingeAngleSensor) {
val angle = event.values[0].toInt()
//TODO something with angle
}
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
//TODO (if required)
}
}
}
override fun onPause() {
super.onPause()
if (mHingeAngleSensor != null) {
mSensorManager?.unregisterListener(mSensorListener, mHingeAngleSensor)
}
}
override fun onResume() {
super.onResume()
if (mHingeAngleSensor != null) {
mSensorManager?.registerListener(
mSensorListener,
mHingeAngleSensor,
SensorManager.SENSOR_DELAY_NORMAL
)
}
}