android - 如何每天重置计步器?
问题描述
我正在创建一个计步器应用程序。它几乎完成了,除了一件事。当一天过去了,我想重置步数。如何实现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) }
推荐阅读
- antlr - 如何将 Antlr3 转换为 Antlr4?
- python - 如何在不使用 Postgres 的 ARRAY 功能的情况下在 SQLAlchemy 中创建简单整数列表的属性
- javascript - 带“录音机”的鼓机
- java - Spring控制器如何每次只服务一个请求,并丢弃同一方法收到的其他请求,直到第一个请求完成
- cloud - 如何在雪花中从今天或之前的日期获取 n 天/月/年日期?
- angular - Onclick不同的按钮,数据应该相应地使用角度材料显示在mat-table中。?
- r - 使用 ggplot2 进行 R 数据可视化 - 使用 RColorBrewer 为 20 个变量添加颜色
- linux - Makefile - make 找到一个文件,而 shell 没有
- api - 如何每 x 分钟在后端执行一次函数
- sql - 如何在不更改表中列的情况下将值添加到选择列表的列开头?