I want to monitor the orientation of the android device just in realtime
(I mean continually and retrieve new orientation as fast as possible). I use the combination of ACCELEROMETER
and MAGNETIC_FIELD
and have tow listeners for the changes that happen to those tow sensors. now where to put these 2 lines of code to get the orientation?
SensorManager.getRotationMatrix(R, null, aValues, mValues);
SensorManager.getOrientation(R, values);
I made a background Thread
and put that code in an infinite for loop
...is it a good implementation?
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(new Runnable() {
@Override
public void run() {
for (;;) {
SensorManager.getRotationMatrix(R, null, aValues, mValues);
SensorManager.getOrientation(R, values);
}
}
}
You should use the 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) {
}
};
On your Activity you have to import:
private SensorManager mSensorManager;
private float mAccel; // acceleration apart from gravity
private float mAccelCurrent; // current acceleration including gravity
private float mAccelLast; // last acceleration including gravity
And to initialize:
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.