如何每天重置计步器?



我正在创建一个计步器应用程序。它几乎完成了,除了一件事。当一天过去了,我想重置步数。如何实现sharedpreferences到我的代码?如何重置步数?我试过这种方法。但随着时间的流逝,每一个数字都变成了正常值。不从零开始

@Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor == stepCounter){
stepCount = (int) sensorEvent.values[0];
////////////////
saveSteps(stepCount);
resetStep(stepCount);

////////////////
progressBar.setProgress(stepCount);
textView.setText(String.valueOf(stepCount));
txtstepinfo.setText("Adım: " +  String.valueOf(stepCount) );
///////////
progressBar.setProgress(stepCount);
Log.i("sda",String.valueOf(stepCount));
/////////////////////
txtcalinfo.setText("Kalori: "+calculateCalori(stepCount));
txtDistanceinfo.setText("Mesafe: "+calculateDistance(stepCount));
}
}

private void resetStep(int s){
Calendar date = Calendar.getInstance();

if(date.get(Calendar.HOUR) == 0 && date.get(Calendar.MINUTE) == 00 ){
editor.putInt("step",0);
editor.apply();
stepCount = 0;
txtstepinfo.setText(String.valueOf(stepCount));
}

}
private void saveSteps(int s){
editor.putInt("step",s);
editor.apply();
}

希望我的回答能说清楚,我会改正你的代码。

if (date.get(Calendar.HOUR) == 0 && date.get(Calendar.MINUTE) == 00 ) {
editor.putInt("step",0);
editor.apply();
stepCount = 0;
txtstepinfo.setText(String.valueOf(stepCount));
}

表示,当应用程序在00:00:00 - 59秒打开时,此代码运行正常。我有一个简单的条件来重置你的共享偏好,但我没想到这是最好的答案。

val preferences by lazy { applicationContext.getSharedPreferences("KEY", MODE_PRIVATE) }
val calendar by lazy {Calendar.getInstance() }
val date by lazy { calendar.get(Calendar.DAY_OF_MONTH) } // 1 - 31
val dateKey = "DATE_NOW"
val stepKey = "STEP_COUNT"
// Check the date
if (preferences.getInt(dateKey, 0) != date) {
// Clear shared preferences
preferences.edit { clear() }
// Persistent the date
preferences.edit { putInt(dateKey, date) }
}
val myStep = preferences.getInt(stepKey, 0)
preferences.edit { putInt(stepKey, myStep + 1) }

最新更新