<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions" />
如果不加
tools:ignore="ProtectedPermissions"
会给出一些系统权限的危险提示。
使用方法: 根据版本的不同,调用不同的方法。
// if the sdk >= 21. It can only use getRunningAppProcesses to get task top package name
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usage = (UsageStatsManager)getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> stats = usage.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 10, time);
if (stats != null) {
SortedMap<Long, UsageStats> runningTask = new TreeMap<Long,UsageStats>();
for (UsageStats usageStats : stats) {
runningTask.put(usageStats.getLastTimeUsed(), usageStats);
}
if (runningTask.isEmpty()) {
continue;
}
packagename = runningTask.get(runningTask.lastKey()).getPackageName();
}
} else {// if sdk <= 20, can use getRunningTasks
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
//4.获取正在开启应用的任务栈
List<ActivityManager.RunningTaskInfo> runningTasks = am.getRunningTasks(1);
ActivityManager.RunningTaskInfo runningTaskInfo = runningTasks.get(0);
//5.获取栈顶的activity,然后在获取此activity所在应用的包名
packagename = runningTaskInfo.topActivity.getPackageName();
}