我正在寻找计算安卓设备速度的方法。我找到了一些东西,但即使我无法解决它。
我正在应用公式 V = Vo + a*t 来计算速度,并使用 TYPE_LINEAR_ACCELEROMETER。尽管如此,我没有得到连贯的结果,我不知道为什么。如果我将设备向右移动,X 轴不会长大,如果我向左移动,它也不会。上下同上。即使它停止了,也会有变化(不是 g!!,而是其他)。
这是我的代码注释。如果有人可以提供帮助,我将不胜感激 =)
public class MainActivity extends Activity implements SensorEventListener, OnClickListener {
TextView txtGravity,txtMax;
Button btnStart;
private long previousMarkTime;
private Vector currentSpeed;
private Boolean measure;
private SensorManager mSensorManager;
private Sensor mSensor;
@SuppressLint("InlinedApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
measure = false;
txtGravity = (TextView)findViewById(R.id.textView1);
txtMax = (TextView)findViewById(R.id.textView2);
btnStart = (Button)findViewById(R.id.button1);
btnStart.setOnClickListener(this);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent a) {
if(previousMarkTime==0){
// I get the first time
previousMarkTime = System.currentTimeMillis();
return;
}
long current_time= System.currentTimeMillis();
// Here I calculate the diference between now and the previous time
long t = current_time- previousMarkTime;
// I create a vector to store the acceleration
Vector aceleracionPorT = new Vector(a.values[0], a.values[1], a.values[2]);
double t_f = (float)t;
// This is a*t
aceleracionPorT.doMultiplyScalar(t_f/1000);
// and this is Vo + a*t
currentSpeed.sum(aceleracionPorT);
previousMarkTime = t_actual;
// I show the results
txtGravity.setText(currentSpeed.toString("0.000") + "\n"+
aceleracionPorT.toString("0.000"));
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
measure = false;
mSensorManager.unregisterListener(this);
}
@Override
public void onClick(View id) {
if(id==btnStart){
measure = !measure;
if(measure) {
mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_FASTEST);
currentSpeed = new Vector(0,0,0);
previousMarkTime = 0;
}
else txtGravity.setText("");
}
}
}