The issue is pretty clear, I want to query which app is currently being executed with queryEvents and looping over the running type events, unfortunately, this does not work for Android R+ devices. Per Android documentation, we need to add two system permissions:
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"
tools:ignore="QueryAllPackagesPermission"/>
But, even with these permissions, the query still returns nothing for Android 11 and onwards devices. the query function is also pretty simple:
(context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager).also {
val usageStatsManager: UsageStatsManager = it
val currentTimeMillis = System.currentTimeMillis()
val queryEvents =
usageStatsManager.queryEvents(currentTimeMillis - (1000*60*10), currentTimeMillis)
val event = UsageEvents.Event()
var str = ""
while (queryEvents.hasNextEvent()) {
queryEvents.getNextEvent(event)
Timber.d(event.className)
if (event.eventType == UsageEvents.Event.ACTIVITY_RESUMED) {
str = event.packageName
}
}
}