I'm running a foreground service which samples the user's app usage in a timely manner.
I noticed a weird behavior of the UsageStats getTotalTimeInForeground(..)
function - it seems that the stats are not updated for the currently foreground application until it goes to the background.
Code:
UsageStatsManager usageStatsManager = (UsageStatsManager)context.getSystemService(Context.USAGE_STATS_SERVICE);
Map<String, UsageStats> queryUsageStats = usageStatsManager.queryAndAggregateUsageStats(UsageStatsManager.INTERVAL_DAILY, 0, System.currentTimeMillis());
long totalTimeUsageInMillis = queryUsageStats.get("com.sample.app").
getTotalTimeInForeground();
After each iteration - totalTimeUsageInMillis
is not affected while the com.sample.app
is in the foreground.
Once I leave com.sample.app
- my service gets the updated value
I can workaround this issue by keeping a counter for the currently-running (=foreground) app and add it to the result until the user switches app, but I prefer not to add overhead to the app.
The following screenshot was taken from a tester I built and shows 2 calls taken with 1 minute intervals: