安卓5.0屏蔽了getRunningAppProcesses@ActivityManager方法,因此不能使用該方法完成獲取頂層應用包名的需求。若要在5.0及以後的版本上獲取頂層app的包名,可以使用Context的“usagestats”服務完成該需求。
但需注意以下幾點:
- 有的手機廠商會屏蔽“usagestats”這一服務,據悉會有魅族、小米等廠商,但我的MX5上是可以正常獲取的。
- 該服務需要在manifest中新增<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />這一權限 - 該服務需要獲取系統的“有權查看使用情況的應用”這一權限,該權限需要用戶手動開啓,啓動的Intent爲:Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
附上代碼(該代碼是從https://blog.csdn.net/dhl_1986/article/details/51305858 裏獲取的):
public static String getTaskPackname(Context context) {
String currentApp = "CurrentNULL";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager) context.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<Long, UsageStats>();
for (UsageStats usageStats : appList) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
} else {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
currentApp = tasks.get(0).processName;
}
Log.e("TAG", "Current App in foreground is: " + currentApp);
return currentApp;
}