Reputation: 1235
I am looking at my results from using:
List<UsageStats> usageStatsList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, startTime,endTime);
where startTime in just after midnight, and endTime is just before midnight the same day.
Example result:
Pkg: com.android.chrome ForegroundTime: 6412 seconds Time last used: Thu Apr 19 22:31:17 PDT 2018
Pkg: com.instagram.android ForegroundTime: 5415 seconds Time last used: Thu Apr 19 23:11:22 PDT 2018
Pkg: com.android.chrome ForegroundTime: 5304 seconds Time last used: Thu Apr 19 03:00:49 PDT 2018
Pkg: com.instagram.android ForegroundTime: 5202 seconds Time last used: Thu Apr 19 03:00:45 PDT 2018
As you can see, it returns the same package twice for some things, with different time last used, even though both time last used were during the 24hr interval I specified.
I have looked at a bunch of other results here: Android UsageStatsManager producing wrong output?
but can't seem to fix my problem.
Does anyone know why it behaves this way? It seems to be time dependent? And the time last used always says 3am for some packages, despite me being fast asleep at that time?
Upvotes: 1
Views: 1196
Reputation: 41
Late to the party. I've seen numerous threads on this issue and everybody seems generally confused about how to use this API. After struggling on my own with this for a while I've discovered that the UsageStats
are accurate but what's going on under the hood is quite counter-intuitive.
From the UsageStatsManager.queryUsageStats()
documentation:
Note: The begin and end times of the time range may be expanded to the nearest whole interval period.
It turns out that more often than not the start & stop times you supplied to the method are both being changed underneath you to match up with a daily interval. You think you are querying the usage over the last 15 minutes but you are actually getting it for the last 24 hours.
Thankfully, the API at least gives you a means of determining what your start & stop times were changed to. The proper way to use this method is to always check what the range was transformed into using getFirstTimeStamp()
and getLastTimeStamp()
.
The very frustrating consequence of this is that you do not have any reliable control over your interval, which makes it useless for a good many use cases. Like others suggest, if you require precision then you should be using the queryEvents()
method, which unfortunately means some manual work in summing up the appropriate events you're looking for.
Upvotes: 4
Reputation: 342
I would recommend having a look at queryAndAggregateUsageStats
(documentation).
However, I myself am also experiencing some problems with UsageStats, please also have a look here: https://issuetracker.google.com/issues/118564471
Upvotes: 0