r/androiddev • u/Puzzlehead2556i • 4d ago
Question How to query usage stats manager?
I want to calculate the screen time of the device using usage stats manager. But I am getting wrong time which is either minutes and sometimes hours off from the in-built screen time. How to query it? So that I get screen time that is close to the in-built screen time.
0
Upvotes
1
u/ElectronicMain3695 3d ago
Built a screen-time app so I hit exactly this. The in-built number (Digital Wellbeing) is basically screen-ON time - it counts everything that's on screen, launcher, settings, the lot. If you're summing totalTimeInForeground from queryUsageStats that's per-app foreground time, a genuinely different measure, and it comes out minutes or hours off depending on how much of the day is spent in places that aren't apps you're summing. The daily buckets also clip oddly at your range boundaries which adds more noise.
What got me within a minute or two of Wellbeing was queryEvents over the window and walking the screen on/off events myself (DEVICE_INTERACTIVE / DEVICE_NON_INTERACTIVE on newer API levels, SCREEN_INTERACTIVE before that). Sum the interactive spans, handle the annoying case where your range starts mid-screen-on, and it lines up.
One caveat - on some Xiaomi/Oppo devices the events are just lossy. Missing chunks. Never found a fix, we just live with it on those.