To collect application usage statistics, follow these steps:
- Get the
UsageStatsManager instance: Access the system service using Context.USAGE_STATS_SERVICE. - Query the statistics: Use the
queryUsageStats() method. This method requires three parameters:interval: The time interval by which the statistics are aggregated (e.g., UsageStatsManager.INTERVAL_DAILY).beginTime: The start of the time range (in milliseconds).endTime: The end of the time range (in milliseconds).
This method returns a List<UsageStats> containing the usage data for the specified period.
// 1. Get the UsageStatsManager instance
mUsageStatsManager = (UsageStatsManager) getActivity()
.getSystemService(Context.USAGE_STATS_SERVICE);
// 2. Query the statistics (e.g., for the last year)
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, -1);
List<UsageStats> queryUsageStats = mUsageStatsManager
.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, cal.getTimeInMillis(),
System.currentTimeMillis());