Search code examples
androidusagestatsmanager

queryUsageStats interval duration


I'm using UsageStatsManager API to get usage statistics for a certain time interval. All works fine if I use the predefined intervals i.e. INTERVAL_DAILY, INTERVAL_WEEKLY, INTERVAL_MONTHLY, INTERVAL_YEARLY. But if I want to view the data for the past 2 or 3 hours, I am getting today's data for the whole day. I have tried using Calendars and System.currentTimeMillis() but that didn't give me filtered results.

Calendar approach :

Calendar startCalendar = Calendar.getInstance();
startCalendar.add(Calendar.HOUR_OF_DAY, -2);

Calendar endCalendar = Calendar.getInstance();

And pass this to queryUsageStats method like this:

usageList = usm.queryUsageStats(interval, startCalendar.getTimeInMillis(), endCalendar.getTimeInMillis());

where interval is INTERVAL_BEST.

System.currentTimeMillis() approach :

long startTime = System.currentTimeMillis() - 7200*1000 // 7200 seconds i.e. 2 hrs

long endTime = System.currentTimeMillis();

Pass this to queryUsageStats just like above :

usageList = usm.queryUsageStats(interval, startTime, endTime);

where interval is again INTERVAL_BEST.

I'd like to know whether it's possible to get data for this duration i.e. less than a day, as the INTERVAL_BEST hasn't been documented properly to include this information. Any help would be appreciated as I'm stuck on this problem.


Solution

  • As UsageStatsManager doc says:

    A request for data in the middle of a time interval will include that interval.

    It seems that usage data is stored in buckets, and minimum bucket is a day, so you can't query usage stats for period less than a day. Even if you query a one-hour interval for a particular day, usage stats for the whole day is returned.