Background
I want usage data about different apps on my company's tablets. The optimal solution spans the greatest amount of time. I read here that I should be able to get data for up to two years past with some of the UsageStatsManager queries.
What I've tried
I figured that UsageStatsManager.queryAndAggregateUsageStats(..) would do the trick but I found it would only return intervals of up to around one week. Since the "aggregate" query wasn't working I tried this code so I could explicitly declare bucket size:
val appStats = statsManager.queryUsageStats(UsageStatsManager.INTERVAL_YEARLY, 0, Long.MAX_VALUE)
I tried using multiple different time intervals including:
val appStats = statsManager.queryUsageStats(UsageStatsManager.INTERVAL_YEARLY,curTime - TimeUnit.DAYS.toMillis(730), curTime)
The longest interval I am able to get is around one week.
Example log:
Name: com.example.myusagestatsmanagertestapp --> Beginning: Tue Jul 20 10:16:41 CDT 2021 --> Ending: Mon Jul 26 21:20:47 CDT 2021 --> Time in FG: 186
Where I am now
I must be doing something wrong as the INTERVAL_YEARLY constant isn't deprecated. However, I have deduced from other posts like this one or this one that this API has been sketchy.
My next move is to build my own stats via UsageStatsManager.queryEvents(..) which seems more consistent and clear cut.
Questions
- What is the problem?
- Are the UsageStatsManager data even worth trusting?
Specs and Code
My device is Android 9.0 Samsung Galaxy Active Tab2.
Here is the full function!
private fun getIndividualAppUsageDuration(
statsManager: UsageStatsManager,
curTime: Long
): Map<String, Long> {
val appMap: MutableMap<String, Long> = mutableMapOf()
val apps = statsManager.queryUsageStats(UsageStatsManager.INTERVAL_MONTHLY,curTime - TimeUnit.DAYS.toMillis(60), curTime)
for(app in apps) {
appMap[app.packageName] = app.totalTimeInForeground
Log.d("TAG_1", "...\n" +
"Name: ${app.packageName}\n" +
"--> Beginning: ${stringifyMilli(app.firstTimeStamp)}\n" +
"--> Ending: ${stringifyMilli(app.lastTimeStamp)}\n" +
"--> Time in FG: ${TimeUnit.MILLISECONDS.toMinutes(app.totalTimeInForeground)}" )
}
return appMap
}
The permissions I use!
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions" />