首先抱歉这个愚蠢的问题。
我试图做的是每秒捕获加速度计数据三秒并添加该数据,但由于缺乏经验,我发现很难做到这一点。 / p>
到目前为止我所做的是:
实时获取 X,Y,X轴的加速度数据,并计算得到的加速度为 resul_acceleration = Math.sqrt(X ^ 2 + y ^ 2 + z ^ 2)< / strong>也是实时,并且随时间不断变化。
我想做的是:
在第一,第二和第三秒结束时找到 resul_acceleration ,即 a1,a2,a3 和返回(a1 + a2 + a3)我经历艰难的时期在java中编写一个完成任务的方法。
public void onSensorChanged(SensorEvent event) {
final ArrayList<Double> accln = new ArrayList<>();
//enter your code here
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
if (!mInitialized) {
mLastX = x;
mLastY = y;
mLastZ = z;
mInitialized = true;
} else {
float deltaX = Math.abs(mLastX - x);
float deltaY = Math.abs(mLastY - y);
float deltaZ = Math.abs(mLastZ - z);
if (deltaX < NOISE) deltaX = (float) 0.0;
if (deltaY < NOISE) deltaY = (float) 0.0;
if (deltaZ < NOISE) deltaZ = (float) 0.0;
mLastX = x;
mLastY = y;
mLastZ = z;
final double a =Math.sqrt((deltaX*deltaX)+(deltaY*deltaY)+(deltaZ*deltaZ));
accln.add(a); //what i am trying to do here is collect the sample data of acceleration in an array list for 3 seconds,// so later i can calculate average acceleration
}
}
答案 0 :(得分:1)
我建议启动一个计时器,然后当它达到1000毫秒时进行测量,然后是2000和3000.这可能会有所帮助: Android timer? How-to?
答案 1 :(得分:0)
只需使用Timer类方法每1秒做一次
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// Just calculate your accleration here
}
}, 0, 1000);
答案 2 :(得分:0)
你从来没有提到你试图获得加速数据的速度,所以我认为它将在~5hz(SENSOR_DELAY_NORMAL
)。请记住,这只是一个提示。如果另一个应用程序以更快的速度注册加速度传感器数据,您可能会以更快的速度获取事件。至于代码:
// SOMEWHERE IN YOUR APP
final ArrayList<Double> accln = new ArrayList<>(); //THIS SHOULD BE OUTSIDE YOUR CALLBACK!
final SensorEventListener eventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
//enter your code here
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
if (!mInitialized) {
mLastX = x;
mLastY = y;
mLastZ = z;
mInitialized = true;
} else {
float deltaX = Math.abs(mLastX - x);
float deltaY = Math.abs(mLastY - y);
float deltaZ = Math.abs(mLastZ - z);
if (deltaX < NOISE) deltaX = (float) 0.0;
if (deltaY < NOISE) deltaY = (float) 0.0;
if (deltaZ < NOISE) deltaZ = (float) 0.0;
mLastX = x;
mLastY = y;
mLastZ = z;
final double a = Math.sqrt((deltaX * deltaX) + (deltaY * deltaY) + (deltaZ * deltaZ));
accln.add(a); //what i am trying to do here is collect the sample data of acceleration in an array list for 3 seconds,// so later i can calculate average acceleration
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
SensorManager sensorManager = (SensorManager) context.getSystemService(SENSOR_SERVICE);
Handler handler = new Handler();
Sensor accel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(eventListener, accel, SensorManager.SENSOR_DELAY_NORMAL); //~5hz of data
handler.postDelayed(new Runnable() {
@Override
public void run() {
sensorManager.unregisterListener(eventListener);
}
}, 5000);
这将注册你的监听器并在5秒后从处理程序runnable中取消注册。