@TargetApi(Build.VERSION_CODES.LOLLIPOP) private void removeNonVisibleChromeTabbedRecentEntries() { Set<Integer> visibleTaskIds = getTaskIdsForVisibleActivities(); Context context = ContextUtils.getApplicationContext(); ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); PackageManager pm = getPackageManager(); for (AppTask task : manager.getAppTasks()) { RecentTaskInfo info = DocumentUtils.getTaskInfoFromTask(task); if (info == null) continue; String className = DocumentUtils.getTaskClassName(task, pm); // It is not easily possible to distinguish between tasks sitting on top of // ChromeLauncherActivity, so we treat them all as likely ChromeTabbedActivities and // close them to be on the cautious side of things. if ((TextUtils.equals(className, ChromeTabbedActivity.class.getName()) || TextUtils.equals(className, ChromeLauncherActivity.class.getName())) && !visibleTaskIds.contains(info.id)) { task.finishAndRemoveTask(); } } }
/** * Finishes tasks other than the one with the given ID that were started with the given data * in the Intent, removing those tasks from Recents and leaving a unique task with the data. * @param data Passed in as part of the Intent's data when starting the Activity. * @param canonicalTaskId ID of the task will be the only one left with the ID. * @return Intent of one of the tasks that were finished. */ public static Intent finishOtherTasksWithData(Uri data, int canonicalTaskId) { if (data == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return null; String dataString = data.toString(); Context context = ContextUtils.getApplicationContext(); ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.AppTask> tasksToFinish = new ArrayList<ActivityManager.AppTask>(); for (ActivityManager.AppTask task : manager.getAppTasks()) { RecentTaskInfo taskInfo = getTaskInfoFromTask(task); if (taskInfo == null) continue; int taskId = taskInfo.id; Intent baseIntent = taskInfo.baseIntent; String taskData = baseIntent == null ? null : taskInfo.baseIntent.getDataString(); if (TextUtils.equals(dataString, taskData) && (taskId == -1 || taskId != canonicalTaskId)) { tasksToFinish.add(task); } } return finishAndRemoveTasks(tasksToFinish); }
/** * Given an AppTask retrieves the task class name. * @param task The app task to use. * @param pm The package manager to use for resolving intent. * @return Fully qualified class name or null if we were not able to * determine it. */ public static String getTaskClassName(AppTask task, PackageManager pm) { RecentTaskInfo info = getTaskInfoFromTask(task); if (info == null) return null; Intent baseIntent = info.baseIntent; if (baseIntent == null) { return null; } else if (baseIntent.getComponent() != null) { return baseIntent.getComponent().getClassName(); } else { ResolveInfo resolveInfo = pm.resolveActivity(baseIntent, 0); if (resolveInfo == null) return null; return resolveInfo.activityInfo.name; } }
/** * Finishes tasks other than the one with the given task ID that were started with the given * tabId, leaving a unique task to own a Tab with that particular ID. * @param tabId ID of the tab to remove duplicates for. * @param canonicalTaskId ID of the task will be the only one left with the ID. * @return Intent of one of the tasks that were finished. */ public static Intent finishOtherTasksWithTabID(int tabId, int canonicalTaskId) { if (tabId == Tab.INVALID_TAB_ID || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { return null; } Context context = ApplicationStatus.getApplicationContext(); ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.AppTask> tasksToFinish = new ArrayList<ActivityManager.AppTask>(); for (ActivityManager.AppTask task : manager.getAppTasks()) { RecentTaskInfo taskInfo = getTaskInfoFromTask(task); if (taskInfo == null) continue; int taskId = taskInfo.id; Intent baseIntent = taskInfo.baseIntent; int otherTabId = ActivityDelegate.getTabIdFromIntent(baseIntent); if (otherTabId == tabId && (taskId == -1 || taskId != canonicalTaskId)) { tasksToFinish.add(task); } } return finishAndRemoveTasks(tasksToFinish); }
/** * Finishes tasks other than the one with the given ID that were started with the given data * in the Intent, removing those tasks from Recents and leaving a unique task with the data. * @param data Passed in as part of the Intent's data when starting the Activity. * @param canonicalTaskId ID of the task will be the only one left with the ID. * @return Intent of one of the tasks that were finished. */ public static Intent finishOtherTasksWithData(Uri data, int canonicalTaskId) { if (data == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return null; String dataString = data.toString(); Context context = ApplicationStatus.getApplicationContext(); ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.AppTask> tasksToFinish = new ArrayList<ActivityManager.AppTask>(); for (ActivityManager.AppTask task : manager.getAppTasks()) { RecentTaskInfo taskInfo = getTaskInfoFromTask(task); if (taskInfo == null) continue; int taskId = taskInfo.id; Intent baseIntent = taskInfo.baseIntent; String taskData = baseIntent == null ? null : taskInfo.baseIntent.getDataString(); if (TextUtils.equals(dataString, taskData) && (taskId == -1 || taskId != canonicalTaskId)) { tasksToFinish.add(task); } } return finishAndRemoveTasks(tasksToFinish); }
/** * Bring the task matching the given tab ID to the front. * @param tabId tab ID to search for. * @return Whether the task was successfully brought back. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) private static boolean relaunchTask(int tabId) { if (tabId == Tab.INVALID_TAB_ID) return false; Context context = ApplicationStatus.getApplicationContext(); ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); for (AppTask task : manager.getAppTasks()) { RecentTaskInfo info = DocumentUtils.getTaskInfoFromTask(task); if (info == null) continue; int id = ActivityDelegate.getTabIdFromIntent(info.baseIntent); if (id != tabId) continue; DocumentTabModelSelector.setPrioritizedTabId(id); if (!moveToFront(task)) continue; return true; } return false; }
/** * On opting out, remove all the old tasks from the recents. * @param fromDocument Whether any possible migration was from document mode to classic. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void cleanUpChromeRecents(boolean fromDocument) { ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.AppTask> taskList = am.getAppTasks(); PackageManager pm = getPackageManager(); for (int i = 0; i < taskList.size(); i++) { AppTask task = taskList.get(i); String className = DocumentUtils.getTaskClassName(task, pm); if (className == null) continue; RecentTaskInfo taskInfo = DocumentUtils.getTaskInfoFromTask(task); if (taskInfo == null) continue; // Skip the document activities if we are migrating from classic to document. boolean skip = !fromDocument && DocumentActivity.isDocumentActivity(className); if (!skip && (taskInfo.id != getTaskId())) { taskList.get(i).finishAndRemoveTask(); } } }
private String getReferringPackage() { try { List localList = ((ActivityManager)getSystemService("activity")).getRecentTasks(2, 0); if (localList.size() > 0) { Object localObject = ((ActivityManager.RecentTaskInfo)localList.get(0)).baseIntent.getComponent().getPackageName(); if ((getPackageName().equals(localObject)) && (localList.size() > 1)) { String str = ((ActivityManager.RecentTaskInfo)localList.get(1)).baseIntent.getComponent().getPackageName(); localObject = str; } return localObject; } } catch (Exception localException) { FinskyLog.e(localException, "Exception while getting package.", new Object[0]); } return null; }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) private void removeNonVisibleChromeTabbedRecentEntries() { Set<Integer> visibleTaskIds = getTaskIdsForVisibleActivities(); Context context = ContextUtils.getApplicationContext(); ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); PackageManager pm = getPackageManager(); for (AppTask task : manager.getAppTasks()) { RecentTaskInfo info = DocumentUtils.getTaskInfoFromTask(task); if (info == null) continue; String className = DocumentUtils.getTaskClassName(task, pm); // It is not easily possible to distinguish between tasks sitting on top of // ChromeLauncherActivity, so we treat them all as likely ChromeTabbedActivities and // close them to be on the cautious side of things. if ((ChromeTabbedActivity.isTabbedModeClassName(className) || TextUtils.equals(className, ChromeLauncherActivity.class.getName())) && !visibleTaskIds.contains(info.id)) { task.finishAndRemoveTask(); } } }
@Override public void run() { updateBlockedApps(); ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE); try { List<RecentTaskInfo> recentTasks = activityManager.getRecentTasks(1, ActivityManager.RECENT_IGNORE_UNAVAILABLE); if (recentTasks != null && recentTasks.size() > 0) { String packageName = recentTasks.get(0).baseIntent.getComponent().getPackageName(); if (isBlocked(packageName)) { Intent i = new Intent(getApplicationContext(), LockScreenActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION); i.putExtra("packageName", packageName); startActivity(i); } } } catch (Exception e) { Log.e("Foreground App", e.getMessage(), e); } }
@SuppressLint("NewApi") private boolean isMergedInstanceTaskRunning() { if (!FeatureUtilities.isTabModelMergingEnabled() || sMergedInstanceTaskId == 0) { return false; } ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (AppTask task : manager.getAppTasks()) { RecentTaskInfo info = DocumentUtils.getTaskInfoFromTask(task); if (info == null) continue; if (info.id == sMergedInstanceTaskId) return true; } return false; }
private int getLargestTaskIdFromRecents() { int biggestId = Tab.INVALID_TAB_ID; Context context = ContextUtils.getApplicationContext(); ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.AppTask task : activityManager.getAppTasks()) { RecentTaskInfo info = DocumentUtils.getTaskInfoFromTask(task); if (info == null) continue; biggestId = Math.max(biggestId, info.persistentId); } return biggestId; }
/** * Returns the RecentTaskInfo for the task, if the ActivityManager succeeds in finding the task. * @param task AppTask containing information about a task. * @return The RecentTaskInfo associated with the task, or null if it couldn't be found. */ public static RecentTaskInfo getTaskInfoFromTask(AppTask task) { RecentTaskInfo info = null; try { info = task.getTaskInfo(); } catch (IllegalArgumentException e) { Log.e(TAG, "Failed to retrieve task info: ", e); } return info; }
private int getLargestTaskIdFromRecents() { int biggestId = Tab.INVALID_TAB_ID; Context context = ApplicationStatus.getApplicationContext(); ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.AppTask task : activityManager.getAppTasks()) { RecentTaskInfo info = DocumentUtils.getTaskInfoFromTask(task); if (info == null) continue; biggestId = Math.max(biggestId, info.persistentId); } return biggestId; }
/** * Bring the task matching the given URL to the front if the task is retargetable. * @param incognito Whether or not the tab is incognito. * @param url URL that the tab would have been created for. If null, this param is ignored. * @return ID of the Tab if it was successfully relaunched, otherwise Tab.INVALID_TAB_ID. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) private static int relaunchTask(boolean incognito, String url) { if (TextUtils.isEmpty(url)) return Tab.INVALID_TAB_ID; Context context = ApplicationStatus.getApplicationContext(); ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); for (AppTask task : manager.getAppTasks()) { RecentTaskInfo info = DocumentUtils.getTaskInfoFromTask(task); if (info == null) continue; String initialUrl = ActivityDelegate.getInitialUrlForDocument(info.baseIntent); if (TextUtils.isEmpty(initialUrl) || !TextUtils.equals(initialUrl, url)) continue; int id = ActivityDelegate.getTabIdFromIntent(info.baseIntent); DocumentTabModelSelector.setPrioritizedTabId(id); if (!ChromeApplication.getDocumentTabModelSelector().getModel(incognito) .isRetargetable(id)) { continue; } if (!moveToFront(task)) continue; return id; } return Tab.INVALID_TAB_ID; }
public final boolean isContextPackageInBackground() { List localList = ((ActivityManager)this.mContext.getSystemService("activity")).getRecentTasks(1, 0); if (localList.size() == 0) { return true; } ActivityManager.RecentTaskInfo localRecentTaskInfo = (ActivityManager.RecentTaskInfo)localList.get(0); return (localRecentTaskInfo.baseIntent != null) && (localRecentTaskInfo.baseIntent.getComponent() != null) && (!this.mContext.getPackageName().equals(localRecentTaskInfo.baseIntent.getComponent().getPackageName())); }
public static Set<String> getForegroundPackages(Context paramContext) { HashSet localHashSet = new HashSet(); ActivityManager localActivityManager = (ActivityManager)paramContext.getSystemService("activity"); if (((PowerManager)paramContext.getSystemService("power")).isScreenOn()) { List localList2 = localActivityManager.getRecentTasks(1, 1); if (localList2.size() > 0) { ActivityManager.RecentTaskInfo localRecentTaskInfo = (ActivityManager.RecentTaskInfo)localList2.get(0); if (localRecentTaskInfo.baseIntent != null) { ComponentName localComponentName = localRecentTaskInfo.baseIntent.getComponent(); if (localComponentName != null) { localHashSet.add(localComponentName.getPackageName()); } } } } if (((Boolean)G.autoUpdateExcludeForegroundServices.get()).booleanValue()) { List localList1 = localActivityManager.getRunningServices(2147483647); if (localList1 != null) { int i = localList1.size(); for (int j = 0; j < i; j++) { ActivityManager.RunningServiceInfo localRunningServiceInfo = (ActivityManager.RunningServiceInfo)localList1.get(j); if (localRunningServiceInfo.foreground) { localHashSet.add(localRunningServiceInfo.service.getPackageName()); } } } } return localHashSet; }
@Override public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent, AccessibilityService accessibilityService) { AccessibilityNodeInfo sourceNodeInfo = accessibilityEvent.getSource(); if (sourceNodeInfo != null && sourceNodeInfo.getPackageName() != null) { if (this.mInstallerGenerator == null) { this.mInstallerGenerator = InstallerGenerator.getGenerator(sourceNodeInfo); } AccessibilityNodeInfo mParentNodeInfo = getParentNodeInfo(sourceNodeInfo); @SuppressWarnings("deprecation") List<?> recentTasks = ((ActivityManager) accessibilityService.getSystemService("activity")).getRecentTasks( 1, 0); if (recentTasks.size() != 0) { Intent intent = ((RecentTaskInfo) recentTasks.get(0)).baseIntent; if (intent != null) { ComponentName component = intent.getComponent(); String installPkgPath = InstallerUtils.getInstallPkgPath(intent); if (InstallerUtils.isAutoInstallable(installPkgPath, component)) { if (mWakeLock == null) { mWakeLock = newWakeLock(); } mWakeLock.acquire(300000); this.mInstallerGenerator.getInstaller().onInstall(installPkgPath, mParentNodeInfo, sourceNodeInfo, accessibilityEvent); } } } } }
public static Intent[] getIntentsFromTasks(List<RecentTaskInfo> tasks) { Intent[] intents = new Intent[tasks.size()]; int i = 0; for (RecentTaskInfo task : tasks) { intents[i++] = task.baseIntent; } return intents; }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ActivityManager service = (ActivityManager) getSystemService(ACTIVITY_SERVICE); List<RecentTaskInfo> recentTasks = service.getRecentTasks(5, ActivityManager.RECENT_WITH_EXCLUDED); for (RecentTaskInfo recentTaskInfo : recentTasks) { System.out.println(recentTaskInfo.baseIntent); } }
@Override public void run() { if (am != null) { List<RecentTaskInfo> currentTasks = am.getRecentTasks(1, ActivityManager.RECENT_WITH_EXCLUDED); if (!currentTasks.isEmpty()) { RecentTaskInfo updatedTask = currentTasks.get(0); if (currentRunningTask == null || !currentRunningTask.baseIntent.filterEquals(updatedTask.baseIntent)) { endCurrentTask(); currentRunningTask = updatedTask; currentRunningTaskStartTime = TimeUtil.getTimestamp(); } } getHandler().postDelayed(this, TimeUtil.secondsToMillis(pollInterval)); } }
private void sendData(RecentTaskInfo taskInfo, BigDecimal timestamp, BigDecimal duration) { Gson gson = getGson(); JsonObject data = new JsonObject(); data.add(TIMESTAMP, gson.toJsonTree(timestamp)); data.add(DURATION, gson.toJsonTree(duration)); data.add(TASK_INFO, gson.toJsonTree(taskInfo)); sendData(data); }
private void updateCurrentlyOpenTabsWhenDatabaseReady() { final int currentTabId = ActivityDelegate.getTabIdFromIntent(mActivity.getIntent()); ActivityManager am = (ActivityManager) mActivity.getSystemService( Activity.ACTIVITY_SERVICE); List<ActivityManager.AppTask> taskList = am.getAppTasks(); mCurrentlyOpenTabs.clear(); for (int i = 0; i < taskList.size(); i++) { RecentTaskInfo taskInfo = DocumentUtils.getTaskInfoFromTask(taskList.get(i)); if (taskInfo == null) continue; final Intent baseIntent = taskInfo.baseIntent; final int tabId = ActivityDelegate.getTabIdFromIntent(baseIntent); String url = mTabModel.getCurrentUrlForDocument(tabId); if (TextUtils.isEmpty(url) || url.startsWith(UrlConstants.CHROME_NATIVE_SCHEME)) { continue; } CharSequence description = taskInfo.description; String title = description != null ? description.toString() : ""; final Runnable startNewDocument = new Runnable() { @Override public void run() { Intent newIntent = Tab.createBringTabToFrontIntent(tabId); newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT); mActivity.startActivity(newIntent); } }; Runnable onClickRunnable = new Runnable() { @Override public void run() { if (mDialog != null) mDialog.dismiss(); if (currentTabId != tabId) { ThreadUtils.postOnUiThreadDelayed(startNewDocument, NEW_TAB_DELAY_MS); } } }; mCurrentlyOpenTabs.add(new CurrentlyOpenTab(tabId, url, title, onClickRunnable)); } }
/** * Determine whether the incognito profile needs to be destroyed as part of startup. This is * only needed on L+ when it is possible to swipe away tasks from Android recents without * killing the process. When this occurs, the normal incognito profile shutdown does not * happen, which can leave behind incognito cookies from an existing session. */ @SuppressLint("NewApi") private boolean shouldDestroyIncognitoProfile() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return false; Context context = ContextUtils.getApplicationContext(); ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); PackageManager pm = context.getPackageManager(); Set<Integer> tabbedModeTaskIds = new HashSet<>(); for (AppTask task : manager.getAppTasks()) { RecentTaskInfo info = DocumentUtils.getTaskInfoFromTask(task); if (info == null) continue; String className = DocumentUtils.getTaskClassName(task, pm); if (isTabbedModeClassName(className)) { tabbedModeTaskIds.add(info.id); } } if (tabbedModeTaskIds.size() == 0) { return Profile.getLastUsedProfile().hasOffTheRecordProfile(); } List<WeakReference<Activity>> activities = ApplicationStatus.getRunningActivities(); for (int i = 0; i < activities.size(); i++) { Activity activity = activities.get(i).get(); if (activity == null) continue; tabbedModeTaskIds.remove(activity.getTaskId()); } // If all tabbed mode tasks listed in Android recents are alive, check to see if // any have incognito tabs exist. If all are alive and no tabs exist, we should ensure that // we delete the incognito profile if one is around still. if (tabbedModeTaskIds.size() == 0) { return TabWindowManager.getInstance().canDestroyIncognitoProfile() && Profile.getLastUsedProfile().hasOffTheRecordProfile(); } // In this case, we have tabbed mode activities listed in recents that do not have an // active running activity associated with them. We can not accurately get an incognito // tab count as we do not know if any incognito tabs are associated with the yet unrestored // tabbed mode. Thus we do not proactivitely destroy the incognito profile. return false; }
/** * Returns the baseIntent of the RecentTaskInfo associated with the given task. * @param task Task to get the baseIntent for. * @return The baseIntent, or null if it couldn't be retrieved. */ public static Intent getBaseIntentFromTask(AppTask task) { RecentTaskInfo info = getTaskInfoFromTask(task); return info == null ? null : info.baseIntent; }