Java Code Examples for android.app.ActivityManager#RecentTaskInfo

The following examples show how to use android.app.ActivityManager#RecentTaskInfo . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AppTaskImpl.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public ActivityManager.RecentTaskInfo getTaskInfo() {
    checkCaller();

    synchronized (mService) {
        long origId = Binder.clearCallingIdentity();
        try {
            TaskRecord tr = mService.mStackSupervisor.anyTaskForIdLocked(mTaskId,
                    MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
            if (tr == null) {
                throw new IllegalArgumentException("Unable to find task ID " + mTaskId);
            }
            return mService.getRecentTasks().createRecentTaskInfo(tr);
        } finally {
            Binder.restoreCallingIdentity(origId);
        }
    }
}
 
Example 2
Source File: RecentTasks.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the list of {@link ActivityManager.AppTask}s.
 */
ArrayList<IBinder> getAppTasksList(int callingUid, String callingPackage) {
    final ArrayList<IBinder> list = new ArrayList<>();
    final int size = mTasks.size();
    for (int i = 0; i < size; i++) {
        final TaskRecord tr = mTasks.get(i);
        // Skip tasks that do not match the caller.  We don't need to verify
        // callingPackage, because we are also limiting to callingUid and know
        // that will limit to the correct security sandbox.
        if (tr.effectiveUid != callingUid) {
            continue;
        }
        Intent intent = tr.getBaseIntent();
        if (intent == null || !callingPackage.equals(intent.getComponent().getPackageName())) {
            continue;
        }
        ActivityManager.RecentTaskInfo taskInfo = createRecentTaskInfo(tr);
        AppTaskImpl taskImpl = new AppTaskImpl(mService, taskInfo.persistentId, callingUid);
        list.add(taskImpl.asBinder());
    }
    return list;
}
 
Example 3
Source File: ActivityStack.java    From container with GNU General Public License v3.0 6 votes vote down vote up
/**
 * App started in VA may be removed in OverView screen, then AMS.removeTask
 * will be invoked, all data struct about the task in AMS are released,
 * while the client's process is still alive. So remove related data in VA
 * as well. A new TaskRecord will be recreated in `onActivityCreated`
 */
private void optimizeTasksLocked() {
    // noinspection deprecation
    ArrayList<ActivityManager.RecentTaskInfo> recentTask = new ArrayList<>(mAM.getRecentTasks(Integer.MAX_VALUE,
            ActivityManager.RECENT_WITH_EXCLUDED | ActivityManager.RECENT_IGNORE_UNAVAILABLE));
    int N = mHistory.size();
    while (N-- > 0) {
        TaskRecord task = mHistory.valueAt(N);
        ListIterator<ActivityManager.RecentTaskInfo> iterator = recentTask.listIterator();
        boolean taskAlive = false;
        while (iterator.hasNext()) {
            ActivityManager.RecentTaskInfo info = iterator.next();
            if (info.id == task.taskId) {
                taskAlive = true;
                iterator.remove();
                break;
            }
        }
        if (!taskAlive) {
            mHistory.removeAt(N);
        }
    }
}
 
Example 4
Source File: AppInfoEngine.java    From AppPlus with MIT License 6 votes vote down vote up
/**
 * get recent running app list
 * @return recent running app list
 */
@Deprecated
public List<AppEntity> getRecentAppList() {
    List<AppEntity> list = new ArrayList<>();
    ActivityManager mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RecentTaskInfo> recentTasks = mActivityManager.getRecentTasks(10, 0);
    for (ActivityManager.RecentTaskInfo taskInfo : recentTasks) {
        Intent intent = taskInfo.baseIntent;
        ResolveInfo resolveInfo = mPackageManager.resolveActivity(intent, 0);
        if (resolveInfo == null)continue;
        String packageName = resolveInfo.activityInfo.packageName;
        if (isSystemApp(packageName)) continue;
        if (isShowSelf(packageName)) continue;
        AppEntity appEntity = DataHelper.getAppByPackageName(packageName);
        if (appEntity == null)continue;
        list.add (appEntity);
    }
    return list;
}
 
Example 5
Source File: RecentTasks.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new RecentTaskInfo from a TaskRecord.
 */
ActivityManager.RecentTaskInfo createRecentTaskInfo(TaskRecord tr) {
    // Compose the recent task info
    ActivityManager.RecentTaskInfo rti = new ActivityManager.RecentTaskInfo();
    rti.id = tr.getTopActivity() == null ? INVALID_TASK_ID : tr.taskId;
    rti.persistentId = tr.taskId;
    rti.baseIntent = new Intent(tr.getBaseIntent());
    rti.origActivity = tr.origActivity;
    rti.realActivity = tr.realActivity;
    rti.description = tr.lastDescription;
    rti.stackId = tr.getStackId();
    rti.userId = tr.userId;
    rti.taskDescription = new ActivityManager.TaskDescription(tr.lastTaskDescription);
    rti.lastActiveTime = tr.lastActiveTime;
    rti.affiliatedTaskId = tr.mAffiliatedTaskId;
    rti.affiliatedTaskColor = tr.mAffiliatedTaskColor;
    rti.numActivities = 0;
    if (!tr.matchParentBounds()) {
        rti.bounds = new Rect(tr.getOverrideBounds());
    }
    rti.supportsSplitScreenMultiWindow = tr.supportsSplitScreenWindowingMode();
    rti.resizeMode = tr.mResizeMode;
    rti.configuration.setTo(tr.getConfiguration());

    tr.getNumRunningActivities(mTmpReport);
    rti.numActivities = mTmpReport.numActivities;
    rti.baseActivity = (mTmpReport.base != null) ? mTmpReport.base.intent.getComponent() : null;
    rti.topActivity = (mTmpReport.top != null) ? mTmpReport.top.intent.getComponent() : null;

    return rti;
}
 
Example 6
Source File: TaskbarController.java    From Taskbar with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"deprecation", "JavaReflectionMemberAccess"})
@TargetApi(Build.VERSION_CODES.M)
private List<AppEntry> getAppEntriesUsingActivityManager(int maxNum) {
    ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RecentTaskInfo> usageStatsList = mActivityManager.getRecentTasks(maxNum, 0);
    List<AppEntry> entries = new ArrayList<>();

    for(int i = 0; i < usageStatsList.size(); i++) {
        ActivityManager.RecentTaskInfo recentTaskInfo = usageStatsList.get(i);
        if(recentTaskInfo.id != -1) {
            String packageName = recentTaskInfo.baseActivity.getPackageName();
            AppEntry newEntry = new AppEntry(
                    packageName,
                    null,
                    null,
                    null,
                    false
            );

            U.allowReflection();
            try {
                Field field = ActivityManager.RecentTaskInfo.class.getField("firstActiveTime");
                newEntry.setLastTimeUsed(field.getLong(recentTaskInfo));
            } catch (Exception e) {
                newEntry.setLastTimeUsed(i);
            }

            entries.add(newEntry);
        }
    }

    return entries;
}
 
Example 7
Source File: AppInfoEngine.java    From AppPlus with MIT License 5 votes vote down vote up
public List<AppEntity> getRecentAppListV1() {
    List<AppEntity> list = new ArrayList<>();
    ActivityManager mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RecentTaskInfo> recentTasks = mActivityManager.getRecentTasks(10, 0);
    for (ActivityManager.RecentTaskInfo taskInfo : recentTasks) {
        Intent intent = taskInfo.baseIntent;
        ResolveInfo resolveInfo = mPackageManager.resolveActivity(intent, 0);
        if (resolveInfo == null)continue;

        if (isSystemApp(resolveInfo.resolvePackageName)) continue;

        ActivityInfo activityInfo = resolveInfo.activityInfo;
        if(activityInfo==null)continue;

        if (isShowSelf(activityInfo.packageName)) continue;
        AppEntity entity = new AppEntity();
        Bitmap bitmap = drawableToBitmap(resolveInfo.loadIcon(mPackageManager));
        entity.setAppIconData(formatBitmapToBytes(bitmap));
        entity.setAppName(resolveInfo.loadLabel(mPackageManager).toString());
        entity.setPackageName(activityInfo.packageName);
        ApplicationInfo applicationInfo = activityInfo.applicationInfo;
        if (applicationInfo == null)continue;

        if(applicationInfo.publicSourceDir!= null){
            entity.setSrcPath(applicationInfo.publicSourceDir);
        }
        list.add(entity);
    }
    return list;
}
 
Example 8
Source File: AppStateTracker.java    From hover with Apache License 2.0 5 votes vote down vote up
public void trackTask(@NonNull ActivityManager.RecentTaskInfo taskToTrack) {
    mTaskToTrack = taskToTrack;
    Log.d(TAG, "Task ID: " + taskToTrack.id);
    Log.d(TAG, "Original activity: " + taskToTrack.origActivity);

    if (null != mTaskToTrack.origActivity) {
        mActivityStates.add(new ActivityState(mTaskToTrack.origActivity.getClassName(), ActivityState.State.CREATED));
    }

    mApplication.registerActivityLifecycleCallbacks(mActivityLifecycleCallback);
}
 
Example 9
Source File: SystemUtils.java    From q-municate-android with Apache License 2.0 5 votes vote down vote up
public static boolean isAppRunning() {
    final ActivityManager activityManager = (ActivityManager) App.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
    final List<ActivityManager.RecentTaskInfo> recentTasks = activityManager != null ? activityManager.getRecentTasks(Integer.MAX_VALUE, ActivityManager.RECENT_IGNORE_UNAVAILABLE) : null;
    ActivityManager.RecentTaskInfo recentTaskInfo = null;

    for (int i = 0; i < (recentTasks != null ? recentTasks.size() : 0); i++) {
        ComponentName componentName = recentTasks.get(i).baseIntent.getComponent();
        if (componentName != null && componentName.getPackageName().equals(App.getInstance().getPackageName())) {
            recentTaskInfo = recentTasks.get(i);
            break;
        }
    }
    return recentTaskInfo != null && recentTaskInfo.id > -1;
}
 
Example 10
Source File: RecentTasks.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * @return the list of recent tasks for presentation.
 */
ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
        boolean getTasksAllowed, boolean getDetailedTasks, int userId, int callingUid) {
    final boolean withExcluded = (flags & RECENT_WITH_EXCLUDED) != 0;

    if (!mService.isUserRunning(userId, FLAG_AND_UNLOCKED)) {
        Slog.i(TAG, "user " + userId + " is still locked. Cannot load recents");
        return ParceledListSlice.emptyList();
    }
    loadUserRecentsLocked(userId);

    final Set<Integer> includedUsers = mUserController.getProfileIds(userId);
    includedUsers.add(Integer.valueOf(userId));

    final ArrayList<ActivityManager.RecentTaskInfo> res = new ArrayList<>();
    final int size = mTasks.size();
    int numVisibleTasks = 0;
    for (int i = 0; i < size; i++) {
        final TaskRecord tr = mTasks.get(i);

        if (isVisibleRecentTask(tr)) {
            numVisibleTasks++;
            if (isInVisibleRange(tr, numVisibleTasks)) {
                // Fall through
            } else {
                // Not in visible range
                continue;
            }
        } else {
            // Not visible
            continue;
        }

        // Skip remaining tasks once we reach the requested size
        if (res.size() >= maxNum) {
            continue;
        }

        // Only add calling user or related users recent tasks
        if (!includedUsers.contains(Integer.valueOf(tr.userId))) {
            if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, not user: " + tr);
            continue;
        }

        if (tr.realActivitySuspended) {
            if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, activity suspended: " + tr);
            continue;
        }

        // Return the entry if desired by the caller.  We always return
        // the first entry, because callers always expect this to be the
        // foreground app.  We may filter others if the caller has
        // not supplied RECENT_WITH_EXCLUDED and there is some reason
        // we should exclude the entry.

        if (i == 0
                || withExcluded
                || (tr.intent == null)
                || ((tr.intent.getFlags() & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
                == 0)) {
            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;
                }
            }
            if (tr.autoRemoveRecents && tr.getTopActivity() == null) {
                // Don't include auto remove tasks that are finished or finishing.
                if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
                        "Skipping, auto-remove without activity: " + tr);
                continue;
            }
            if ((flags & RECENT_IGNORE_UNAVAILABLE) != 0 && !tr.isAvailable) {
                if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
                        "Skipping, unavail real act: " + tr);
                continue;
            }

            if (!tr.mUserSetupComplete) {
                // Don't include task launched while user is not done setting-up.
                if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
                        "Skipping, user setup not complete: " + tr);
                continue;
            }

            final ActivityManager.RecentTaskInfo rti = createRecentTaskInfo(tr);
            if (!getDetailedTasks) {
                rti.baseIntent.replaceExtras((Bundle)null);
            }

            res.add(rti);
        }
    }
    return new ParceledListSlice<>(res);
}
 
Example 11
Source File: ApplicationUtils.java    From QPM with Apache License 2.0 4 votes vote down vote up
/**
 * 通过ActivityManager拿到栈顶Activity的ClassName,然后跟列表中的Activity比对,获取栈顶Activity。
 * 注意:这种方式有个很严重的缺陷,如果某个Activity在栈里多次出现将导致判断错误,这时候将返回null。
 * 可靠性相对一般,不会返回错误结果。
 *
 * @param application application
 * @param activities  所有的Activity列表
 * @return 栈顶Activity,获取不到的时候将返回null,不会返回错误结果。
 * @throws ReflectUtils.ReflectException 可能会发生异常,强制要求处理异常情况。
 */
public static Activity getTopActivityByActivityManager(Context application
        , List<Activity> activities) throws ReflectUtils.ReflectException {
    ActivityManager activityManager = (ActivityManager) application
            .getSystemService(Context.ACTIVITY_SERVICE);
    String topActivity = null;
    String packageName = application.getPackageName();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        List<ActivityManager.AppTask> appTasks = activityManager.getAppTasks();
        for (int i = 0, size = appTasks.size(); i < size; i++) {
            ActivityManager.RecentTaskInfo taskInfo = appTasks.get(size - 1 - i).getTaskInfo();
            if (packageName.equals(taskInfo.baseActivity.getPackageName())) {
                topActivity = taskInfo.topActivity.getClassName();
            }
        }
    }
    if (TextUtils.isEmpty(topActivity)) {
        Log.i(TAG, "尝试通过getTopActivityByActivityManager获取Activity失败");
        return null;
    }

    boolean check = false;
    Activity result = null;
    if (activities != null) {
        for (Activity activity : activities) {
            if (topActivity.equals(activity.getClass().getName())) {
                if (check) {
                    // 出现重复Activity,返回null
                    Log.i(TAG, "尝试通过getTopActivityByActivityManager获取Activity失败");
                    return null;
                }
                check = true;
                result = activity;
            }
        }
    }
    if (result == null) {
        Log.w(TAG, "尝试通过getTopActivityByActivityManager获取Activity失败");
    } else {
        Log.i(TAG, "尝试通过getTopActivityByActivityManager获取Activity成功");
    }
    return result;
}
 
Example 12
Source File: Util.java    From Float-Bar with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * 核心方法,加载最近启动的应用程序 注意:这里我们取出的最近任务为 MAX_RECENT_TASKS +
 * 1个,因为有可能最近任务中包好Launcher2。 这样可以保证我们展示出来的 最近任务 为 MAX_RECENT_TASKS 个
 * 通过以下步骤,可以获得近期任务列表,并将其存放在了appInfos这个list中,接下来就是展示这个list的工作了。
 */
public static void reloadButtons(Service service, List<HashMap<String, Object>> appInfos, int appNumber) {
	int MAX_RECENT_TASKS = appNumber; // allow for some discards
	int repeatCount = appNumber;// 保证上面两个值相等,设定存放的程序个数

	/* 每次加载必须清空list中的内容 */
	appInfos.removeAll(appInfos);

	// 得到包管理器和activity管理器
	final Context context = service.getApplication();
	final PackageManager pm = context.getPackageManager();
	final ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

	// 从ActivityManager中取出用户最近launch过的 MAX_RECENT_TASKS + 1 个,以从早到晚的时间排序,
	// 注意这个 0x0002,它的值在launcher中是用ActivityManager.RECENT_IGNORE_UNAVAILABLE
	// 但是这是一个隐藏域,因此我把它的值直接拷贝到这里
	@SuppressWarnings("deprecation")
	final List<ActivityManager.RecentTaskInfo> recentTasks = am.getRecentTasks(MAX_RECENT_TASKS + 1, 0x0002);

	// 这个activity的信息是我们的launcher
	ActivityInfo homeInfo = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME).resolveActivityInfo(pm, 0);
	int numTasks = recentTasks.size();
	for (int i = 0; i < numTasks && (i < MAX_RECENT_TASKS); i++) {
		HashMap<String, Object> singleAppInfo = new HashMap<String, Object>();// 当个启动过的应用程序的信息
		final ActivityManager.RecentTaskInfo info = recentTasks.get(i);

		Intent intent = new Intent(info.baseIntent);
		if (info.origActivity != null) {
			intent.setComponent(info.origActivity);
		}
		/**
		 * 如果找到是launcher,直接continue,后面的appInfos.add操作就不会发生了
		 */
		if (homeInfo != null) {
			if (homeInfo.packageName.equals(intent.getComponent().getPackageName()) && homeInfo.name.equals(intent.getComponent().getClassName())) {
				MAX_RECENT_TASKS = MAX_RECENT_TASKS + 1;
				continue;
			}
		}
		// 设置intent的启动方式为 创建新task()【并不一定会创建】
		intent.setFlags((intent.getFlags() & ~Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) | Intent.FLAG_ACTIVITY_NEW_TASK);
		// 获取指定应用程序activity的信息(按我的理解是:某一个应用程序的最后一个在前台出现过的activity。)
		final ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
		if (resolveInfo != null) {
			final ActivityInfo activityInfo = resolveInfo.activityInfo;
			final String title = activityInfo.loadLabel(pm).toString();
			Drawable icon = activityInfo.loadIcon(pm);

			if (title != null && title.length() > 0 && icon != null) {
				singleAppInfo.put("title", title);
				singleAppInfo.put("icon", icon);
				singleAppInfo.put("tag", intent);
				singleAppInfo.put("packageName", activityInfo.packageName);
				appInfos.add(singleAppInfo);
			}
		}
	}
	MAX_RECENT_TASKS = repeatCount;
}
 
Example 13
Source File: Util.java    From Float-Bar with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * 核心方法,加载最近启动的应用程序 注意:这里我们取出的最近任务为 MAX_RECENT_TASKS +
 * 1个,因为有可能最近任务中包好Launcher2。 这样可以保证我们展示出来的 最近任务 为 MAX_RECENT_TASKS 个
 * 通过以下步骤,可以获得近期任务列表,并将其存放在了appInfos这个list中,接下来就是展示这个list的工作了。
 */
public static void reloadButtons(Service service, List<HashMap<String, Object>> appInfos, int appNumber) {
	int MAX_RECENT_TASKS = appNumber; // allow for some discards
	int repeatCount = appNumber;// 保证上面两个值相等,设定存放的程序个数

	/* 每次加载必须清空list中的内容 */
	appInfos.removeAll(appInfos);

	// 得到包管理器和activity管理器
	final Context context = service.getApplication();
	final PackageManager pm = context.getPackageManager();
	final ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

	// 从ActivityManager中取出用户最近launch过的 MAX_RECENT_TASKS + 1 个,以从早到晚的时间排序,
	// 注意这个 0x0002,它的值在launcher中是用ActivityManager.RECENT_IGNORE_UNAVAILABLE
	// 但是这是一个隐藏域,因此我把它的值直接拷贝到这里
	@SuppressWarnings("deprecation")
	final List<ActivityManager.RecentTaskInfo> recentTasks = am.getRecentTasks(MAX_RECENT_TASKS + 1, 0x0002);

	// 这个activity的信息是我们的launcher
	ActivityInfo homeInfo = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME).resolveActivityInfo(pm, 0);
	int numTasks = recentTasks.size();
	for (int i = 0; i < numTasks && (i < MAX_RECENT_TASKS); i++) {
		HashMap<String, Object> singleAppInfo = new HashMap<String, Object>();// 当个启动过的应用程序的信息
		final ActivityManager.RecentTaskInfo info = recentTasks.get(i);

		Intent intent = new Intent(info.baseIntent);
		if (info.origActivity != null) {
			intent.setComponent(info.origActivity);
		}
		/**
		 * 如果找到是launcher,直接continue,后面的appInfos.add操作就不会发生了
		 */
		if (homeInfo != null) {
			if (homeInfo.packageName.equals(intent.getComponent().getPackageName()) && homeInfo.name.equals(intent.getComponent().getClassName())) {
				MAX_RECENT_TASKS = MAX_RECENT_TASKS + 1;
				continue;
			}
		}
		// 设置intent的启动方式为 创建新task()【并不一定会创建】
		intent.setFlags((intent.getFlags() & ~Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) | Intent.FLAG_ACTIVITY_NEW_TASK);
		// 获取指定应用程序activity的信息(按我的理解是:某一个应用程序的最后一个在前台出现过的activity。)
		final ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
		if (resolveInfo != null) {
			final ActivityInfo activityInfo = resolveInfo.activityInfo;
			final String title = activityInfo.loadLabel(pm).toString();
			Drawable icon = activityInfo.loadIcon(pm);

			if (title != null && title.length() > 0 && icon != null) {
				singleAppInfo.put("title", title);
				singleAppInfo.put("icon", icon);
				singleAppInfo.put("tag", intent);
				singleAppInfo.put("packageName", activityInfo.packageName);
				appInfos.add(singleAppInfo);
			}
		}
	}
	MAX_RECENT_TASKS = repeatCount;
}