I'm trying to detect which app is currently in the foreground using UsageStatsManager. My implementation works fine in most cases, but there's an issue:
When an app is minimized (swiped up to the recent apps view) and then reopened, UsageStatsManager registers the launcher instead of the actual foreground app.
This prevents my logic from correctly identifying the reopened app.
Here’s the code I'm using in a foreground service to periodically check the current foreground app:
val mUsageStatsManager = context.getSystemService(Service.USAGE_STATS_SERVICE) as UsageStatsManager
val time = System.currentTimeMillis()
// Query usage events for the past hour
val usageEvents = mUsageStatsManager.queryEvents(time - 3600 * 1000, time)
var lastForegroundApp: String? = null
// Iterate through events to find the latest MOVE_TO_FOREGROUND
while (usageEvents.hasNextEvent()) {
usageEvents.getNextEvent(event)
if (event.eventType == UsageEvents.Event.MOVE_TO_FOREGROUND) {
lastForegroundApp = event.packageName
}
}
This works well except when an app is reopened from the recent apps screen. In that case, lastForegroundApp incorrectly returns the launcher or my own app instead of the actual app in the foreground.
Is there a more reliable way to detect the correct foreground app in this scenario?
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745284249a4620464.html
评论列表(0条)