9

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

有没有更简单的方法来做到这一点?似乎有 2 个具有重复代码的处理程序是不必要的。有没有办法使用组合的加速度计和方向数据访问 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);
4

1 回答 1

40

你可以尝试这样的事情:

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);
于 2010-12-03T08:49:40.200 回答