我发现了这段代码,它的功能是在设备受到足够强的震动时执行某些操作,但我还没有完全理解它。有人请帮帮我
public class ShakeActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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;
}
private SensorManager mSensorManager;
private float mAccel; // acceleration apart from gravity
private float mAccelCurrent; // current acceleration including gravity
private float mAccelLast; // last acceleration including gravity
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) {
}
};
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onStop() {
mSensorManager.unregisterListener(mSensorListener);
super.onStop();
}
}
请帮助我理解这两句话
mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));//I guess this is for computing the value of the acceleration
我不明白这句台词
mAccel = mAccel * 0.9f + delta;
提前谢谢。
最佳答案
传感器将返回三个值,用于沿三个轴方向的加速度;这些值放在代码示例中的x
、y
和z
中。假设弹簧上的三个质量彼此成直角;当您移动设备时,弹簧会拉伸和收缩,x
、y
和z
包含它们的长度。mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));
这是计算加速度的大小。想象一下,如果不是弹簧上的三个质量,而是只有一个,总是指向设备加速的方向。实际上,可以根据我们的值计算出这个系统的样子,这就是这里要做的:mAccelCurrent
是这样一个弹簧会被拉伸多少。This是正在执行的计算。mAccel = mAccel * 0.9f + delta;
这是输入上的high pass filter。它的作用是使加速度的突然变化产生更大的值。仅仅从你发布的代码中还不清楚为什么要这样做;我猜是为了让其他地方的代码在设备被震动时,最终检查mAccel
时对每次震动的极限力更敏感。