Han Seria
Han Seria

Reputation: 15

How do I reset my step counter to 0 every time the app launches?

How do I reset my step counter to 0 every time my app launches? If I close my app and relaunch It, the counter continues from where it previously left off. I would like it to start over. I have already tried setting my steps taken textview to 0 every time my app launches but it doesn't change anything.

public class HomeActivity extends AppCompatActivity implements SensorEventListener {
private TextView stepsTakenTextView;
private TextView distanceTraveledTextView;
private SensorManager sensorManager;
private  Boolean running = false;
private UserModel userModel;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    stepsTakenTextView = findViewById(R.id.stepsTakenTextView);
    distanceTraveledTextView = findViewById(R.id.distanceTraveledTextView);
    sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

}

@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;
}


@Override
public void onSensorChanged(SensorEvent event) {
    if(running){
        float stepsTaken= event.values[0];

Upvotes: 0

Views: 402

Answers (1)

dglozano
dglozano

Reputation: 6607

The sensor will only be restarted when the device is rebooted.

Android Sensor API

A sensor of this type returns the number of steps taken by the user since the last reboot while activated. The value is returned as a float (with the fractional part set to zero) and is reset to zero only on a system reboot...

Instead, you can do the following:

  1. As soon as you start the app, save the first value returned by the sensor.
  2. Every time the sensor emits a new value, subtract the initial value from it.

Upvotes: 1

Related Questions