参数含义:
1.SensorEventListenner listener 监听传感器事件的监听器
2.,Sensor sensor, 传感器对象
3.int samplingPeriodUs 获取传感器数据的频率
(1)SensorManager.SENSOR_DELAY_GAME
(2)SensorManager.SENSOR_DELAY_FASTEST
(3)SensorManager.SENSOR_DELAY_UI
sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_GAME);
implements SensorEventListener的实现方法中重写onSensorChanged,
里面有三个值分别为x,y,z轴值:values[0],values[1],values[2]
package com.mt.sensor; import android.annotation.TargetApi; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Build; import android.os.Bundle; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity implements SensorEventListener { TextView exTxt1; SensorManager sensorManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); exTxt1= findViewById(R.id.txt1); //1.获取系统的传感器管理服务 sensorManager= (SensorManager) getSystemService(Context.SENSOR_SERVICE); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override protected void onResume() { super.onResume(); //2.为系统的加速度传感器注册监听事件 sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_GAME); } @Override protected void onPause() { super.onPause(); //取消注册 sensorManager.unregisterListener(this); } //传感器的1值发生变化回调 @Override public void onSensorChanged(SensorEvent sensorEvent) { float[] values=sensorEvent.values; String sb="x方向加速度:"+ values[0]+ "\nY轴方向加速度:"+ values[1]+ "\nZ轴方向加速度:"+ values[2]; exTxt1.setText(sb); } @Override public void onAccuracyChanged(Sensor sensor, int i) { } }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/txt1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>界面展示