Search code examples
androidkotlinandroid-sensorssensormanager

Displaying multiple sensors readings on screen


I am trying to display multiple sensor readings on screen (accelerometer, magnetometer, etc.) in its own line of text. I can change the text onscreen for one type of sensor (accelerometer), but not another sensor.

I registered both sensors as Listeners, but don't know how to update each one separately inside the onSensorChanged function.

package com.example.sensorlistener_kotlin

import android.annotation.SuppressLint
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), SensorEventListener {

    lateinit var sensorManager: SensorManager

    override fun onAccuracyChanged(p0: Sensor?, p1: Int) {
    }

    @SuppressLint("SetTextI18n")
    override fun onSensorChanged(event: SensorEvent?) {

        label_accelerometerX.text = "X = ${event!!.values[0]}"
        label_accelerometerY.text = "Y = ${event.values[1]}"
        label_accelerometerZ.text = "Z = ${event.values[2]}"

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager

        sensorManager.registerListener(
            this,
            sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
            SensorManager.SENSOR_DELAY_NORMAL
        )

/*        sensorManager.registerListener(
            this,
            sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
            SensorManager.SENSOR_DELAY_NORMAL
        )*/

    }
}

As the end result, I want to display X,Y,Z components of accelerometer, magnetometer, and gyroscope on screen in their own line as follows:


AccelerometerX

AccelerometerY

AccelerometerZ

MagnetometerX

MagnetometerY

MagnetometerZ

GyroX

GyroY

GyroZ



Solution

  • You need to check of each sensorevent on your onsensorchanged:

    if (sensorEvent.sensor.type == Sensor.TYPE_ACCELEROMETER) {
                        label_accelerometerX.text = sensorEvent.values[0] 
                       ...
    }
    
    if (sensorEvent.sensor.type == Sensor.TYPE_MAGNETOMETER) {
      ...
    }
    
    if (sensorEvent.sensor.type == Sensor.TYPE_GYROSCOPE) {
      ...
    }