user14536109
user14536109

Reputation:

How to get the package name of the current foreground activity?

I looked around at similar questions and every answer has one thing in common and that's that they don't work on APIs greater than 21.

There's this snippet that only works on APIs of 20 and lower:

ActivityManager am = (ActivityManager) getApplicationContext().getSystemService(Activity.ACTIVITY_SERVICE);
String packageName = am.getRunningTasks(1).get(0).topActivity.getPackageName();

And then there's the one that uses UsageStats. The bizarre thing is that despite being the most commonly posted answer on SO this method only works on one single API and that's 21, i.e. Android 5.0. It doesn't even work on Android 5.1.

Is there a modern way that works? Thanks for reading.

Upvotes: 2

Views: 2064

Answers (1)

Amirhosein
Amirhosein

Reputation: 4446

The following method that returns Observable of current top package likely work:

    public Observable<String> topPackageNameObservable() {
    return Observable.fromCallable(() -> {
        String topPackageName = "";
        ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
                List<UsageStats> stats =
                        mUsageStatsManager.queryUsageStats(
                                UsageStatsManager.INTERVAL_DAILY,
                                System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1),
                                System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1));
                if (stats != null) {
                    SortedMap<Long, UsageStats> mySortedMap = new TreeMap<>();
                    for (UsageStats usageStats : stats) {
                        mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
                    }
                    if (!mySortedMap.isEmpty()) {
                        topPackageName = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
                    }
                } else {
                    topPackageName = mActivityManager.getRunningAppProcesses().get(0).processName;
                }
            } else {
                topPackageName = mActivityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return topPackageName;
    });

}

Upvotes: 2

Related Questions