我试图弄清楚何时发生步骤。因此,我编写了一个名为 countSteps 的方法来执行此操作。它的问题是我陷入其中,因为在 while 循环中我不断获取新数据,我认为它永远不会返回到 onSensor。我还收到一个名为 indexoutofboundsexception 的错误:invalid index 2,size 2。
所以我的第一个问题是有没有其他方法可以实现没有while循环的方法?其次是如何修复 indexoutofboundsexception。公共类 MainActivity 扩展 Activity 实现 SensorEventListener {
private SensorManager mSensorManager;
private Sensor mRotationVector;
private Sensor mAccelerometer;
private TextView mTextView4;
private TextView mTextView5;
private TextView mTextView6;
private TextView mTextView7;
private TextView mTextView8;
float a, b, c, d, x, y, z, xyz;
float[] retVals = new float[3];
float avg = 10;
float factor = (float) 1.15;
ArrayList<Float> accelData = new ArrayList<Float>();
public int peakCounter = 0;
public int underAvgCounter = 0;
public void countSteps() {
int n = 0;
float controlPoint = accelData.get(0);
while (accelData.iterator().hasNext()) {
if (accelData.get(n) != accelData.get(n + 1)) {
if (accelData.get(n) > accelData.get(n + 1)) {
if (accelData.get(n) < controlPoint) {
n++;
} else {
if (accelData.get(n) < avg * factor) {
underAvgCounter++;
}
peakCounter++;
n++;
}
} else {
controlPoint = accelData.get(n + 1);
n++;
}
} else {
n++;
}
peakCounter -= underAvgCounter;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView4 = (TextView) findViewById(R.id.textView4);
mTextView5 = (TextView) findViewById(R.id.textView5);
mTextView6 = (TextView) findViewById(R.id.textView6);
mTextView7 = (TextView) findViewById(R.id.textView7);
mTextView8 = (TextView) findViewById(R.id.textView8);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
accelData.add((float) 0);
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mAccelerometer,
SensorManager.SENSOR_DELAY_GAME);
}
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
@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 sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
x = event.values[0];
y = event.values[1];
z = event.values[2];
xyz = (float) Math.sqrt((x * x) + (y * y) + (z * z));
accelData.add(xyz);
mTextView7.setText("magnitude accel " + xyz);
countSteps();
mTextView8.setText("steps " + peakCounter);
}
}