最近在应用中,需要获取最近获取的应用的列表以进行业务逻辑的判断,根据之前的经验迅速撸了一个:
public static List<ActivityManager.RecentTaskInfo> getRecentTask() {PackageManager pm = Application.getContext().getPackageManager();ActivityManager mActivityManager = (ActivityManager) Application.getContext().getSystemService(Context.ACTIVITY_SERVICE);List<ActivityManager.RecentTaskInfo> recentTasks = (List<ActivityManager.RecentTaskInfo>) mActivityManager.getRecentTasks(5, ActivityManager.RECENT_WITH_EXCLUDED);for (ActivityManager.RecentTaskInfo running : recentTasks) {Intent intent = running.baseIntent;ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);if (resolveInfo != null) {Log.e("getRecentTask", resolveInfo.activityInfo.packageName + "/n");//获取应用包名Log.e("getRecentTask", resolveInfo.loadLabel(pm).toString() + "/n");//获取应用名}}return recentTasks;}
在logcat中,发现只有两个应用,即当前应用和Launcher两个应用,查看原因,是因为ActivityManager.getRecentTasks 已经过期了,描述如下:
@deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method is no longer available to third party applications: the introduction of document-centric recents means it can leak personal information to the caller.
是因为安全性考虑,所以对于第三方的应用已经只暴露了安全的信息。但是由于系统就是我们自己的,所以需要研究一下。 由于是滴啊用的ActivityManager,所以直接打开ActivityManagerService,查看getRecentTasks,调用了
mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,callingUid);
mRecentTasks是RecentTasks的一个实例
getRecentTasksImpl(int maxNum, int flags,boolean getTasksAllowed, boolean getDetailedTasks, int userId, int callingUid)
其中关键的一段代码是:
if (!getTasksAllowed) {// If the caller doesn't have the GET_TASKS permission, then only// allow them to see a small subset of tasks -- their own and home.if (!tr.isActivityTypeHome() && tr.effectiveUid != callingUid) {if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, not allowed: " + tr);continue;}}
如果是自己的系统,把这个代码去掉就ok了
