我试图写一个小应用程序,用手机的速度更新屏幕。它使用加速度计计算当前速度并将其写入屏幕。问题是移动手机后速度不会回到零速度。它会在速度的最高点稳定下来。我使用的是LINEAR_ACCELEROMETER
这是代码:
public class AccelerometerUpSensor extends SensorAbstract{
private ExerciseFragment fragment;
private double v0 = 0;
private float lastX;
private float lastY;
private float lastZ;
private long interval;
private long lastEvent = System.currentTimeMillis();
public AccelerometerUpSensor(SensorManager sensorManager, ExerciseFragment fragment, int[] sensorTypes){
super(sensorManager,sensorTypes);
this.fragment = fragment;
}
@Override
public final void onSensorChanged(SensorEvent event) {
lastX = event.values[0];
lastY = event.values[1];
lastZ = event.values[2];
long now = System.currentTimeMillis();
interval = (now - lastEvent);
lastEvent = now;
double acceleration = lastX+lastY+lastZ;
double velocity = v0 + (acceleration*(interval/(double)1000));
v0 = velocity;
System.out.println(velocity);
}
答案 0 :(得分:1)
有com.google.android.gms
ActivityRecognition
,您可以在其中跟踪不同类型的移动。
Accelerometer
mGravity = event.values.clone();
float x = mGravity[0];
float y = mGravity[1];
float z = mGravity[2];
mAccelLast = mAccelCurrent;
mAccelCurrent =(float) Math.sqrt(x * x + y * y + z * z);
float delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 0.9f + delta;
// Make this higher or lower according to how much motion you want to detect
if (Math.abs(mAccel) > 2) {
答案 1 :(得分:1)
private void calculateVelocity(float x, float y, float z){
long now = System.currentTimeMillis();
interval = (now - lastEvent);
if(interval > 100){
lastEvent = now;
double acceleration = x+y+z-lastX-lastY-lastZ;
double velocity = v0 + (acceleration*(interval/(double)1000));
velocities.add(Math.abs(velocity));
v0= velocity;
lastX = x;
lastY = y;
lastZ = z;
}
}
这是我用来计算每100毫秒速度的代码。 velocities-array用于计算每秒的平均速度,您可以忽略它。该方法的输入是event.values