首页 > 解决方案 > 如何每天重置计步器?

问题描述

我正在创建一个计步器应用程序。它几乎完成了,除了一件事。当一天过去了,我想重置步数。如何实现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();
}

标签: androidsharedpreferences

解决方案


希望我的回答清楚,我会更正您的代码。

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

推荐阅读