UsageStatsManager从最后一天/周/月/年返回数据?

时间:2014-11-12 09:02:25

标签: android android-5.0-lollipop

我试图从UsageStats查询UsageStatsManager。 我已经建立了一个DateUtils课程,为我提供了获取每天/每月/每年(一周即将到来)的开始和结束时间的方法,如下所示:

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();
}

我使用这些长篇查询UsageStats不同日期:

 mUsageStats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, startTime, endTime);

我今天可以获取数据,但前几天会返回一个空列表。

这是我用来获取数据的原因:

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

API中是否存在限制,导致我无法获取较旧的数据或我做错了什么?

1 个答案:

答案 0 :(得分:0)

通过使用queryAndAggregateUsageStats()方法(正确的毫秒数),您可以从任意日期(在here范围内)获取使用情况统计信息,如下所示:

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());
}