Search code examples
javaandroidsensors

Restore Step Counter data after phone reboot


I am writing an android app in java which uses Android phone's Step Counter sensor event values to record walking steps taken by the user. Basically my java code to display current Steps is as follows:

if (running) {
   totalSteps = event.values[0];
   currentSteps = totalSteps - previousTotalSteps;
   tv_stepsTaken.setText(String.valueOf(currentSteps));
}

I am using SharedPreferences to load, save and reset previousTotalSteps on a daily basis.

My problem is that when phone reboots, the totalSteps event value from Step Counter Sensor is reset automatically to zero, hence it turns my currentSteps value to negative as previousTotalSteps value is then being subtracted from zero. Only solution that is coming to my mind is to set previousTotalSteps to zero too. But it will defeat the purpose of recording daily steps. If the user reboots the phone in the middle of the day, then half day's data will be lost or otherwise turn negative in display. I am also recording this daily steps value to sqlite database as daily history to be shown graphically to user. So, this negative value goes to sqlite databse too and ruins the historical graph. I need suggestions to solve this problem. My reset data code is as follows:

previousTotalSteps = totalSteps;
tv_stepsTaken.setText("0");
saveStepsData();
return true;

Solution

  • So, I have solved this problem by myself. I am posting this solution for anyone else who find themselves in this situation, so that it might help them solve it.

    For this, currentSteps as well as previousSteps need to be saved to SharedPreferences after each step. Earlier only previousSteps was being saved and that too once daily.

    Thus, totalSteps-previousSteps will give an increment of one step to be added to currentSteps.

    In case, the phone reboots, totalSteps value is reset to zero. If that happens(or by any chance, if totalSteps is less than previousSteps), then the previousSteps value will also be set equal to totalSteps for that condition before applying both variables for current steps calculation.

     if (running) {
    
                totalSteps = event.values[0];
                loadCurrentStepsData();
                loadPreviousStepsData();
                if (totalSteps == 0 || totalSteps<previousSteps) {
                    previousSteps = totalSteps;
                    savePreviousStepsData();
                }
                currentSteps = currentSteps + (totalSteps - previousSteps);
                previousSteps = totalSteps;
                saveCurrentStepsData();
                savePreviousStepsData();
            }
            tv_stepsTaken.setText(String.valueOf(currentSteps));