I am trying to display the linear acceleration of the phone inside a textview, on an Android app, using Kotlin. I tried many things, but I do not understand why the code I have doesn't work. In one activity, I have
var sensorManager : SensorManager? = null
var lastUpdatedDate : Date? = null
Then, inside the onCreate()
method I have
lastUpdatedDate = Date(System.currentTimeMillis())
sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
And my onSensorChanged()
method is as follows:
@Override
override fun onSensorChanged(event: SensorEvent?) {
when (event?.sensor?.type) {
Sensor.TYPE_LINEAR_ACCELERATION -> {
timer_since_started_detecting.text = event.values[0].toString()
}
}
}
From my understanding, onSensorChanged()
gets called (when the activity class extends SensorEventListener
) every time one of the sensors the phone has updates its value. Looking from other answers and from the documentation, I should be able to see the type of sensor that changed its value, and in my case, if it is the linear acceleration sensor, the new value should be written inside my textview.
Since there must be something I do not understand, it would be great if some of you could help me see what is wrong with the code. Thank you.
CodePudding user response:
From my understanding, onSensorChanged() gets called (when the activity class extends SensorEventListener) every time one of the sensors the phone has updates its value.
You also need to call registerListener()
on SensorManager
, supplying your listener and the sensor that you want. See: