我正在使用加速度计,第一段代码是摇晃检测器: (Code1)
if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
long now = System.currentTimeMillis();
//**********************************************************************
if ((now - mLastForce) > SHAKE_TIMEOUT) {
mShakeCount = 0;
}
if ((now - mLastTime) > TIME_THRESHOLD) {
long diff = now - mLastTime;
float speed = Math.abs(x + y + z - mLastX - mLastY - mLastZ) / diff * 10000;
if (speed > FORCE_THRESHOLD) {
if ((++mShakeCount >= SHAKE_COUNT) && (now - mLastShake > SHAKE_DURATION)) {
mLastShake = now;
mShakeCount = 0;
if (mShakeListener != null) {
mShakeListener.onShake();
}
}
mLastForce = now;
}
mLastTime = now;
mLastX = x;
mLastY = y;
mLastZ = z;
当手机被摇晃时,我收到了这条消息: (Code2)
mSensorListener.setOnShakeListener(new OnShakeListener() {
@Override
public void onShake() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Shake!", Toast.LENGTH_SHORT).show();
}
});
我也有一个循环,每两秒将加速度计值 x、y、z 保存到数组中: (代码3)
if (lastUpdate == -1 || (curTime - lastUpdate) > 2000) {
lastUpdate = curTime;
x = values[0];
y = values[1];
z = values[2];
for (int column = 0; column < 3; column++) {
if (column == 0) {
p[row][column] = values[0];
}
if (column == 1) {
p[row][column] = values[1];
//yacc.setText("Os X: " + p[row][column]);
}
if (column == 2) {
p[row][column] = values[2];
//zacc.setText("Os X: " + p[row][column]);
}}
if (row == 0) {
xacc.setText("Os X: " + p[row][0] + " " + p[row][1] +" " + p[row][2]);
}
if (row == 1) {
yacc.setText("Os X: " + p[row][0] + " " + p[row][1] +" " + p[row][2]);
}
if (row == 2) {
zacc.setText("Os X: " + p[row][0] + " " + p[row][1] +" " + p[row][2]);
}
if (row == 3) {
z2acc.setText("Os X: " + p[row][0] + " " + p[row][1] +" " + p[row][2]);
}
if (row == 4) {
z3acc.setText("Os X: " + p[row][0] + " " + p[row][1] +" " + p[row][2]);
}
row++;
if (row == 5) {
row = 0;
}
Code3是无限循环程序,而code1是晃动检测器。我该如何同时运行它们?可以使用线程(如何使用)或其他方式。