0

我想监视 android 设备的方向realtime(我的意思是不断地并尽快检索新的方向)。我使用 和 的组合ACCELEROMETERMAGNETIC_FIELD有两个侦听器来处理这些拖曳传感器发生的变化。现在把这两行代码放在哪里来获得方向?

SensorManager.getRotationMatrix(R, null, aValues, mValues);
SensorManager.getOrientation(R, values);

我做了一个背景Thread并将该代码放入无限for loop......这是一个很好的实现吗?

    ExecutorService executor = Executors.newCachedThreadPool();
    executor.execute(new Runnable() {

        @Override
        public void run() {
            for (;;) {
                SensorManager.getRotationMatrix(R, null, aValues, mValues);
                SensorManager.getOrientation(R, values);
                      }
                          }
                                    }
4

1 回答 1

0

您应该使用 SensorEventListener

private final SensorEventListener mSensorListener = new SensorEventListener() {

    public void onSensorChanged(SensorEvent se) {
      float x = se.values[0];
      float y = se.values[1];
      float z = se.values[2];
      mAccelLast = mAccelCurrent;
      mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));
      float delta = mAccelCurrent - mAccelLast;
      mAccel = mAccel * 0.9f + delta; // perform low-cut filter
    }

    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }
};

在您的活动中,您必须导入:

private SensorManager mSensorManager;
private float mAccel; // acceleration apart from gravity
private float mAccelCurrent; // current acceleration including gravity
private float mAccelLast; // last acceleration including gravity

并初始化:

mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
mAccel = 0.00f;
mAccelCurrent = SensorManager.GRAVITY_EARTH;
mAccelLast = SensorManager.GRAVITY_EARTH;
于 2013-08-29T08:48:34.677 回答