问题
I want to get the app user's steps data, but I got the data wasn't current day's, how can I to get the only current day data?
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:
The Sensor.TYPE_STEP_COUNTER returns the number of steps taken by the user since the last reboot while activated.
Therefore, if you want to get the steps of today, you should calculate programmatically.
Below code is my idea for 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());
}
来源:https://stackoverflow.com/questions/42661678/android-how-to-get-the-sensor-step-counter-data-only-one-day