• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Inifite Step Counter app

I'm writing a basic step counter app in Android Studio using:

sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
val stepSensor : Sensor? = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)

and sharedPreferences to read/write data.

I've no problem to read total steps.
What I need is my app counts the total steps since first time it is executed. My problem is that steps are reset on device reboot and I don't know how to setup the logic to continue to add steps to the total.

Anyone could help on this? TY
 
To persist the step count across device reboots, you can use shared preferences to store the total step count.

Here is an example of how you can implement this:

Code:
// Get an instance of shared preferences
val sharedPreferences = getSharedPreferences("STEP_COUNTER_PREFS", Context.MODE_PRIVATE)

// Get the current total step count from shared preferences
val totalSteps = sharedPreferences.getInt("TOTAL_STEPS", 0)

// Register the step counter sensor listener
sensorManager.registerListener(object : SensorEventListener {
  override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}

  override fun onSensorChanged(event: SensorEvent?) {
    // Increment the total step count by the number of steps taken
    totalSteps += event?.values?.get(0)?.toInt() ?: 0

    // Save the updated total step count to shared preferences
    sharedPreferences.edit().putInt("TOTAL_STEPS", totalSteps).apply()
  }
}, stepSensor, SensorManager.SENSOR_DELAY_UI)

This code will read the current total step count from shared preferences when the app starts, and then use a sensor listener to increment the total step count every time the step sensor fires an event. The updated total step count is then saved back to shared preferences.

This way, the total step count will be persisted across device reboots, and you can retrieve the current total step count from shared preferences at any time by calling getInt("TOTAL_STEPS").

I hope this helps! Let me know if you have any questions.
 
Back
Top Bottom