How get step count from background app using JobScheduler

1.4k views Asked by At

The Android docs for the STEP_COUNTER sensor are a bit confusing.

According to this: Android Sensor doc I should always register the STEP_COUNTER sensor because otherwise the step counter sensor will not count at all. That is all fine and works as expected up until I think Android 10 when sensor events are no longer sent to background apps.

So then I tried to take the advice from this other step counter doc recommending using a JobScheduler to read the last value periodically. Now, afaik there is no way to get the latest value from a sensor, I must register a SensorEventListener as always.

So, now I tried to combine the two advices, always register the step counter sensor so the hardware sensor is counting then since I always get a fresh event when I register my listener, I tried to unregister and re-register this listener when the JobScheduler executed but I have not been able to get the latest step count when in background on my Pixel running Android 11 no matter what method I have tried.

I know we have Google Fit but for this specific scenario, using the basic step counter would be good enough if I could read out the latest value also when the JobScheduler runs as indicated in the documentation.

Anyone knows if this should still be possible or is it just that the docs are not updated?

1

There are 1 answers

1
Alexey Zakharenka On

Your app should be in foreground mode to get sensors data. Works for me with attaching foreground notification to worker (workmanager + setForegroundAsync). I think you solution will also work if foreground service will be active.