catspeake
在API 21或更高版本中获取“运行应用”的最佳解决方案是尝试以下方法。这项工作对我来说private String retriveNewApp() { if (VERSION.SDK_INT >= 21) { String currentApp = null; UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE); long time = System.currentTimeMillis(); List<UsageStats> applist = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time); if (applist != null && applist.size() > 0) { SortedMap<Long, UsageStats> mySortedMap = new TreeMap<>(); for (UsageStats usageStats : applist) { mySortedMap.put(usageStats.getLastTimeUsed(), usageStats); } if (mySortedMap != null && !mySortedMap.isEmpty()) { currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName(); } } Log.e(TAG, "Current App in foreground is: " + currentApp); return currentApp; } else { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); String mm=(manager.getRunningTasks(1).get(0)).topActivity.getPackageName(); Log.e(TAG, "Current App in foreground is: " + mm); return mm; }}