How to get the amount of time an activity was in foreground in Android. For Ex. If WhatsApp was used 1 hour today, how to get that WhatsApp was active for one hour, programmatically.
The App usage statistics API allows app developers to collect statistics related to usage of the applications. This API provides more detailed usage information than the deprecated getRecentTasks(
) method.
To use this API, you must first declare the android.permission.PACKAGE_USAGE_STATS
permission in your manifest. The user must also enable access for this app through Settings > Security > Apps with usage access
.
To collect the statistics of the app usage, you need to first get the instance of UsageStatsManager by the following code:
mUsageStatsManager = (UsageStatsManager) getActivity()
.getSystemService(Context.USAGE_STATS_SERVICE);
Then you can retrieve the statistics of the app usage by the following method:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, -1);
List<UsageStats> queryUsageStats = mUsageStatsManager
.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, cal.getTimeInMillis(),
System.currentTimeMillis());
The first argument of the queryUsageStats()
is used for the time interval by which the stats are aggregated. The second and the third arguments are used for specifying the beginning and the end of the range of the stats to include in the results.
Here is a basic app code on GitHub showing how to use App usage statistics API to let users collect statistics related to usage of the applications.
Note: android.app.usage
required API level 21 or above.
Android have a built-in tool for that named "dumpsys".
Most of it's features are for developers throw ADB, but for your purposes you should dig into UsageStatsManager which will provide you the data you need about other apps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With