有没有办法在Android中检索多个传感器数据

时间:2010-12-03 07:25:35

标签: android orientation accelerometer sensor

我正在尝试获取加速度计和方向数据。目前,我创建了一个AccelerometerManager和OrientationManager。他们都做同样的事情;实现SensorEventListener并从onSensorChanged()侦听器中的values []中检索数据。

有更简单的方法吗?似乎有两个处理程序重复代码是不必要的。有没有办法使用组合的加速度计和方向数据一起访问values []数组?

由于有2个处理程序,我还必须这样做:

    orientationManager = new OrientationManager(this);
    orientationSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    orientationSensorManager.registerListener(orientationManager, 
            orientationSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), 
            SensorManager.SENSOR_DELAY_GAME);

    accelerometerManager = new AccelerometerManager(this);
    accelerometerSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    accelerometerSensorManager.registerListener(accelerometerManager, 
            orientationSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), 
            SensorManager.SENSOR_DELAY_GAME);

1 个答案:

答案 0 :(得分:34)

你可以尝试这样的事情:

private SensorManager mSensorManager;
private SensorEventListener mSensorListener;

////


mSensorManager = (SensorManager) this
                .getSystemService(Context.SENSOR_SERVICE);
mSensorListener = new SensorEventListener() {
    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1) {
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        Sensor sensor = event.sensor;
        if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            //TODO: get values
        }else if (sensor.getType() == Sensor.TYPE_ORIENTATION) {
            //TODO: get values
        }
    }
}

mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_GAME);