SystemServicesProxy.java revision ee44595bd53c4f3f6a2eeb664ea96a268636c041
1/* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.systemui.recents.misc; 18 19import android.app.ActivityManager; 20import android.app.ActivityManagerNative; 21import android.app.ActivityOptions; 22import android.app.AppGlobals; 23import android.app.IActivityManager; 24import android.app.SearchManager; 25import android.appwidget.AppWidgetHost; 26import android.appwidget.AppWidgetManager; 27import android.appwidget.AppWidgetProviderInfo; 28import android.content.ComponentName; 29import android.content.ContentResolver; 30import android.content.Context; 31import android.content.Intent; 32import android.content.pm.ActivityInfo; 33import android.content.pm.IPackageManager; 34import android.content.pm.PackageManager; 35import android.content.pm.ResolveInfo; 36import android.content.res.Resources; 37import android.graphics.Bitmap; 38import android.graphics.BitmapFactory; 39import android.graphics.Canvas; 40import android.graphics.Color; 41import android.graphics.Paint; 42import android.graphics.Point; 43import android.graphics.PorterDuff; 44import android.graphics.PorterDuffXfermode; 45import android.graphics.Rect; 46import android.graphics.drawable.ColorDrawable; 47import android.graphics.drawable.Drawable; 48import android.os.Bundle; 49import android.os.ParcelFileDescriptor; 50import android.os.RemoteException; 51import android.os.UserHandle; 52import android.provider.Settings; 53import android.util.Log; 54import android.util.Pair; 55import android.view.Display; 56import android.view.DisplayInfo; 57import android.view.SurfaceControl; 58import android.view.WindowManager; 59import android.view.accessibility.AccessibilityManager; 60import com.android.systemui.recents.Constants; 61 62import java.io.IOException; 63import java.util.ArrayList; 64import java.util.Iterator; 65import java.util.List; 66import java.util.Random; 67 68/** 69 * Acts as a shim around the real system services that we need to access data from, and provides 70 * a point of injection when testing UI. 71 */ 72public class SystemServicesProxy { 73 final static String TAG = "SystemServicesProxy"; 74 75 final static BitmapFactory.Options sBitmapOptions; 76 77 AccessibilityManager mAccm; 78 ActivityManager mAm; 79 IActivityManager mIam; 80 AppWidgetManager mAwm; 81 PackageManager mPm; 82 IPackageManager mIpm; 83 SearchManager mSm; 84 WindowManager mWm; 85 Display mDisplay; 86 String mRecentsPackage; 87 ComponentName mAssistComponent; 88 89 Bitmap mDummyIcon; 90 int mDummyThumbnailWidth; 91 int mDummyThumbnailHeight; 92 Paint mBgProtectionPaint; 93 Canvas mBgProtectionCanvas; 94 95 static { 96 sBitmapOptions = new BitmapFactory.Options(); 97 sBitmapOptions.inMutable = true; 98 } 99 100 /** Private constructor */ 101 public SystemServicesProxy(Context context) { 102 mAccm = AccessibilityManager.getInstance(context); 103 mAm = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 104 mIam = ActivityManagerNative.getDefault(); 105 mAwm = AppWidgetManager.getInstance(context); 106 mPm = context.getPackageManager(); 107 mIpm = AppGlobals.getPackageManager(); 108 mSm = (SearchManager) context.getSystemService(Context.SEARCH_SERVICE); 109 mWm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); 110 mDisplay = mWm.getDefaultDisplay(); 111 mRecentsPackage = context.getPackageName(); 112 113 // Get the dummy thumbnail width/heights 114 Resources res = context.getResources(); 115 int wId = com.android.internal.R.dimen.thumbnail_width; 116 int hId = com.android.internal.R.dimen.thumbnail_height; 117 mDummyThumbnailWidth = res.getDimensionPixelSize(wId); 118 mDummyThumbnailHeight = res.getDimensionPixelSize(hId); 119 120 // Create the protection paints 121 mBgProtectionPaint = new Paint(); 122 mBgProtectionPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP)); 123 mBgProtectionPaint.setColor(0xFFffffff); 124 mBgProtectionCanvas = new Canvas(); 125 126 // Resolve the assist intent 127 Intent assist = mSm.getAssistIntent(context, false); 128 if (assist != null) { 129 mAssistComponent = assist.getComponent(); 130 } 131 132 if (Constants.DebugFlags.App.EnableSystemServicesProxy) { 133 // Create a dummy icon 134 mDummyIcon = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); 135 mDummyIcon.eraseColor(0xFF999999); 136 } 137 } 138 139 /** Returns a list of the recents tasks */ 140 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int numLatestTasks, int userId) { 141 if (mAm == null) return null; 142 143 // If we are mocking, then create some recent tasks 144 if (Constants.DebugFlags.App.EnableSystemServicesProxy) { 145 ArrayList<ActivityManager.RecentTaskInfo> tasks = 146 new ArrayList<ActivityManager.RecentTaskInfo>(); 147 int count = Math.min(numLatestTasks, Constants.DebugFlags.App.SystemServicesProxyMockTaskCount); 148 for (int i = 0; i < count; i++) { 149 // Create a dummy component name 150 int packageIndex = i % Constants.DebugFlags.App.SystemServicesProxyMockPackageCount; 151 ComponentName cn = new ComponentName("com.android.test" + packageIndex, 152 "com.android.test" + i + ".Activity"); 153 String description = "" + i + " - " + 154 Long.toString(Math.abs(new Random().nextLong()), 36); 155 // Create the recent task info 156 ActivityManager.RecentTaskInfo rti = new ActivityManager.RecentTaskInfo(); 157 rti.id = rti.persistentId = i; 158 rti.baseIntent = new Intent(); 159 rti.baseIntent.setComponent(cn); 160 rti.description = description; 161 rti.firstActiveTime = rti.lastActiveTime = i; 162 if (i % 2 == 0) { 163 rti.taskDescription = new ActivityManager.TaskDescription(description, 164 Bitmap.createBitmap(mDummyIcon), 165 0xFF000000 | (0xFFFFFF & new Random().nextInt())); 166 } else { 167 rti.taskDescription = new ActivityManager.TaskDescription(); 168 } 169 tasks.add(rti); 170 } 171 return tasks; 172 } 173 174 // Remove home/recents/excluded tasks 175 int minNumTasksToQuery = 10; 176 int numTasksToQuery = Math.max(minNumTasksToQuery, numLatestTasks); 177 List<ActivityManager.RecentTaskInfo> tasks = mAm.getRecentTasksForUser(numTasksToQuery, 178 ActivityManager.RECENT_IGNORE_HOME_STACK_TASKS | 179 ActivityManager.RECENT_IGNORE_UNAVAILABLE | 180 ActivityManager.RECENT_INCLUDE_PROFILES | 181 ActivityManager.RECENT_WITH_EXCLUDED, userId); 182 boolean isFirstValidTask = true; 183 Iterator<ActivityManager.RecentTaskInfo> iter = tasks.iterator(); 184 while (iter.hasNext()) { 185 ActivityManager.RecentTaskInfo t = iter.next(); 186 187 // NOTE: The order of these checks happens in the expected order of the traversal of the 188 // tasks 189 190 // Check the first non-recents task, include this task even if it is marked as excluded 191 // from recents. In other words, only remove excluded tasks if it is not the first task 192 boolean isExcluded = (t.baseIntent.getFlags() & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) 193 == Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS; 194 if (isExcluded && !isFirstValidTask) { 195 iter.remove(); 196 continue; 197 } 198 isFirstValidTask = false; 199 } 200 201 return tasks.subList(0, Math.min(tasks.size(), numLatestTasks)); 202 } 203 204 /** Returns a list of the running tasks */ 205 public List<ActivityManager.RunningTaskInfo> getRunningTasks(int numTasks) { 206 if (mAm == null) return null; 207 return mAm.getRunningTasks(numTasks); 208 } 209 210 /** Returns whether the specified task is in the home stack */ 211 public boolean isInHomeStack(int taskId) { 212 if (mAm == null) return false; 213 214 // If we are mocking, then just return false 215 if (Constants.DebugFlags.App.EnableSystemServicesProxy) { 216 return false; 217 } 218 219 return mAm.isInHomeStack(taskId); 220 } 221 222 /** Returns the top task thumbnail for the given task id */ 223 public Bitmap getTaskThumbnail(int taskId) { 224 if (mAm == null) return null; 225 226 // If we are mocking, then just return a dummy thumbnail 227 if (Constants.DebugFlags.App.EnableSystemServicesProxy) { 228 Bitmap thumbnail = Bitmap.createBitmap(mDummyThumbnailWidth, mDummyThumbnailHeight, 229 Bitmap.Config.ARGB_8888); 230 thumbnail.eraseColor(0xff333333); 231 return thumbnail; 232 } 233 234 Bitmap thumbnail = SystemServicesProxy.getThumbnail(mAm, taskId); 235 if (thumbnail != null) { 236 // We use a dumb heuristic for now, if the thumbnail is purely transparent in the top 237 // left pixel, then assume the whole thumbnail is transparent. Generally, proper 238 // screenshots are always composed onto a bitmap that has no alpha. 239 if (Color.alpha(thumbnail.getPixel(0, 0)) == 0) { 240 mBgProtectionCanvas.setBitmap(thumbnail); 241 mBgProtectionCanvas.drawRect(0, 0, thumbnail.getWidth(), thumbnail.getHeight(), 242 mBgProtectionPaint); 243 mBgProtectionCanvas.setBitmap(null); 244 Log.e(TAG, "Invalid screenshot detected from getTaskThumbnail()"); 245 } 246 } 247 return thumbnail; 248 } 249 250 /** 251 * Returns a task thumbnail from the activity manager 252 */ 253 public static Bitmap getThumbnail(ActivityManager activityManager, int taskId) { 254 ActivityManager.TaskThumbnail taskThumbnail = activityManager.getTaskThumbnail(taskId); 255 if (taskThumbnail == null) return null; 256 257 Bitmap thumbnail = taskThumbnail.mainThumbnail; 258 ParcelFileDescriptor descriptor = taskThumbnail.thumbnailFileDescriptor; 259 if (thumbnail == null && descriptor != null) { 260 thumbnail = BitmapFactory.decodeFileDescriptor(descriptor.getFileDescriptor(), 261 null, sBitmapOptions); 262 } 263 if (descriptor != null) { 264 try { 265 descriptor.close(); 266 } catch (IOException e) { 267 } 268 } 269 return thumbnail; 270 } 271 272 /** Moves a task to the front with the specified activity options */ 273 public void moveTaskToFront(int taskId, ActivityOptions opts) { 274 if (mAm == null) return; 275 if (Constants.DebugFlags.App.EnableSystemServicesProxy) return; 276 277 if (opts != null) { 278 mAm.moveTaskToFront(taskId, ActivityManager.MOVE_TASK_WITH_HOME, 279 opts.toBundle()); 280 } else { 281 mAm.moveTaskToFront(taskId, ActivityManager.MOVE_TASK_WITH_HOME); 282 } 283 } 284 285 /** Removes the task and kills the process */ 286 public void removeTask(int taskId, boolean isDocument) { 287 if (mAm == null) return; 288 if (Constants.DebugFlags.App.EnableSystemServicesProxy) return; 289 290 // Remove the task, and only kill the process if it is not a document 291 mAm.removeTask(taskId, isDocument ? 0 : ActivityManager.REMOVE_TASK_KILL_PROCESS); 292 } 293 294 /** 295 * Returns the activity info for a given component name. 296 * 297 * @param cn The component name of the activity. 298 * @param userId The userId of the user that this is for. 299 */ 300 public ActivityInfo getActivityInfo(ComponentName cn, int userId) { 301 if (mIpm == null) return null; 302 if (Constants.DebugFlags.App.EnableSystemServicesProxy) return new ActivityInfo(); 303 304 try { 305 return mIpm.getActivityInfo(cn, PackageManager.GET_META_DATA, userId); 306 } catch (RemoteException e) { 307 e.printStackTrace(); 308 return null; 309 } 310 } 311 312 /** 313 * Returns the activity info for a given component name. 314 * 315 * @param cn The component name of the activity. 316 */ 317 public ActivityInfo getActivityInfo(ComponentName cn) { 318 if (mPm == null) return null; 319 if (Constants.DebugFlags.App.EnableSystemServicesProxy) return new ActivityInfo(); 320 321 try { 322 return mPm.getActivityInfo(cn, PackageManager.GET_META_DATA); 323 } catch (PackageManager.NameNotFoundException e) { 324 e.printStackTrace(); 325 return null; 326 } 327 } 328 329 /** Returns the activity label */ 330 public String getActivityLabel(ActivityInfo info) { 331 if (mPm == null) return null; 332 333 // If we are mocking, then return a mock label 334 if (Constants.DebugFlags.App.EnableSystemServicesProxy) { 335 return "Recent Task"; 336 } 337 338 return info.loadLabel(mPm).toString(); 339 } 340 341 /** 342 * Returns the activity icon for the ActivityInfo for a user, badging if 343 * necessary. 344 */ 345 public Drawable getActivityIcon(ActivityInfo info, int userId) { 346 if (mPm == null) return null; 347 348 // If we are mocking, then return a mock label 349 if (Constants.DebugFlags.App.EnableSystemServicesProxy) { 350 return new ColorDrawable(0xFF666666); 351 } 352 353 Drawable icon = info.loadIcon(mPm); 354 return getBadgedIcon(icon, userId); 355 } 356 357 /** 358 * Returns the given icon for a user, badging if necessary. 359 */ 360 public Drawable getBadgedIcon(Drawable icon, int userId) { 361 if (userId != UserHandle.myUserId()) { 362 icon = mPm.getUserBadgedIcon(icon, new UserHandle(userId)); 363 } 364 return icon; 365 } 366 367 /** Returns the package name of the home activity. */ 368 public String getHomeActivityPackageName() { 369 if (mPm == null) return null; 370 if (Constants.DebugFlags.App.EnableSystemServicesProxy) return null; 371 372 ArrayList<ResolveInfo> homeActivities = new ArrayList<ResolveInfo>(); 373 ComponentName defaultHomeActivity = mPm.getHomeActivities(homeActivities); 374 if (defaultHomeActivity != null) { 375 return defaultHomeActivity.getPackageName(); 376 } else if (homeActivities.size() == 1) { 377 ResolveInfo info = homeActivities.get(0); 378 if (info.activityInfo != null) { 379 return info.activityInfo.packageName; 380 } 381 } 382 return null; 383 } 384 385 /** 386 * Resolves and returns the first Recents widget from the same package as the global 387 * assist activity. 388 */ 389 public AppWidgetProviderInfo resolveSearchAppWidget() { 390 if (mAwm == null) return null; 391 if (mAssistComponent == null) return null; 392 393 // Find the first Recents widget from the same package as the global assist activity 394 List<AppWidgetProviderInfo> widgets = mAwm.getInstalledProviders( 395 AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX); 396 for (AppWidgetProviderInfo info : widgets) { 397 if (info.provider.getPackageName().equals(mAssistComponent.getPackageName())) { 398 return info; 399 } 400 } 401 return null; 402 } 403 404 /** 405 * Resolves and binds the search app widget that is to appear in the recents. 406 */ 407 public Pair<Integer, AppWidgetProviderInfo> bindSearchAppWidget(AppWidgetHost host) { 408 if (mAwm == null) return null; 409 if (mAssistComponent == null) return null; 410 411 // Find the first Recents widget from the same package as the global assist activity 412 AppWidgetProviderInfo searchWidgetInfo = resolveSearchAppWidget(); 413 414 // Return early if there is no search widget 415 if (searchWidgetInfo == null) return null; 416 417 // Allocate a new widget id and try and bind the app widget (if that fails, then just skip) 418 int searchWidgetId = host.allocateAppWidgetId(); 419 Bundle opts = new Bundle(); 420 opts.putInt(AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY, 421 AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX); 422 if (!mAwm.bindAppWidgetIdIfAllowed(searchWidgetId, searchWidgetInfo.provider, opts)) { 423 return null; 424 } 425 return new Pair<Integer, AppWidgetProviderInfo>(searchWidgetId, searchWidgetInfo); 426 } 427 428 /** 429 * Returns the app widget info for the specified app widget id. 430 */ 431 public AppWidgetProviderInfo getAppWidgetInfo(int appWidgetId) { 432 if (mAwm == null) return null; 433 434 return mAwm.getAppWidgetInfo(appWidgetId); 435 } 436 437 /** 438 * Destroys the specified app widget. 439 */ 440 public void unbindSearchAppWidget(AppWidgetHost host, int appWidgetId) { 441 if (mAwm == null) return; 442 443 // Delete the app widget 444 host.deleteAppWidgetId(appWidgetId); 445 } 446 447 /** 448 * Returns whether touch exploration is currently enabled. 449 */ 450 public boolean isTouchExplorationEnabled() { 451 if (mAccm == null) return false; 452 453 return mAccm.isEnabled() && mAccm.isTouchExplorationEnabled(); 454 } 455 456 /** 457 * Returns a global setting. 458 */ 459 public int getGlobalSetting(Context context, String setting) { 460 ContentResolver cr = context.getContentResolver(); 461 return Settings.Global.getInt(cr, setting, 0); 462 } 463 464 /** 465 * Returns a system setting. 466 */ 467 public int getSystemSetting(Context context, String setting) { 468 ContentResolver cr = context.getContentResolver(); 469 return Settings.System.getInt(cr, setting, 0); 470 } 471 472 /** 473 * Returns the window rect. 474 */ 475 public Rect getWindowRect() { 476 Rect windowRect = new Rect(); 477 if (mWm == null) return windowRect; 478 479 Point p = new Point(); 480 mWm.getDefaultDisplay().getRealSize(p); 481 windowRect.set(0, 0, p.x, p.y); 482 return windowRect; 483 } 484 485 /** 486 * Locks the current task. 487 */ 488 public void lockCurrentTask() { 489 if (mIam == null) return; 490 491 try { 492 mIam.startLockTaskModeOnCurrent(); 493 } catch (RemoteException e) {} 494 } 495 496 /** 497 * Takes a screenshot of the current surface. 498 */ 499 public Bitmap takeScreenshot() { 500 DisplayInfo di = new DisplayInfo(); 501 mDisplay.getDisplayInfo(di); 502 return SurfaceControl.screenshot(di.getNaturalWidth(), di.getNaturalHeight()); 503 } 504 505 /** 506 * Takes a screenshot of the current app. 507 */ 508 public Bitmap takeAppScreenshot() { 509 return takeScreenshot(); 510 } 511 512 public void startActivityFromRecents(int taskId, ActivityOptions options) { 513 if (mIam != null) { 514 try { 515 mIam.startActivityFromRecents(taskId, options == null ? null : options.toBundle()); 516 } catch (RemoteException e) { 517 } 518 } 519 } 520} 521