最近在应用中,需要获取最近获取的应用的列表以进行业务逻辑的判断,根据之前的经验迅速撸了一个:

    1. public static List<ActivityManager.RecentTaskInfo> getRecentTask() {
    2. PackageManager pm = Application.getContext().getPackageManager();
    3. ActivityManager mActivityManager = (ActivityManager) Application.getContext()
    4. .getSystemService(Context.ACTIVITY_SERVICE);
    5. List<ActivityManager.RecentTaskInfo> recentTasks = (List<ActivityManager.RecentTaskInfo>) mActivityManager
    6. .getRecentTasks(5, ActivityManager.RECENT_WITH_EXCLUDED);
    7. for (ActivityManager.RecentTaskInfo running : recentTasks) {
    8. Intent intent = running.baseIntent;
    9. ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
    10. if (resolveInfo != null) {
    11. Log.e("getRecentTask", resolveInfo.activityInfo.packageName + "/n");//获取应用包名
    12. Log.e("getRecentTask", resolveInfo.loadLabel(pm).toString() + "/n");//获取应用名
    13. }
    14. }
    15. return recentTasks;
    16. }

    在logcat中,发现只有两个应用,即当前应用和Launcher两个应用,查看原因,是因为ActivityManager.getRecentTasks 已经过期了,描述如下:

    1. @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,调用了

    1. mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,callingUid);

    mRecentTasks是RecentTasks的一个实例

    1. getRecentTasksImpl(int maxNum, int flags,
    2. boolean getTasksAllowed, boolean getDetailedTasks, int userId, int callingUid)

    其中关键的一段代码是:

    1. if (!getTasksAllowed) {
    2. // If the caller doesn't have the GET_TASKS permission, then only
    3. // allow them to see a small subset of tasks -- their own and home.
    4. if (!tr.isActivityTypeHome() && tr.effectiveUid != callingUid) {
    5. if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, not allowed: " + tr);
    6. continue;
    7. }
    8. }

    如果是自己的系统,把这个代码去掉就ok了