Getting wrong data from stats usage Android

895 views Asked by At

i am tying to retrieve User usage data using the Usagestats ...but i'm getting wrong data...i want to get daily usage "From 00:00:00 to 23:59:59 "

    Calendar cal = Calendar.getInstance();

      cal.add(Calendar.DAY_OF_WEEK, -1); \\ the missing line


    UsageStatsManager uStateManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
   List<UsageStats> usageList = uStateManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, cal.getTimeInMillis(), System.currentTimeMillis());

when i use .getTotalTimeInForeground() i get a different result than expected ? Can you help me in setting the right way cause i tried alot and different ways without getting the expected result? Thanks

1

There are 1 answers

0
jguerinet On

This question is a bit old but I've been battling with the UsageStatsManager for a fair bit of time now and have found out a few things which might be useful to others. Here's a few tips to help you with this problem.

  • Calendar.getInstance() returns "a Calendar object whose calendar fields have been initialized with the current date and time." (link) So if you're looking to get the daily usage at those times, you need to set them manually to midnight.
  • It looks like the UsageStatsManager uses UTC time to store all of their data. So when querying, make sure to adjust the time for that.
  • I have found the daily usage stats using queryUsageStats to be completely unreliable. Even with UTC time adjustment, it seems that depending on the time of day it'll send back yesterday's stats instead of today's stats.

There's not much documentation as to how they decide which stats to take into account when you query this method, which makes it fairly unreliable. If calculating daily stats, I would highly recommend using the UsageEvents instead and manually calculating the time. The calculated time matches what is returned by queryUsageStats (provided that that method returns the right stats), which for me is proof enough that it's reliable enough for foreground tracking. There's more about how to do that on this question, and I have added my implementation of it there (link).