android-如何实时监控设备的方向?

时间:2013-08-29 08:35:39

标签: java android

我想在realtime中监控Android设备的方向(我的意思是不断地并尽可能快地检索新的方向)。我使用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);
                      }
                          }
                                    }

1 个答案:

答案 0 :(得分: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;