我正在尝试使用移动设备的accerlerometer为android构建一个计步器应用程序。无需重新启动移动设备,即可获得几乎准确的读数。这是针对每个步骤,它将值递增1.当重新启动移动设备时,步数计数器值变为0,因此我使用 sharedPreferences 保存了先前读数的值。但是当我启动手机并开始行走时,步数计数器每步增加2.如何解决?
public class Pedometer extends Activity implements SensorEventListener {
private TextView textView;
private SensorManager mSensorManager;
private Sensor mStepCounterSensor;
private Sensor mStepDetectorSensor;
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pedometer);
textView = (TextView) findViewById(R.id.textview);
mSensorManager = (SensorManager)
getSystemService(Context.SENSOR_SERVICE);
mStepCounterSensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
mStepDetectorSensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
}
@Override
public void onSensorChanged(SensorEvent event) {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
Sensor sensor = event.sensor;
float[] values = event.values;
int value = -1;
if (values.length > 0) {
value = (int) values[0];
}
int temp = sharedPreferences.getInt("steps", 0);
if (temp > value) {
temp = temp + 1;
editor.putInt("steps", temp).commit();
} else {
editor.putInt("steps", value).commit();
}
int count = sharedPreferences.getInt("steps", 0);
if (sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
textView.setText("Step Counter Detected : " + count);
} else if (sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
// For test only. Only allowed value is 1.0 i.e. for step taken
textView.setText("Step Detector Detected : " + count);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mStepCounterSensor,
SensorManager.SENSOR_DELAY_FASTEST);
mSensorManager.registerListener(this, mStepDetectorSensor,
SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onStop() {
super.onStop();
mSensorManager.unregisterListener(this, mStepCounterSensor);
mSensorManager.unregisterListener(this, mStepDetectorSensor);
}
}
答案 0 :(得分:0)
问题在于您的侦听器未注册,就像某些other people reported一样。由于您已注册多个侦听器和共享变量,因此步骤将计为两次。要解决此问题,您需要获取共享状态以跟踪您的侦听器是否未注册。