我做了这个Android应用程序,它计算足迹并且运行良好,但它只能重置设备重启时的步骤。我希望它将计算的足迹存储在SharedPreferences首选项中。然后每天将其重置为零,但我不知道如何继续。通过运行reset()函数,它只将可视步骤设置为零。
public class MainActivity extends AppCompatActivity implements SensorEventListener {
SensorManager sensorManager;
TextView tv_steps;
boolean running = false;
SharedPreferences prefs = null;
SharedPreferences.Editor editor;
int steps;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_steps = (TextView) findViewById(R.id.tv_steps);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
prefs = getApplicationContext().getSharedPreferences("MY_PREFS", MODE_PRIVATE);
editor = prefs.edit();
}
@Override
protected void onResume(){
super.onResume();
running = true;
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if(countSensor != null){
sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
}
else {
Toast.makeText(this, "Sensor not found!", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onPause(){
super.onPause();
running = false;
sensorManager.unregisterListener(this);
// unregistering register listener hardware counter is disabled
}
@Override
public void onSensorChanged(SensorEvent event) {
if(running){
steps = (int) event.values[0];
editor.putInt("steps", steps);
editor.commit();
// resetStepCount();
tv_steps.setText(String.valueOf(prefs.getInt("steps", steps)));
}
}
private void resetStepCount() {
// reset every 24 hours.
editor.clear();
steps = 0;
editor.putInt("steps", steps);
editor.commit();
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}