[英]android-how to monitor the orientation of the device in Realtime?
I want to monitor the orientation of the android device just in realtime
(I mean continually and retrieve new orientation as fast as possible). 我要监控的Android设备只是在定向realtime
(我的意思是不断并提取新的方向尽可能快)。 I use the combination of ACCELEROMETER
and MAGNETIC_FIELD
and have tow listeners for the changes that happen to those tow sensors. 我将ACCELEROMETER
和MAGNETIC_FIELD
结合使用,并为两个拖曳传感器发生的变化提供了拖车监听器。 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? 我制作了一个后台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);
}
}
}
You should use the SensorEventListener 您应该使用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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.