實現感測監聽
class MainActivity : AppCompatActivity(), SensorEventListener {
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
}
override fun onSensorChanged(event: SensorEvent?) {
}
}
1.取得SensorManager
val sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
2.光感測器 實現SensorEventListener
sensorManager.registerListener(this , sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT), SensorManager.SENSOR_DELAY_NORMAL)
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
}
override fun onSensorChanged(event: SensorEvent) {
//光越亮數值越大
val lightValue = event.values[0]
}
3.距離感測器 實現SensorEventListener
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY), SensorManager.SENSOR_DELAY_NORMAL)
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
}
override fun onSensorChanged(event: SensorEvent) {
//距離越遠數值越大 目前只有0跟5
val proximityValue = event.values[0]
}
4.加速度感測器 實現SensorEventListener
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL)
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
}
override fun onSensorChanged(event: SensorEvent) {
val x = event.values[0]
val y = event.values[1]
val z = event.values[2]
}
5.計步感測器(不會馬上顯示) 實現SensorEventListener
//總步數
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER), SensorManager.SENSOR_DELAY_NORMAL)
//步數是否有效 1代表有效
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR), SensorManager.SENSOR_DELAY_NORMAL)
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
}
override fun onSensorChanged(event: SensorEvent) {
when(event.sensor.type) {
Sensor.TYPE_STEP_COUNTER -> {
val counter = event.values[0]
}
Sensor.TYPE_STEP_DETECTOR -> {
val detector = event.values[0]
}
}
}