javaandroid

Is there a way to count steps from the start of the day?


My friend asked me to make a step counter app, but i've encountered a problem. When i get the number of steps taken bu the user using sensorEvent.values[0], it counts the steps from the last reboot. Yet i need the app to work so that it takes steps per day, not per reboot or per launch.

I tried to set the sensorEvent.values myself, but that did not work. I want so that if the app detects that the current date isnt the date written in shared preferences, it resets the step counter, yet with it working by sensorEvent.values[0], i have no idea how to.


Solution

  • For this you need to store(in shared prefs) count of steps when user first opens the app after reboot (call it Int initialStepsAfterReboot). And the total steps count since reboot will also be fetched from sensorEvent.values[0] (call it Int totalStepsSinceReboot). Whenever you want to get total steps user has walked today(since he opened the app) you will subtract initial steps count from total steps count.

    you will use following formula:

    Int totalStepsCountToday = totalStepsSinceReboot - initialStepsAfterReboot //totalStepsSinceReboot was fetched using sensorEvent.values[0] as you said
    

    then next day you will reset initialStepsAfterReboot based on a value you will store to know when was this initial steps recorded , was it today or yesterday? call it Date initialStepsAfterRebootRecordedDate . And you will update initialStepsAfterReboot to whatever value you get when user opened app using sensorEvent.values[0] and use same formula again and again after verifying that date of today is same as initialStepsAfterRebootRecordedDate i.e it should be valid for today not outdated.

    variables to store description
    initialStepsAfterRebootcount count of steps when user first time launch app after reboot.
    initialStepsAfterRebootRecordedDatedate count of the day when you stored initialStepsAfterReboot to check if it's valid for today or outdated.

    for example, if user opened your app and sensorEvent.values[0] returns 100 steps, which means today you have extra 100 steps, now when user walked 300 steps, sensorEvent.values[0] will show you 400 steps, so you subtract initialSteps=100 from totalSteps=400 so you will get 100, and this is correct. Next day you will check if the initialStepsRecordedDate is today or yesterday, if it's today, use it, otherwise update it to sensorEvent.values[0].

    Make sure you don't update initialStepsAfterReboot again and again when user opens the app, rather you update it only if it's null/empty or outdated. this will make sure that you update it once a day only.

    PS: pls share more snippets so I can help more.