The third parameter above is the sampling rate Fastest: SensorManager.SENSOR_DELAY_FASTEST Game: SensorManager.SENSOR_DELAY_GAME Normal: SensorManager.SENSOR_DELAY_NORMAL User interface: SensorManager.SENSOR_DELAY_UI
Example of obtaining acceleration sensor data:
//MainActivity.java
package aaa.android.com.myapplication123;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private MySensorEventListener sensorEventListener = new MySensorEventListener();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text_view);
//获取管理器
SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
//获取加速度感应器
Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
private final class MySensorEventListener implements SensorEventListener {
//传感器实时变化值
@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
String result = "X= " + x + "\n"
+ "Y= " + y + "\n"
+ "Z= " + z;
textView.setText(result);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
}
//activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="30dp"
tools:context="aaa.android.com.myapplication123.MainActivity">
<!--定义一个textview用来显示结果-->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="test"
android:textSize="30sp"
android:id="@+id/text_view"/>
</LinearLayout>
Orientation sensor: Sensor.TYPE_ORIENTATION
Acceleration sensor: Sensor.TYPE_ACCELEROMETER
Light sensor: Sensor.TYPE_LIGHT
Magnetic field sensor: Sensor.TYPE_MAGNETIC_FIELD
Distance sensor: Sensor.TYPE_PROXIMITY
Temperature sensor : Sensor.TYPE_TEMPERATURE
//Get a certain type of sensor
Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//Register listening
sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME);
The third parameter above is the sampling rate
Fastest: SensorManager.SENSOR_DELAY_FASTEST
Game: SensorManager.SENSOR_DELAY_GAME
Normal: SensorManager.SENSOR_DELAY_NORMAL
User interface: SensorManager.SENSOR_DELAY_UI
Example of obtaining acceleration sensor data: