How to get the packagename of the app that is running in the foreground on an Amazon firetv stick 4K Max?

63 Views Asked by At

I’m messing around with this problem for a long time and I’m very clueless how to get this going.

I want to create an app for the Amazon firetv stick 4k max (Android 9 - API level 28), that monitors if one specific app is in the foreground (or gets opened).

Do you have any ideas how to get the packagename of the app that is currently running in the foreground and that's actually working on an Amazon firetv stick 4K Max?

I would really appreciate your help!

I have found a way that works for other Android 9 devices by using the UsageStatsManager, but that does not seem to work for the stick. Here is what I tried:

public String packageInForeground() {
        // Get the UsageStatsManager
        UsageStatsManager usageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);

        // Get the usage events for the last 5 seconds
        long currentTime = System.currentTimeMillis();
        List<UsageStats> usageStatsList = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, currentTime - 5000, currentTime);

        // Find the latest usage event
        UsageStats latestUsageStats = null;
        if (usageStatsList != null) {
            for (UsageStats usageStats : usageStatsList) {
                if (latestUsageStats == null || usageStats.getLastTimeUsed() > latestUsageStats.getLastTimeUsed()) {
                    latestUsageStats = usageStats;
                }
            }
        }

        // Get the package name of the current foreground app
        String currentForegroundApp = latestUsageStats != null ? latestUsageStats.getPackageName() : "";
        Log.d("Service", "Current foreground app: " + currentForegroundApp);

        return currentForegroundApp;
    }

There is also a way to use the ActivityManager, but it will only show my own packagename if my own app is in the foreground, but does not show the packagename of other apps, if I open them. Here is what I tried:

public String packageInForeground() {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
        String packageName = "";
        if (runningAppProcesses != null && runningAppProcesses.size() > 0) {
            for (ActivityManager.RunningAppProcessInfo processInfo : runningAppProcesses) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    packageName = processInfo.processName.split(":")[0];
                    Log.d("LockService", "Package Name: " + packageName);
                    break;
                }
            }
        }
        return packageName;
    }
0

There are 0 best solutions below