I am developing a digital wellbeing app and I have to get accurate data about how much time user spends in apps in a given day. If now is 16.05.2023 12:21 we are calculating the time since 16.05.2023 00:00 till now per each application and show the results in a Map.
Here is how i am currently approaching this problem using UsageStats available since Api level 21 (doc. https://developer.android.com/reference/android/app/usage/UsageStats)
private void getAppUsageStats() { UsageStatsManager usageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
Calendar calendar = Calendar.getInstance();
long endTime = calendar.getTimeInMillis(); // current moment
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
long startTime = calendar.getTimeInMillis(); // start of the current day
List<UsageStats> usageStatsList = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, startTime, endTime);
Map<String, Long> usageMap = new HashMap<>();
for (UsageStats usageStats : usageStatsList) {
long timeInForeground = usageStats.getTotalTimeInForeground();
if (timeInForeground > 0) {
usageMap.put(usageStats.getPackageName(), timeInForeground);
}
}
Map<String, String> formattedUsageMap = formatUsageMap(usageMap);
System.out.println("Usage Map: " + formattedUsageMap);
displayUsageStats(formattedUsageMap);
}
However the problem with this approach is inaccuracy in calculating the time spend in the apps when we compare the usage seen on Digital Wellbeing app https://play.google.com/store/apps/details?id=com.google.android.apps.wellbeing&hl=en_US&pli=1 which is probably correct given the time I spend in apps. Switching to other methods from UsageStats api like getTotalTimeVisible() or getTotalTimeForegroundServiceUsed() doesn't solve this issue.
For example - This is Usage Map from this method regarding my current day app usage:
Usage Map: {com.chess=00:13:39, com.facebook.orca=00:19:21, com.digitalwellbeingexperiments.toolkit.applist=00:01:16, pl.mbank=00:09:57, com.facebook.katana=00:01:28, pl.ing.mojeing=00:00:20, com.samsung.android.calendar=00:07:42, com.android.chrome=00:32:12, com.google.android.apps.docs.editors.sheets=00:01:13, com.google.android.youtube=00:02:50, }
And this is real usage based on Digital Wellbeing app:
Youtube 1h 56 min
Chrome 25 min
Messenger 10 min
Facebook 1 min
Gmail 1 min
So it seems that my method somehow combined usages from this day and day earlier (because i did use chess 13 min and mbank 10 min yesterday) but it shouldn't because i set start to the beginning of this day and also it didn't calculated usage for youtube whatsoever.
Please any suggestion will be highly appreciated ;)