2013-08-29 27 views
0

我想監視Android設備的方向只是在realtime(我的意思是不斷,並儘快檢索新的方向)。我使用ACCELEROMETERMAGNETIC_FIELD的組合,並且爲這些拖曳傳感器發生的變化提供了兩個聽衆。現在在哪裏放這兩行代碼來獲取方向?android-如何實時監控設備的方向?

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); 
         } 
          } 
            } 

回答

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; 
+0

你的答案是沒有關係的我問了什麼!我爲'ACCELEROMETER'和'MAGNETIC_FIELD'使用'SensorEventListener'。但如何監視'orientation'的變化? – Soheil