我需要在点击按钮时重置android步骤计数器。我知道,当传感器被激活时,该值将继续增加而不会重置为零,直到系统重新启动。
我试过这个,但它只显示0;
SharedPreferences prefs = getActivity().getSharedPreferences(MY_PREFS, MODE_PRIVATE);
stepsAtReset = prefs.getInt("stepsAtReset", 0);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
isPaused = false;
isStopped = false;
activityRunning = true;
//Disable the start and pause button
btnStart.setEnabled(false);
btnResume.setEnabled(false);
//Enabled the pause and stop button
btnPause.setEnabled(true);
btnStop.setEnabled(true);
stepsAtReset = stepsInSensor;
SharedPreferences.Editor editor = getActivity().getSharedPreferences(MY_PREFS, MODE_PRIVATE).edit();
editor.putInt("stepsAtReset", stepsAtReset);
editor.commit();
// you can now display 0:
count.setText(String.valueOf(0));
}
});
@Override
public void onSensorChanged(SensorEvent event) {
if (isPaused || isStopped) {
Log.d("MAINFRAG", "pause or stopped");
} else{
if(activityRunning){
count.setText(String.valueOf(event.values[0]));
int stepsSinceReset = stepsInSensor - stepsAtReset;
count.setText(String.valueOf(stepsSinceReset));
}else{
event.values[0] = 0;
}
}
}
答案 0 :(得分:1)
首先,您需要将数据保存在pref中,然后需要将var重置为零
editor.commit();
stepsAtReset = 0
count.setText(String.valueOf(stepsAtReset));`