I have always successfully been able to detect the foreground app on all Android versions, up to Android 14. On Android 14, somehow it seems as if the UsageStatsManager
is not returning all of the most recent data on app usage.
The way I detect foreground apps:
UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
String fgApp = null;
UsageEvents usageEvents = usageStatsManager.queryEvents(time - MyTime.MINUTE_MILLIS, time);
UsageEvents.Event event = new UsageEvents.Event();
while (usageEvents.hasNextEvent()) {
usageEvents.getNextEvent(event);
// MOVE_TO_FOREGROUND is deprecated since Android Q (API 29) in favor of ACTIVITY_RESUMED:
// //https://developer.android.com/reference/android/app/usage/UsageEvents.Event#MOVE_TO_FOREGROUND
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (event.getEventType() == UsageEvents.Event.ACTIVITY_RESUMED) {
fgApp = event.getPackageName();
}
} else { // Else we use MOVE_TO_FOREGROUND.
if (event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
fgApp = event.getPackageName();
}
}
}
return fgApp;
Another way to detect the foreground app is through the getLastTimeUsed()
method from the UsageStats object, as explained here.
None of these methods work anymore on Android 14: the UsageStatsManager does not return the latest elements, so no objects are returned with a getLastTimeUsed()
that matches the actual app that's in the foreground (e.g. it will say Nexus Launcher is in the foreground based on the data, while it's actually YouTube).
Any ideas why? I could not find any information in the behavior changes for Android 14 either. It seems like a bug to me.
Update: I have confirmed this is indeed an issue with UsageStatsManager on Android 14. I've submitted a bug report including a minimum reproducible example in Google's Issue Tracker here - if you experience the same issues, please upvote.