The application usage statistics API allows application developers to collect application related statistics. This API provides more detailed usage information than the deprecated getRecentTasks( ) method.
To use this API, you must first declare android.permission.PACKAGE_USAGE_STATS permission in your manifest. The user must also allow access for this application through Settings > Security > Apps with usage access .
To collect usage statistics for an application, you first need to get an instance of UsageStatsManager using the following code:
mUsageStatsManager = (UsageStatsManager) getActivity() .getSystemService(Context.USAGE_STATS_SERVICE);
Then you can get application usage statistics in the following way:
Calendar cal = Calendar.getInstance(); cal.add(Calendar.YEAR, -1); List<UsageStats> queryUsageStats = mUsageStatsManager .queryUsageStats(UsageStatsManager.INTERVAL_DAILY, cal.getTimeInMillis(), System.currentTimeMillis());
The first argument to queryUsageStats() used for the time interval with which statistics are aggregated. The second and third arguments are used to indicate the beginning and end of the range of statistics to include in the results.
Here is the basic GitHub application code showing how to use the application usage statistics API so that users can collect application usage statistics.
Note. android.app.usage requires API level 21 or higher.
source share