Android传感器使用


public class SensorTest extends Activity implements SensorEventListener { SensorManager sensorManager = null; //for accelerometer values TextView outputX; TextView outputY; TextView outputZ; //for orientation values TextView outputX2; TextView outputY2; TextView outputZ2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //初始化sensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); setContentView(R.layout.main); //just some textviews, for data output outputX = (TextView) findViewById(R.id.TextView01); outputY = (TextView) findViewById(R.id.TextView02); outputZ = (TextView) findViewById(R.id.TextView03); outputX2 = (TextView) findViewById(R.id.TextView04); outputY2 = (TextView) findViewById(R.id.TextView05); outputZ2 = (TextView) findViewById(R.id.TextView06); } //在onResume中注册监听 @Override protected void onResume() { super.onResume(); sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), sensorManager.SENSOR_DELAY_GAME); sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), sensorManager.SENSOR_DELAY_GAME); } //在onStop中注销监听 @Override protected void onStop() { super.onStop(); sensorManager.unregisterListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)); sensorManager.unregisterListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION)); } //当传感器状态发生改变时 public void onSensorChanged(SensorEvent event) { synchronized (this) { switch (event.sensor.getType()){ case Sensor.TYPE_ACCELEROMETER: outputX.setText("x:"+Float.toString(event.values[0])); outputY.setText("y:"+Float.toString(event.values[1])); outputZ.setText("z:"+Float.toString(event.values[2])); break; case Sensor.TYPE_ORIENTATION: outputX2.setText("x:"+Float.toString(event.values[0])); outputY2.setText("y:"+Float.toString(event.values[1])); outputZ2.setText("z:"+Float.toString(event.values[2])); break; } } } //更精确的改变 @Override public void onAccuracyChanged(Sensor sensor, int accuracy) {} }

To sum things up, to access sensor data you have to do the following things:
1. Check sensor availability.
2. Register a listener to a sensorManager.
3. Catch the needed data , from onSensorChanged.
4. Unregister the sensorManager's listener.

另:其他参考资料

1, http://www.ibm.com/developerworks/opensource/library/os-android-sensor/index.html?ca=dgr-lnxw09Android-Sensors&S_TACT=105AGX59&S_CMP=grlnxw09

posted @ 2011-06-14 17:59  OYK  阅读(857)  评论(0编辑  收藏  举报