簡體   English   中英

android-如何實時監視設備的方向?

[英]android-how to monitor the orientation of the device in Realtime?

我要監控的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);
                      }
                          }
                                    }

您應該使用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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM