Android 检索传感器事件
示例
从板载传感器中检索传感器信息:
public class MainActivity extends Activity implements SensorEventListener { private SensorManager mSensorManager; private Sensor accelerometer; private Sensor gyroscope; float[] accelerometerData = new float[3]; float[] gyroscopeData = new float[3]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); gyroscope = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); } @Override public void onResume() { //注册您感兴趣的传感器的侦听器 mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_FASTEST); mSensorManager.registerListener(this, gyroscope, SensorManager.SENSOR_DELAY_FASTEST); super.onResume(); } @Override protected void onPause() { //取消注册任何先前注册的侦听器 mSensorManager.unregisterListener(this); super.onPause(); } @Override public void onSensorChanged(SensorEvent event) { //检查要轮询的传感器数据的类型,并将其存储到相应的浮点数组中 if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { accelerometerData = event.values; } else if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE) { gyroscopeData = event.values; } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { //TODO自动生成的方法存根 } }