android如何获取传感器步数数据只有一天?

时间:2017-03-08 02:04:41

标签: android sensor

我想获取应用用户的步骤数据,但我得到的数据不是现在的数据,我怎样才能获得当天唯一的数据?

 public StepCounterRecord(ReactApplicationContext reactContext) {
        mSensorManager = (SensorManager)reactContext.getSystemService(reactContext.SENSOR_SERVICE);
        mReactContext = reactContext;
    }

    public int start(int delay) {
    this.delay = delay;
    if ((mStepCounter = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)) != null) {
        mSensorManager.registerListener(this, mStepCounter, SensorManager.SENSOR_DELAY_FASTEST);
        return (1);
    }
    return (0);
}


@Override
public void onSensorChanged(SensorEvent sensorEvent) {

    Sensor mySensor = sensorEvent.sensor;
    WritableMap map = mArguments.createMap();

    if (mySensor.getType() == Sensor.TYPE_STEP_COUNTER) {
        long curTime = System.currentTimeMillis();
        i++;
        if ((curTime - lastUpdate) > delay) {
            i = 0;
            map.putDouble("steps", sensorEvent.values[0]);
            sendEvent("StepCounter", map);
            lastUpdate = curTime;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

Sensor.TYPE_STEP_COUNTER返回自上次重启后用户所执行的步骤数 因此,如果您想获得今天的步骤,您应该以编程方式进行计算 下面的代码是我对计算它的想法

private int milestoneStep;

@Override
public void onSensorChanged(SensorEvent sensorEvent) {
    int totalStepSinceReboot = sensorEvent.values[0];

    int todayStep = getPreferences(today());
    if(todayStep == 0){
        milestoneStep = totalStepSinceReboot;
    }else{
        int additionStep = totalStepSinceReboot - milestoneStep;
        savePreferences(today(), todayStep + additionStep);
        milestoneStep = totalStepSinceReboot;

        Log.i("TAG","Your today step now is "+getPreferences(today()));
    }
}


private void savePreferences(String key, int value) {
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt(key, value);
    editor.commit();
}

private void getPreferences(String key){
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    return; = sharedPreferences.getInt(key, 0);

}

public String today() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    return sdf.format(Calendar.getInstance().getTime());
}