安卓怎么才能一天就拿到传感器步数数据呢?

2022-08-31 00:00:00 sensors android

我想获取APP用户的步数数据,但获取的数据不是当天的数据,如何才能获取唯一的当天数据?

 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;
        }
    }
}

解决方案

Sensor.TYPE_STEP_COUNTER返回自上次重新启动以来用户在激活时执行的步骤数。
因此,如果您想得到今天的步骤,您应该通过编程进行计算。
下面的代码是我对Calcualte It的想法

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());
}

相关文章