问题
I'm trying to query UsageStats
from UsageStatsManager
.
I've build a DateUtils
class that provide me with methods to get the start and end time of each day/month/year (week is coming), like this:
public static Calendar getCal(int year, int month, int day) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, day, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal;
}
public static long getDayStart(int year, int month, int day) {
return getCal(year, month, day).getTimeInMillis();
}
public static long getDayEnd(int year, int month, int day) {
Calendar cal = getCal(year, month, day);
cal.add(Calendar.DATE, 1);
return cal.getTimeInMillis();
}
I'm using these longs to query UsageStats
for different days:
mUsageStats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, startTime, endTime);
I can get data for today, but previous days will return an empty list.
This is what I use to get the data:
12 nov 2014, with type UsageStatsManager.INTERVAL_DAILY
startTime: 1415746800000
endTime: 1415833200000
mUsageStats size: 18
11 nov 2014, with type UsageStatsManager.INTERVAL_DAILY
startTime: 1415660400000
endTime: 1415746800000
mUsageStats size: 0
Is there a limit in the API that prevents me from getting older data or am I doing something wrong?
回答1:
You can get usage stats from whatever date you want (within the bounds set here) by using queryAndAggregateUsageStats()
method with correct milliseconds like this:
UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
if(mUsageStatsManager != null){
Calendar beginCal = Calendar.getInstance();
beginCal.add(Calendar.DATE, -1); // get yesterdays data
Calendar endCal = Calendar.getInstance();
Map<String, UsageStats> queryUsageStats = mUsageStatsManager.queryAndAggregateUsageStats(beginCal.getTimeInMillis(), endCal.getTimeInMillis());
}
来源:https://stackoverflow.com/questions/26882956/usagestatsmanager-returning-data-from-just-last-day-week-month-year