private val TAG = MainActivity::class.java.simpleName } private val temperatureSensorDriver: Bmx280SensorDriver by lazy { Bmx280SensorDriver("I2C1") } private val sensorManager: SensorManager by lazy { getSystemService(Context.SENSOR_SERVICE) as SensorManager } private val dynamicSensorCallback = object : DynamicSensorCallback() { override fun onDynamicSensorConnected(sensor: Sensor) { if (sensor.type == Sensor.TYPE_AMBIENT_TEMPERATURE) { Log.i(TAG, "Temperature sensor connected") sensorManager.registerListener(this@MainActivity, sensor, SensorManager.SENSOR_DELAY_NORMAL) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) sensorManager.registerDynamicSensorCallback(dynamicSensorCallback) temperatureSensorDriver.registerTemperatureSensor() } override fun onDestroy() { super.onDestroy() sensorManager.unregisterDynamicSensorCallback(dynamicSensorCallback) sensorManager.unregisterListener(this) temperatureSensorDriver.run { unregisterTemperatureSensor() close() } } override fun onSensorChanged(event: SensorEvent) { // event.values[0] } override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) { Log.i(TAG, "sensor accuracy changed: $accuracy") } }