I am trying to build a step counter app for android using the accerlerometer of the mobile. Without restarting the mobile, it gives almost accurate reading. That is for each steps, it increments the value by 1. When the mobile is restarted, the step counter value goes to 0 so i saved the value of the previous reading using the sharedPreferences. But when I start my mobile and start walking, for each steps the step counter increments by 2. How to solve it?
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);
}
}