我试图找出用板载加速度计按下按钮的力。我想我必须做一系列读数,然后比较这些值。我的尝试是这样的:
velButton.setOnTouchListener(new OnTouchListener()
{
public boolean onTouch(View view, MotionEvent event)
{
int velocity = 0;
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
velocity = getVelocity();
velocityView.setText("This is the velocity: " + velocity);
break;
}
return false;
});
}
protected int getVelocity()
{
float accent = 0;
int velocity;
try
{
accent = getHighestValue();
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
velocity = (int) accent;
return velocity;
}
protected float getHighestValue() throws InterruptedException
{
float highest;
float[] value = new float[20];
String txt = "";
for(int i = 0; i < value.length; i++)
{
Thread.sleep(1);
value[i] = accelerometer_z;
txt += "Reading at: " + i + " ms returns: " + value[i] + "\n";
}
Arrays.sort(value);
highest = value[19];
textView2.setText(txt);
return highest;
}
float accelerometer_z 在我的主要活动中初始化,并通过 onSensorChanged 不断更新。
我的问题是我没有得到一系列值,我只从 getHighestValue 方法中的 for 循环中得到一个值。
干杯/M
添加了 onSensorChanged:
@Override
public void onSensorChanged(SensorEvent event)
{
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
{
getAccelerometer(event);
}
}
private void getAccelerometer(SensorEvent event)
{
float[] value = event.values;
// Movement
accelerometer_x = value[0];
accelerometer_y = value[1];
accelerometer_z = value[2];
accelationSquareRoot = (accelerometer_x * accelerometer_x + accelerometer_y *
accelerometer_y + accelerometer_z * accelerometer_z)
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
long actualTime = System.currentTimeMillis();
if (accelationSquareRoot >= 2)
{
if (actualTime - lastUpdate < 200)
{
return;
}
lastUpdate = actualTime;
}
}