Accelerometer

MainActivity

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 android.widget.TextView

class MainActivity : AppCompatActivity() {
lateinit var sManager: SensorManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val tvSensor = findViewById<TextView>(R.id.tvSensor)

sManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
val sensor = sManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
val sListener = object : SensorEventListener{
override fun onSensorChanged(sEvent: SensorEvent?) {
val value = sEvent?.values
val sData = "X: ${value?.get(0)}\nY: ${value?.get(1)}\nZ: ${value?.get(2)}"
tvSensor.text = sData
}

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

}

}
sManager.registerListener(sListener, sensor, SensorManager.SENSOR_DELAY_NORMAL)
}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/tvSensor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textColor="@color/black"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *