1

我正在尝试使用手机的加速度计为 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);
    }
}
4

1 回答 1

0

问题是您的听众并没有像其他人报告的那样未注册。由于您注册了多个侦听器和一个共享变量,因此这些步骤将被计算两次。要解决这个问题,您需要获取一个共享状态来跟踪您的侦听器是否未注册。

于 2016-12-01T19:25:18.507 回答