ActivityManager.java revision 02a5a6bb9ba05bdf7517de90ede49fb535ea06ca
1/* 2 * Copyright (C) 2007 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 android.app; 18 19import android.Manifest; 20import android.annotation.NonNull; 21import android.annotation.Nullable; 22import android.annotation.RequiresPermission; 23import android.annotation.SystemApi; 24import android.graphics.Canvas; 25import android.graphics.Matrix; 26import android.graphics.Point; 27import android.os.BatteryStats; 28import android.os.IBinder; 29import android.os.ParcelFileDescriptor; 30 31import android.util.Log; 32import com.android.internal.app.ProcessStats; 33import com.android.internal.os.TransferPipe; 34import com.android.internal.util.FastPrintWriter; 35 36import android.content.ComponentName; 37import android.content.Context; 38import android.content.Intent; 39import android.content.pm.ApplicationInfo; 40import android.content.pm.ConfigurationInfo; 41import android.content.pm.IPackageDataObserver; 42import android.content.pm.PackageManager; 43import android.content.pm.UserInfo; 44import android.content.res.Resources; 45import android.graphics.Bitmap; 46import android.graphics.Color; 47import android.graphics.Rect; 48import android.os.Bundle; 49import android.os.Debug; 50import android.os.Handler; 51import android.os.Parcel; 52import android.os.Parcelable; 53import android.os.Process; 54import android.os.RemoteException; 55import android.os.ServiceManager; 56import android.os.SystemProperties; 57import android.os.UserHandle; 58import android.text.TextUtils; 59import android.util.DisplayMetrics; 60import android.util.Size; 61import android.util.Slog; 62import org.xmlpull.v1.XmlSerializer; 63 64import java.io.FileDescriptor; 65import java.io.FileOutputStream; 66import java.io.IOException; 67import java.io.PrintWriter; 68import java.util.ArrayList; 69import java.util.List; 70 71/** 72 * Interact with the overall activities running in the system. 73 */ 74public class ActivityManager { 75 private static String TAG = "ActivityManager"; 76 77 private static int gMaxRecentTasks = -1; 78 79 private final Context mContext; 80 private final Handler mHandler; 81 82 /** 83 * <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code 84 * <meta-data>}</a> name for a 'home' Activity that declares a package that is to be 85 * uninstalled in lieu of the declaring one. The package named here must be 86 * signed with the same certificate as the one declaring the {@code <meta-data>}. 87 */ 88 public static final String META_HOME_ALTERNATE = "android.app.home.alternate"; 89 90 /** 91 * Result for IActivityManager.startActivity: trying to start a background user 92 * activity that shouldn't be displayed for all users. 93 * @hide 94 */ 95 public static final int START_NOT_CURRENT_USER_ACTIVITY = -8; 96 97 /** 98 * Result for IActivityManager.startActivity: trying to start an activity under voice 99 * control when that activity does not support the VOICE category. 100 * @hide 101 */ 102 public static final int START_NOT_VOICE_COMPATIBLE = -7; 103 104 /** 105 * Result for IActivityManager.startActivity: an error where the 106 * start had to be canceled. 107 * @hide 108 */ 109 public static final int START_CANCELED = -6; 110 111 /** 112 * Result for IActivityManager.startActivity: an error where the 113 * thing being started is not an activity. 114 * @hide 115 */ 116 public static final int START_NOT_ACTIVITY = -5; 117 118 /** 119 * Result for IActivityManager.startActivity: an error where the 120 * caller does not have permission to start the activity. 121 * @hide 122 */ 123 public static final int START_PERMISSION_DENIED = -4; 124 125 /** 126 * Result for IActivityManager.startActivity: an error where the 127 * caller has requested both to forward a result and to receive 128 * a result. 129 * @hide 130 */ 131 public static final int START_FORWARD_AND_REQUEST_CONFLICT = -3; 132 133 /** 134 * Result for IActivityManager.startActivity: an error where the 135 * requested class is not found. 136 * @hide 137 */ 138 public static final int START_CLASS_NOT_FOUND = -2; 139 140 /** 141 * Result for IActivityManager.startActivity: an error where the 142 * given Intent could not be resolved to an activity. 143 * @hide 144 */ 145 public static final int START_INTENT_NOT_RESOLVED = -1; 146 147 /** 148 * Result for IActivityManaqer.startActivity: the activity was started 149 * successfully as normal. 150 * @hide 151 */ 152 public static final int START_SUCCESS = 0; 153 154 /** 155 * Result for IActivityManaqer.startActivity: the caller asked that the Intent not 156 * be executed if it is the recipient, and that is indeed the case. 157 * @hide 158 */ 159 public static final int START_RETURN_INTENT_TO_CALLER = 1; 160 161 /** 162 * Result for IActivityManaqer.startActivity: activity wasn't really started, but 163 * a task was simply brought to the foreground. 164 * @hide 165 */ 166 public static final int START_TASK_TO_FRONT = 2; 167 168 /** 169 * Result for IActivityManaqer.startActivity: activity wasn't really started, but 170 * the given Intent was given to the existing top activity. 171 * @hide 172 */ 173 public static final int START_DELIVERED_TO_TOP = 3; 174 175 /** 176 * Result for IActivityManaqer.startActivity: request was canceled because 177 * app switches are temporarily canceled to ensure the user's last request 178 * (such as pressing home) is performed. 179 * @hide 180 */ 181 public static final int START_SWITCHES_CANCELED = 4; 182 183 /** 184 * Result for IActivityManaqer.startActivity: a new activity was attempted to be started 185 * while in Lock Task Mode. 186 * @hide 187 */ 188 public static final int START_RETURN_LOCK_TASK_MODE_VIOLATION = 5; 189 190 /** 191 * Flag for IActivityManaqer.startActivity: do special start mode where 192 * a new activity is launched only if it is needed. 193 * @hide 194 */ 195 public static final int START_FLAG_ONLY_IF_NEEDED = 1<<0; 196 197 /** 198 * Flag for IActivityManaqer.startActivity: launch the app for 199 * debugging. 200 * @hide 201 */ 202 public static final int START_FLAG_DEBUG = 1<<1; 203 204 /** 205 * Flag for IActivityManaqer.startActivity: launch the app for 206 * allocation tracking. 207 * @hide 208 */ 209 public static final int START_FLAG_TRACK_ALLOCATION = 1<<2; 210 211 /** 212 * Result for IActivityManaqer.broadcastIntent: success! 213 * @hide 214 */ 215 public static final int BROADCAST_SUCCESS = 0; 216 217 /** 218 * Result for IActivityManaqer.broadcastIntent: attempt to broadcast 219 * a sticky intent without appropriate permission. 220 * @hide 221 */ 222 public static final int BROADCAST_STICKY_CANT_HAVE_PERMISSION = -1; 223 224 /** 225 * Result for IActivityManager.broadcastIntent: trying to send a broadcast 226 * to a stopped user. Fail. 227 * @hide 228 */ 229 public static final int BROADCAST_FAILED_USER_STOPPED = -2; 230 231 /** 232 * Type for IActivityManaqer.getIntentSender: this PendingIntent is 233 * for a sendBroadcast operation. 234 * @hide 235 */ 236 public static final int INTENT_SENDER_BROADCAST = 1; 237 238 /** 239 * Type for IActivityManaqer.getIntentSender: this PendingIntent is 240 * for a startActivity operation. 241 * @hide 242 */ 243 public static final int INTENT_SENDER_ACTIVITY = 2; 244 245 /** 246 * Type for IActivityManaqer.getIntentSender: this PendingIntent is 247 * for an activity result operation. 248 * @hide 249 */ 250 public static final int INTENT_SENDER_ACTIVITY_RESULT = 3; 251 252 /** 253 * Type for IActivityManaqer.getIntentSender: this PendingIntent is 254 * for a startService operation. 255 * @hide 256 */ 257 public static final int INTENT_SENDER_SERVICE = 4; 258 259 /** @hide User operation call: success! */ 260 public static final int USER_OP_SUCCESS = 0; 261 262 /** @hide User operation call: given user id is not known. */ 263 public static final int USER_OP_UNKNOWN_USER = -1; 264 265 /** @hide User operation call: given user id is the current user, can't be stopped. */ 266 public static final int USER_OP_IS_CURRENT = -2; 267 268 /** @hide Process does not exist. */ 269 public static final int PROCESS_STATE_NONEXISTENT = -1; 270 271 /** @hide Process is a persistent system process. */ 272 public static final int PROCESS_STATE_PERSISTENT = 0; 273 274 /** @hide Process is a persistent system process and is doing UI. */ 275 public static final int PROCESS_STATE_PERSISTENT_UI = 1; 276 277 /** @hide Process is hosting the current top activities. Note that this covers 278 * all activities that are visible to the user. */ 279 public static final int PROCESS_STATE_TOP = 2; 280 281 /** @hide Process is hosting a foreground service due to a system binding. */ 282 public static final int PROCESS_STATE_BOUND_FOREGROUND_SERVICE = 3; 283 284 /** @hide Process is hosting a foreground service. */ 285 public static final int PROCESS_STATE_FOREGROUND_SERVICE = 4; 286 287 /** @hide Same as {@link #PROCESS_STATE_TOP} but while device is sleeping. */ 288 public static final int PROCESS_STATE_TOP_SLEEPING = 5; 289 290 /** @hide Process is important to the user, and something they are aware of. */ 291 public static final int PROCESS_STATE_IMPORTANT_FOREGROUND = 6; 292 293 /** @hide Process is important to the user, but not something they are aware of. */ 294 public static final int PROCESS_STATE_IMPORTANT_BACKGROUND = 7; 295 296 /** @hide Process is in the background running a backup/restore operation. */ 297 public static final int PROCESS_STATE_BACKUP = 8; 298 299 /** @hide Process is in the background, but it can't restore its state so we want 300 * to try to avoid killing it. */ 301 public static final int PROCESS_STATE_HEAVY_WEIGHT = 9; 302 303 /** @hide Process is in the background running a service. Unlike oom_adj, this level 304 * is used for both the normal running in background state and the executing 305 * operations state. */ 306 public static final int PROCESS_STATE_SERVICE = 10; 307 308 /** @hide Process is in the background running a receiver. Note that from the 309 * perspective of oom_adj receivers run at a higher foreground level, but for our 310 * prioritization here that is not necessary and putting them below services means 311 * many fewer changes in some process states as they receive broadcasts. */ 312 public static final int PROCESS_STATE_RECEIVER = 11; 313 314 /** @hide Process is in the background but hosts the home activity. */ 315 public static final int PROCESS_STATE_HOME = 12; 316 317 /** @hide Process is in the background but hosts the last shown activity. */ 318 public static final int PROCESS_STATE_LAST_ACTIVITY = 13; 319 320 /** @hide Process is being cached for later use and contains activities. */ 321 public static final int PROCESS_STATE_CACHED_ACTIVITY = 14; 322 323 /** @hide Process is being cached for later use and is a client of another cached 324 * process that contains activities. */ 325 public static final int PROCESS_STATE_CACHED_ACTIVITY_CLIENT = 15; 326 327 /** @hide Process is being cached for later use and is empty. */ 328 public static final int PROCESS_STATE_CACHED_EMPTY = 16; 329 330 /** @hide requestType for assist context: only basic information. */ 331 public static final int ASSIST_CONTEXT_BASIC = 0; 332 333 /** @hide requestType for assist context: generate full AssistStructure. */ 334 public static final int ASSIST_CONTEXT_FULL = 1; 335 336 /** 337 * Lock task mode is not active. 338 */ 339 public static final int LOCK_TASK_MODE_NONE = 0; 340 341 /** 342 * Full lock task mode is active. 343 */ 344 public static final int LOCK_TASK_MODE_LOCKED = 1; 345 346 /** 347 * App pinning mode is active. 348 */ 349 public static final int LOCK_TASK_MODE_PINNED = 2; 350 351 Point mAppTaskThumbnailSize; 352 353 /*package*/ ActivityManager(Context context, Handler handler) { 354 mContext = context; 355 mHandler = handler; 356 } 357 358 /** 359 * Screen compatibility mode: the application most always run in 360 * compatibility mode. 361 * @hide 362 */ 363 public static final int COMPAT_MODE_ALWAYS = -1; 364 365 /** 366 * Screen compatibility mode: the application can never run in 367 * compatibility mode. 368 * @hide 369 */ 370 public static final int COMPAT_MODE_NEVER = -2; 371 372 /** 373 * Screen compatibility mode: unknown. 374 * @hide 375 */ 376 public static final int COMPAT_MODE_UNKNOWN = -3; 377 378 /** 379 * Screen compatibility mode: the application currently has compatibility 380 * mode disabled. 381 * @hide 382 */ 383 public static final int COMPAT_MODE_DISABLED = 0; 384 385 /** 386 * Screen compatibility mode: the application currently has compatibility 387 * mode enabled. 388 * @hide 389 */ 390 public static final int COMPAT_MODE_ENABLED = 1; 391 392 /** 393 * Screen compatibility mode: request to toggle the application's 394 * compatibility mode. 395 * @hide 396 */ 397 public static final int COMPAT_MODE_TOGGLE = 2; 398 399 /** @hide */ 400 public static class StackId { 401 /** Invalid stack ID. */ 402 public static final int INVALID_STACK_ID = -1; 403 404 /** First static stack ID. */ 405 public static final int FIRST_STATIC_STACK_ID = 0; 406 407 /** Home activity stack ID. */ 408 public static final int HOME_STACK_ID = FIRST_STATIC_STACK_ID; 409 410 /** ID of stack where fullscreen activities are normally launched into. */ 411 public static final int FULLSCREEN_WORKSPACE_STACK_ID = 1; 412 413 /** ID of stack where freeform/resized activities are normally launched into. */ 414 public static final int FREEFORM_WORKSPACE_STACK_ID = FULLSCREEN_WORKSPACE_STACK_ID + 1; 415 416 /** ID of stack that occupies a dedicated region of the screen. */ 417 public static final int DOCKED_STACK_ID = FREEFORM_WORKSPACE_STACK_ID + 1; 418 419 /** ID of stack that always on top (always visible) when it exist. */ 420 public static final int PINNED_STACK_ID = DOCKED_STACK_ID + 1; 421 422 /** Last static stack stack ID. */ 423 public static final int LAST_STATIC_STACK_ID = PINNED_STACK_ID; 424 425 /** Start of ID range used by stacks that are created dynamically. */ 426 public static final int FIRST_DYNAMIC_STACK_ID = LAST_STATIC_STACK_ID + 1; 427 428 public static boolean isStaticStack(int stackId) { 429 return stackId >= FIRST_STATIC_STACK_ID && stackId <= LAST_STATIC_STACK_ID; 430 } 431 432 /** 433 * Returns true if the activities contained in the input stack display a shadow around 434 * their border. 435 */ 436 public static boolean hasWindowShadow(int stackId) { 437 return stackId == FREEFORM_WORKSPACE_STACK_ID || stackId == PINNED_STACK_ID; 438 } 439 440 /** 441 * Returns true if the activities contained in the input stack display a decor view. 442 */ 443 public static boolean hasWindowDecor(int stackId) { 444 return stackId == FREEFORM_WORKSPACE_STACK_ID; 445 } 446 447 /** 448 * Returns true if the tasks contained in the stack can be resized independently of the 449 * stack. 450 */ 451 public static boolean isTaskResizeAllowed(int stackId) { 452 return stackId == FREEFORM_WORKSPACE_STACK_ID; 453 } 454 455 /** 456 * Returns true if the task bounds should persist across power cycles. 457 */ 458 public static boolean persistTaskBounds(int stackId) { 459 return isStaticStack(stackId) && 460 stackId != DOCKED_STACK_ID && stackId != PINNED_STACK_ID; 461 } 462 463 /** 464 * Returns true if dynamic stacks are allowed to be visible behind the input stack. 465 */ 466 public static boolean isDynamicStacksVisibleBehindAllowed(int stackId) { 467 return stackId == PINNED_STACK_ID; 468 } 469 470 /** 471 * Returns true if we try to maintain focus in the current stack when the top activity 472 * finishes. 473 */ 474 public static boolean keepFocusInStackIfPossible(int stackId) { 475 return stackId == FREEFORM_WORKSPACE_STACK_ID 476 || stackId == DOCKED_STACK_ID || stackId == PINNED_STACK_ID; 477 } 478 479 /** 480 * Returns true if Stack size is affected by the docked stack changing size. 481 */ 482 public static boolean isResizeableByDockedStack(int stackId) { 483 return isStaticStack(stackId) && 484 stackId != DOCKED_STACK_ID && stackId != PINNED_STACK_ID; 485 } 486 487 /** 488 * Returns true if the size of tasks in the input stack are affected by the docked stack 489 * changing size. 490 */ 491 public static boolean isTaskResizeableByDockedStack(int stackId) { 492 return isStaticStack(stackId) && stackId != FREEFORM_WORKSPACE_STACK_ID 493 && stackId != DOCKED_STACK_ID && stackId != PINNED_STACK_ID; 494 } 495 496 /** 497 * Returns true if the windows of tasks being moved to this stack should be preserved so 498 * there isn't a display gap. 499 */ 500 public static boolean preserveWindowOnTaskMove(int stackId) { 501 return stackId == FULLSCREEN_WORKSPACE_STACK_ID 502 || stackId == DOCKED_STACK_ID || stackId == PINNED_STACK_ID; 503 } 504 } 505 506 /** 507 * Input parameter to {@link android.app.IActivityManager#moveTaskToDockedStack} which 508 * specifies the position of the created docked stack at the top half of the screen if 509 * in portrait mode or at the left half of the screen if in landscape mode. 510 * @hide 511 */ 512 public static final int DOCKED_STACK_CREATE_MODE_TOP_OR_LEFT = 0; 513 514 /** 515 * Input parameter to {@link android.app.IActivityManager#moveTaskToDockedStack} which 516 * specifies the position of the created docked stack at the bottom half of the screen if 517 * in portrait mode or at the right half of the screen if in landscape mode. 518 * @hide 519 */ 520 public static final int DOCKED_STACK_CREATE_MODE_BOTTOM_OR_RIGHT = 1; 521 522 /** 523 * Input parameter to {@link android.app.IActivityManager#resizeTask} which indicates 524 * that the resize doesn't need to preserve the window, and can be skipped if bounds 525 * is unchanged. This mode is used by window manager in most cases. 526 * @hide 527 */ 528 public static final int RESIZE_MODE_SYSTEM = 0; 529 530 /** 531 * Input parameter to {@link android.app.IActivityManager#resizeTask} which indicates 532 * that the resize should preserve the window if possible. 533 * @hide 534 */ 535 public static final int RESIZE_MODE_PRESERVE_WINDOW = (0x1 << 0); 536 537 /** 538 * Input parameter to {@link android.app.IActivityManager#resizeTask} which indicates 539 * that the resize should be performed even if the bounds appears unchanged. 540 * @hide 541 */ 542 public static final int RESIZE_MODE_FORCED = (0x1 << 1); 543 544 /** 545 * Input parameter to {@link android.app.IActivityManager#resizeTask} used by window 546 * manager during a screen rotation. 547 * @hide 548 */ 549 public static final int RESIZE_MODE_SYSTEM_SCREEN_ROTATION = RESIZE_MODE_PRESERVE_WINDOW; 550 551 /** 552 * Input parameter to {@link android.app.IActivityManager#resizeTask} used when the 553 * resize is due to a drag action. 554 * @hide 555 */ 556 public static final int RESIZE_MODE_USER = RESIZE_MODE_PRESERVE_WINDOW; 557 558 /** 559 * Input parameter to {@link android.app.IActivityManager#resizeTask} which indicates 560 * that the resize should preserve the window if possible, and should not be skipped 561 * even if the bounds is unchanged. Usually used to force a resizing when a drag action 562 * is ending. 563 * @hide 564 */ 565 public static final int RESIZE_MODE_USER_FORCED = 566 RESIZE_MODE_PRESERVE_WINDOW | RESIZE_MODE_FORCED; 567 568 /** @hide */ 569 public int getFrontActivityScreenCompatMode() { 570 try { 571 return ActivityManagerNative.getDefault().getFrontActivityScreenCompatMode(); 572 } catch (RemoteException e) { 573 // System dead, we will be dead too soon! 574 return 0; 575 } 576 } 577 578 /** @hide */ 579 public void setFrontActivityScreenCompatMode(int mode) { 580 try { 581 ActivityManagerNative.getDefault().setFrontActivityScreenCompatMode(mode); 582 } catch (RemoteException e) { 583 // System dead, we will be dead too soon! 584 } 585 } 586 587 /** @hide */ 588 public int getPackageScreenCompatMode(String packageName) { 589 try { 590 return ActivityManagerNative.getDefault().getPackageScreenCompatMode(packageName); 591 } catch (RemoteException e) { 592 // System dead, we will be dead too soon! 593 return 0; 594 } 595 } 596 597 /** @hide */ 598 public void setPackageScreenCompatMode(String packageName, int mode) { 599 try { 600 ActivityManagerNative.getDefault().setPackageScreenCompatMode(packageName, mode); 601 } catch (RemoteException e) { 602 // System dead, we will be dead too soon! 603 } 604 } 605 606 /** @hide */ 607 public boolean getPackageAskScreenCompat(String packageName) { 608 try { 609 return ActivityManagerNative.getDefault().getPackageAskScreenCompat(packageName); 610 } catch (RemoteException e) { 611 // System dead, we will be dead too soon! 612 return false; 613 } 614 } 615 616 /** @hide */ 617 public void setPackageAskScreenCompat(String packageName, boolean ask) { 618 try { 619 ActivityManagerNative.getDefault().setPackageAskScreenCompat(packageName, ask); 620 } catch (RemoteException e) { 621 // System dead, we will be dead too soon! 622 } 623 } 624 625 /** 626 * Return the approximate per-application memory class of the current 627 * device. This gives you an idea of how hard a memory limit you should 628 * impose on your application to let the overall system work best. The 629 * returned value is in megabytes; the baseline Android memory class is 630 * 16 (which happens to be the Java heap limit of those devices); some 631 * device with more memory may return 24 or even higher numbers. 632 */ 633 public int getMemoryClass() { 634 return staticGetMemoryClass(); 635 } 636 637 /** @hide */ 638 static public int staticGetMemoryClass() { 639 // Really brain dead right now -- just take this from the configured 640 // vm heap size, and assume it is in megabytes and thus ends with "m". 641 String vmHeapSize = SystemProperties.get("dalvik.vm.heapgrowthlimit", ""); 642 if (vmHeapSize != null && !"".equals(vmHeapSize)) { 643 return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1)); 644 } 645 return staticGetLargeMemoryClass(); 646 } 647 648 /** 649 * Return the approximate per-application memory class of the current 650 * device when an application is running with a large heap. This is the 651 * space available for memory-intensive applications; most applications 652 * should not need this amount of memory, and should instead stay with the 653 * {@link #getMemoryClass()} limit. The returned value is in megabytes. 654 * This may be the same size as {@link #getMemoryClass()} on memory 655 * constrained devices, or it may be significantly larger on devices with 656 * a large amount of available RAM. 657 * 658 * <p>The is the size of the application's Dalvik heap if it has 659 * specified <code>android:largeHeap="true"</code> in its manifest. 660 */ 661 public int getLargeMemoryClass() { 662 return staticGetLargeMemoryClass(); 663 } 664 665 /** @hide */ 666 static public int staticGetLargeMemoryClass() { 667 // Really brain dead right now -- just take this from the configured 668 // vm heap size, and assume it is in megabytes and thus ends with "m". 669 String vmHeapSize = SystemProperties.get("dalvik.vm.heapsize", "16m"); 670 return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length() - 1)); 671 } 672 673 /** 674 * Returns true if this is a low-RAM device. Exactly whether a device is low-RAM 675 * is ultimately up to the device configuration, but currently it generally means 676 * something in the class of a 512MB device with about a 800x480 or less screen. 677 * This is mostly intended to be used by apps to determine whether they should turn 678 * off certain features that require more RAM. 679 */ 680 public boolean isLowRamDevice() { 681 return isLowRamDeviceStatic(); 682 } 683 684 /** @hide */ 685 public static boolean isLowRamDeviceStatic() { 686 return "true".equals(SystemProperties.get("ro.config.low_ram", "false")); 687 } 688 689 /** 690 * Used by persistent processes to determine if they are running on a 691 * higher-end device so should be okay using hardware drawing acceleration 692 * (which tends to consume a lot more RAM). 693 * @hide 694 */ 695 static public boolean isHighEndGfx() { 696 return !isLowRamDeviceStatic() && 697 !Resources.getSystem().getBoolean(com.android.internal.R.bool.config_avoidGfxAccel); 698 } 699 700 /** 701 * Return the maximum number of recents entries that we will maintain and show. 702 * @hide 703 */ 704 static public int getMaxRecentTasksStatic() { 705 if (gMaxRecentTasks < 0) { 706 return gMaxRecentTasks = isLowRamDeviceStatic() ? 50 : 100; 707 } 708 return gMaxRecentTasks; 709 } 710 711 /** 712 * Return the default limit on the number of recents that an app can make. 713 * @hide 714 */ 715 static public int getDefaultAppRecentsLimitStatic() { 716 return getMaxRecentTasksStatic() / 6; 717 } 718 719 /** 720 * Return the maximum limit on the number of recents that an app can make. 721 * @hide 722 */ 723 static public int getMaxAppRecentsLimitStatic() { 724 return getMaxRecentTasksStatic() / 2; 725 } 726 727 /** 728 * Information you can set and retrieve about the current activity within the recent task list. 729 */ 730 public static class TaskDescription implements Parcelable { 731 /** @hide */ 732 public static final String ATTR_TASKDESCRIPTION_PREFIX = "task_description_"; 733 private static final String ATTR_TASKDESCRIPTIONLABEL = 734 ATTR_TASKDESCRIPTION_PREFIX + "label"; 735 private static final String ATTR_TASKDESCRIPTIONCOLOR = 736 ATTR_TASKDESCRIPTION_PREFIX + "color"; 737 private static final String ATTR_TASKDESCRIPTIONICONFILENAME = 738 ATTR_TASKDESCRIPTION_PREFIX + "icon_filename"; 739 740 private String mLabel; 741 private Bitmap mIcon; 742 private String mIconFilename; 743 private int mColorPrimary; 744 745 /** 746 * Creates the TaskDescription to the specified values. 747 * 748 * @param label A label and description of the current state of this task. 749 * @param icon An icon that represents the current state of this task. 750 * @param colorPrimary A color to override the theme's primary color. This color must be opaque. 751 */ 752 public TaskDescription(String label, Bitmap icon, int colorPrimary) { 753 if ((colorPrimary != 0) && (Color.alpha(colorPrimary) != 255)) { 754 throw new RuntimeException("A TaskDescription's primary color should be opaque"); 755 } 756 757 mLabel = label; 758 mIcon = icon; 759 mColorPrimary = colorPrimary; 760 } 761 762 /** @hide */ 763 public TaskDescription(String label, int colorPrimary, String iconFilename) { 764 this(label, null, colorPrimary); 765 mIconFilename = iconFilename; 766 } 767 768 /** 769 * Creates the TaskDescription to the specified values. 770 * 771 * @param label A label and description of the current state of this activity. 772 * @param icon An icon that represents the current state of this activity. 773 */ 774 public TaskDescription(String label, Bitmap icon) { 775 this(label, icon, 0); 776 } 777 778 /** 779 * Creates the TaskDescription to the specified values. 780 * 781 * @param label A label and description of the current state of this activity. 782 */ 783 public TaskDescription(String label) { 784 this(label, null, 0); 785 } 786 787 /** 788 * Creates an empty TaskDescription. 789 */ 790 public TaskDescription() { 791 this(null, null, 0); 792 } 793 794 /** 795 * Creates a copy of another TaskDescription. 796 */ 797 public TaskDescription(TaskDescription td) { 798 mLabel = td.mLabel; 799 mIcon = td.mIcon; 800 mColorPrimary = td.mColorPrimary; 801 mIconFilename = td.mIconFilename; 802 } 803 804 private TaskDescription(Parcel source) { 805 readFromParcel(source); 806 } 807 808 /** 809 * Sets the label for this task description. 810 * @hide 811 */ 812 public void setLabel(String label) { 813 mLabel = label; 814 } 815 816 /** 817 * Sets the primary color for this task description. 818 * @hide 819 */ 820 public void setPrimaryColor(int primaryColor) { 821 // Ensure that the given color is valid 822 if ((primaryColor != 0) && (Color.alpha(primaryColor) != 255)) { 823 throw new RuntimeException("A TaskDescription's primary color should be opaque"); 824 } 825 mColorPrimary = primaryColor; 826 } 827 828 /** 829 * Sets the icon for this task description. 830 * @hide 831 */ 832 public void setIcon(Bitmap icon) { 833 mIcon = icon; 834 } 835 836 /** 837 * Moves the icon bitmap reference from an actual Bitmap to a file containing the 838 * bitmap. 839 * @hide 840 */ 841 public void setIconFilename(String iconFilename) { 842 mIconFilename = iconFilename; 843 mIcon = null; 844 } 845 846 /** 847 * @return The label and description of the current state of this task. 848 */ 849 public String getLabel() { 850 return mLabel; 851 } 852 853 /** 854 * @return The icon that represents the current state of this task. 855 */ 856 public Bitmap getIcon() { 857 if (mIcon != null) { 858 return mIcon; 859 } 860 return loadTaskDescriptionIcon(mIconFilename); 861 } 862 863 /** @hide */ 864 public String getIconFilename() { 865 return mIconFilename; 866 } 867 868 /** @hide */ 869 public Bitmap getInMemoryIcon() { 870 return mIcon; 871 } 872 873 /** @hide */ 874 public static Bitmap loadTaskDescriptionIcon(String iconFilename) { 875 if (iconFilename != null) { 876 try { 877 return ActivityManagerNative.getDefault(). 878 getTaskDescriptionIcon(iconFilename); 879 } catch (RemoteException e) { 880 } 881 } 882 return null; 883 } 884 885 /** 886 * @return The color override on the theme's primary color. 887 */ 888 public int getPrimaryColor() { 889 return mColorPrimary; 890 } 891 892 /** @hide */ 893 public void saveToXml(XmlSerializer out) throws IOException { 894 if (mLabel != null) { 895 out.attribute(null, ATTR_TASKDESCRIPTIONLABEL, mLabel); 896 } 897 if (mColorPrimary != 0) { 898 out.attribute(null, ATTR_TASKDESCRIPTIONCOLOR, Integer.toHexString(mColorPrimary)); 899 } 900 if (mIconFilename != null) { 901 out.attribute(null, ATTR_TASKDESCRIPTIONICONFILENAME, mIconFilename); 902 } 903 } 904 905 /** @hide */ 906 public void restoreFromXml(String attrName, String attrValue) { 907 if (ATTR_TASKDESCRIPTIONLABEL.equals(attrName)) { 908 setLabel(attrValue); 909 } else if (ATTR_TASKDESCRIPTIONCOLOR.equals(attrName)) { 910 setPrimaryColor((int) Long.parseLong(attrValue, 16)); 911 } else if (ATTR_TASKDESCRIPTIONICONFILENAME.equals(attrName)) { 912 setIconFilename(attrValue); 913 } 914 } 915 916 @Override 917 public int describeContents() { 918 return 0; 919 } 920 921 @Override 922 public void writeToParcel(Parcel dest, int flags) { 923 if (mLabel == null) { 924 dest.writeInt(0); 925 } else { 926 dest.writeInt(1); 927 dest.writeString(mLabel); 928 } 929 if (mIcon == null) { 930 dest.writeInt(0); 931 } else { 932 dest.writeInt(1); 933 mIcon.writeToParcel(dest, 0); 934 } 935 dest.writeInt(mColorPrimary); 936 if (mIconFilename == null) { 937 dest.writeInt(0); 938 } else { 939 dest.writeInt(1); 940 dest.writeString(mIconFilename); 941 } 942 } 943 944 public void readFromParcel(Parcel source) { 945 mLabel = source.readInt() > 0 ? source.readString() : null; 946 mIcon = source.readInt() > 0 ? Bitmap.CREATOR.createFromParcel(source) : null; 947 mColorPrimary = source.readInt(); 948 mIconFilename = source.readInt() > 0 ? source.readString() : null; 949 } 950 951 public static final Creator<TaskDescription> CREATOR 952 = new Creator<TaskDescription>() { 953 public TaskDescription createFromParcel(Parcel source) { 954 return new TaskDescription(source); 955 } 956 public TaskDescription[] newArray(int size) { 957 return new TaskDescription[size]; 958 } 959 }; 960 961 @Override 962 public String toString() { 963 return "TaskDescription Label: " + mLabel + " Icon: " + mIcon + 964 " colorPrimary: " + mColorPrimary; 965 } 966 } 967 968 /** 969 * Information you can retrieve about tasks that the user has most recently 970 * started or visited. 971 */ 972 public static class RecentTaskInfo implements Parcelable { 973 /** 974 * If this task is currently running, this is the identifier for it. 975 * If it is not running, this will be -1. 976 */ 977 public int id; 978 979 /** 980 * The true identifier of this task, valid even if it is not running. 981 */ 982 public int persistentId; 983 984 /** 985 * The original Intent used to launch the task. You can use this 986 * Intent to re-launch the task (if it is no longer running) or bring 987 * the current task to the front. 988 */ 989 public Intent baseIntent; 990 991 /** 992 * If this task was started from an alias, this is the actual 993 * activity component that was initially started; the component of 994 * the baseIntent in this case is the name of the actual activity 995 * implementation that the alias referred to. Otherwise, this is null. 996 */ 997 public ComponentName origActivity; 998 999 /** 1000 * The actual activity component that started the task. 1001 * @hide 1002 */ 1003 @Nullable 1004 public ComponentName realActivity; 1005 1006 /** 1007 * Description of the task's last state. 1008 */ 1009 public CharSequence description; 1010 1011 /** 1012 * The id of the ActivityStack this Task was on most recently. 1013 * @hide 1014 */ 1015 public int stackId; 1016 1017 /** 1018 * The id of the user the task was running as. 1019 * @hide 1020 */ 1021 public int userId; 1022 1023 /** 1024 * The first time this task was active. 1025 * @hide 1026 */ 1027 public long firstActiveTime; 1028 1029 /** 1030 * The last time this task was active. 1031 * @hide 1032 */ 1033 public long lastActiveTime; 1034 1035 /** 1036 * The recent activity values for the highest activity in the stack to have set the values. 1037 * {@link Activity#setTaskDescription(android.app.ActivityManager.TaskDescription)}. 1038 */ 1039 public TaskDescription taskDescription; 1040 1041 /** 1042 * Task affiliation for grouping with other tasks. 1043 */ 1044 public int affiliatedTaskId; 1045 1046 /** 1047 * Task affiliation color of the source task with the affiliated task id. 1048 * 1049 * @hide 1050 */ 1051 public int affiliatedTaskColor; 1052 1053 /** 1054 * The component launched as the first activity in the task. 1055 * This can be considered the "application" of this task. 1056 */ 1057 public ComponentName baseActivity; 1058 1059 /** 1060 * The activity component at the top of the history stack of the task. 1061 * This is what the user is currently doing. 1062 */ 1063 public ComponentName topActivity; 1064 1065 /** 1066 * Number of activities in this task. 1067 */ 1068 public int numActivities; 1069 1070 /** 1071 * The bounds of the task. 1072 * @hide 1073 */ 1074 public Rect bounds; 1075 1076 public RecentTaskInfo() { 1077 } 1078 1079 @Override 1080 public int describeContents() { 1081 return 0; 1082 } 1083 1084 @Override 1085 public void writeToParcel(Parcel dest, int flags) { 1086 dest.writeInt(id); 1087 dest.writeInt(persistentId); 1088 if (baseIntent != null) { 1089 dest.writeInt(1); 1090 baseIntent.writeToParcel(dest, 0); 1091 } else { 1092 dest.writeInt(0); 1093 } 1094 ComponentName.writeToParcel(origActivity, dest); 1095 ComponentName.writeToParcel(realActivity, dest); 1096 TextUtils.writeToParcel(description, dest, 1097 Parcelable.PARCELABLE_WRITE_RETURN_VALUE); 1098 if (taskDescription != null) { 1099 dest.writeInt(1); 1100 taskDescription.writeToParcel(dest, 0); 1101 } else { 1102 dest.writeInt(0); 1103 } 1104 dest.writeInt(stackId); 1105 dest.writeInt(userId); 1106 dest.writeLong(firstActiveTime); 1107 dest.writeLong(lastActiveTime); 1108 dest.writeInt(affiliatedTaskId); 1109 dest.writeInt(affiliatedTaskColor); 1110 ComponentName.writeToParcel(baseActivity, dest); 1111 ComponentName.writeToParcel(topActivity, dest); 1112 dest.writeInt(numActivities); 1113 if (bounds != null) { 1114 dest.writeInt(1); 1115 bounds.writeToParcel(dest, 0); 1116 } else { 1117 dest.writeInt(0); 1118 } 1119 } 1120 1121 public void readFromParcel(Parcel source) { 1122 id = source.readInt(); 1123 persistentId = source.readInt(); 1124 baseIntent = source.readInt() > 0 ? Intent.CREATOR.createFromParcel(source) : null; 1125 origActivity = ComponentName.readFromParcel(source); 1126 realActivity = ComponentName.readFromParcel(source); 1127 description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source); 1128 taskDescription = source.readInt() > 0 ? 1129 TaskDescription.CREATOR.createFromParcel(source) : null; 1130 stackId = source.readInt(); 1131 userId = source.readInt(); 1132 firstActiveTime = source.readLong(); 1133 lastActiveTime = source.readLong(); 1134 affiliatedTaskId = source.readInt(); 1135 affiliatedTaskColor = source.readInt(); 1136 baseActivity = ComponentName.readFromParcel(source); 1137 topActivity = ComponentName.readFromParcel(source); 1138 numActivities = source.readInt(); 1139 bounds = source.readInt() > 0 ? 1140 Rect.CREATOR.createFromParcel(source) : null; 1141 } 1142 1143 public static final Creator<RecentTaskInfo> CREATOR 1144 = new Creator<RecentTaskInfo>() { 1145 public RecentTaskInfo createFromParcel(Parcel source) { 1146 return new RecentTaskInfo(source); 1147 } 1148 public RecentTaskInfo[] newArray(int size) { 1149 return new RecentTaskInfo[size]; 1150 } 1151 }; 1152 1153 private RecentTaskInfo(Parcel source) { 1154 readFromParcel(source); 1155 } 1156 } 1157 1158 /** 1159 * Flag for use with {@link #getRecentTasks}: return all tasks, even those 1160 * that have set their 1161 * {@link android.content.Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag. 1162 */ 1163 public static final int RECENT_WITH_EXCLUDED = 0x0001; 1164 1165 /** 1166 * Provides a list that does not contain any 1167 * recent tasks that currently are not available to the user. 1168 */ 1169 public static final int RECENT_IGNORE_UNAVAILABLE = 0x0002; 1170 1171 /** 1172 * Provides a list that contains recent tasks for all 1173 * profiles of a user. 1174 * @hide 1175 */ 1176 public static final int RECENT_INCLUDE_PROFILES = 0x0004; 1177 1178 /** 1179 * Ignores all tasks that are on the home stack. 1180 * @hide 1181 */ 1182 public static final int RECENT_IGNORE_HOME_STACK_TASKS = 0x0008; 1183 1184 /** 1185 * <p></p>Return a list of the tasks that the user has recently launched, with 1186 * the most recent being first and older ones after in order. 1187 * 1188 * <p><b>Note: this method is only intended for debugging and presenting 1189 * task management user interfaces</b>. This should never be used for 1190 * core logic in an application, such as deciding between different 1191 * behaviors based on the information found here. Such uses are 1192 * <em>not</em> supported, and will likely break in the future. For 1193 * example, if multiple applications can be actively running at the 1194 * same time, assumptions made about the meaning of the data here for 1195 * purposes of control flow will be incorrect.</p> 1196 * 1197 * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method is 1198 * no longer available to third party applications: the introduction of 1199 * document-centric recents means 1200 * it can leak personal information to the caller. For backwards compatibility, 1201 * it will still return a small subset of its data: at least the caller's 1202 * own tasks (though see {@link #getAppTasks()} for the correct supported 1203 * way to retrieve that information), and possibly some other tasks 1204 * such as home that are known to not be sensitive. 1205 * 1206 * @param maxNum The maximum number of entries to return in the list. The 1207 * actual number returned may be smaller, depending on how many tasks the 1208 * user has started and the maximum number the system can remember. 1209 * @param flags Information about what to return. May be any combination 1210 * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}. 1211 * 1212 * @return Returns a list of RecentTaskInfo records describing each of 1213 * the recent tasks. 1214 */ 1215 @Deprecated 1216 public List<RecentTaskInfo> getRecentTasks(int maxNum, int flags) 1217 throws SecurityException { 1218 try { 1219 return ActivityManagerNative.getDefault().getRecentTasks(maxNum, 1220 flags, UserHandle.myUserId()); 1221 } catch (RemoteException e) { 1222 // System dead, we will be dead too soon! 1223 return null; 1224 } 1225 } 1226 1227 /** 1228 * Same as {@link #getRecentTasks(int, int)} but returns the recent tasks for a 1229 * specific user. It requires holding 1230 * the {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission. 1231 * @param maxNum The maximum number of entries to return in the list. The 1232 * actual number returned may be smaller, depending on how many tasks the 1233 * user has started and the maximum number the system can remember. 1234 * @param flags Information about what to return. May be any combination 1235 * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}. 1236 * 1237 * @return Returns a list of RecentTaskInfo records describing each of 1238 * the recent tasks. Most recently activated tasks go first. 1239 * 1240 * @hide 1241 */ 1242 public List<RecentTaskInfo> getRecentTasksForUser(int maxNum, int flags, int userId) 1243 throws SecurityException { 1244 try { 1245 return ActivityManagerNative.getDefault().getRecentTasks(maxNum, 1246 flags, userId); 1247 } catch (RemoteException e) { 1248 // System dead, we will be dead too soon! 1249 return null; 1250 } 1251 } 1252 1253 /** 1254 * Information you can retrieve about a particular task that is currently 1255 * "running" in the system. Note that a running task does not mean the 1256 * given task actually has a process it is actively running in; it simply 1257 * means that the user has gone to it and never closed it, but currently 1258 * the system may have killed its process and is only holding on to its 1259 * last state in order to restart it when the user returns. 1260 */ 1261 public static class RunningTaskInfo implements Parcelable { 1262 /** 1263 * A unique identifier for this task. 1264 */ 1265 public int id; 1266 1267 /** 1268 * The stack that currently contains this task. 1269 * @hide 1270 */ 1271 public int stackId; 1272 1273 /** 1274 * The component launched as the first activity in the task. This can 1275 * be considered the "application" of this task. 1276 */ 1277 public ComponentName baseActivity; 1278 1279 /** 1280 * The activity component at the top of the history stack of the task. 1281 * This is what the user is currently doing. 1282 */ 1283 public ComponentName topActivity; 1284 1285 /** 1286 * Thumbnail representation of the task's current state. Currently 1287 * always null. 1288 */ 1289 public Bitmap thumbnail; 1290 1291 /** 1292 * Description of the task's current state. 1293 */ 1294 public CharSequence description; 1295 1296 /** 1297 * Number of activities in this task. 1298 */ 1299 public int numActivities; 1300 1301 /** 1302 * Number of activities that are currently running (not stopped 1303 * and persisted) in this task. 1304 */ 1305 public int numRunning; 1306 1307 /** 1308 * Last time task was run. For sorting. 1309 * @hide 1310 */ 1311 public long lastActiveTime; 1312 1313 public RunningTaskInfo() { 1314 } 1315 1316 public int describeContents() { 1317 return 0; 1318 } 1319 1320 public void writeToParcel(Parcel dest, int flags) { 1321 dest.writeInt(id); 1322 dest.writeInt(stackId); 1323 ComponentName.writeToParcel(baseActivity, dest); 1324 ComponentName.writeToParcel(topActivity, dest); 1325 if (thumbnail != null) { 1326 dest.writeInt(1); 1327 thumbnail.writeToParcel(dest, 0); 1328 } else { 1329 dest.writeInt(0); 1330 } 1331 TextUtils.writeToParcel(description, dest, 1332 Parcelable.PARCELABLE_WRITE_RETURN_VALUE); 1333 dest.writeInt(numActivities); 1334 dest.writeInt(numRunning); 1335 } 1336 1337 public void readFromParcel(Parcel source) { 1338 id = source.readInt(); 1339 stackId = source.readInt(); 1340 baseActivity = ComponentName.readFromParcel(source); 1341 topActivity = ComponentName.readFromParcel(source); 1342 if (source.readInt() != 0) { 1343 thumbnail = Bitmap.CREATOR.createFromParcel(source); 1344 } else { 1345 thumbnail = null; 1346 } 1347 description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source); 1348 numActivities = source.readInt(); 1349 numRunning = source.readInt(); 1350 } 1351 1352 public static final Creator<RunningTaskInfo> CREATOR = new Creator<RunningTaskInfo>() { 1353 public RunningTaskInfo createFromParcel(Parcel source) { 1354 return new RunningTaskInfo(source); 1355 } 1356 public RunningTaskInfo[] newArray(int size) { 1357 return new RunningTaskInfo[size]; 1358 } 1359 }; 1360 1361 private RunningTaskInfo(Parcel source) { 1362 readFromParcel(source); 1363 } 1364 } 1365 1366 /** 1367 * Get the list of tasks associated with the calling application. 1368 * 1369 * @return The list of tasks associated with the application making this call. 1370 * @throws SecurityException 1371 */ 1372 public List<ActivityManager.AppTask> getAppTasks() { 1373 ArrayList<AppTask> tasks = new ArrayList<AppTask>(); 1374 List<IAppTask> appTasks; 1375 try { 1376 appTasks = ActivityManagerNative.getDefault().getAppTasks(mContext.getPackageName()); 1377 } catch (RemoteException e) { 1378 // System dead, we will be dead too soon! 1379 return null; 1380 } 1381 int numAppTasks = appTasks.size(); 1382 for (int i = 0; i < numAppTasks; i++) { 1383 tasks.add(new AppTask(appTasks.get(i))); 1384 } 1385 return tasks; 1386 } 1387 1388 /** 1389 * Return the current design dimensions for {@link AppTask} thumbnails, for use 1390 * with {@link #addAppTask}. 1391 */ 1392 public Size getAppTaskThumbnailSize() { 1393 synchronized (this) { 1394 ensureAppTaskThumbnailSizeLocked(); 1395 return new Size(mAppTaskThumbnailSize.x, mAppTaskThumbnailSize.y); 1396 } 1397 } 1398 1399 private void ensureAppTaskThumbnailSizeLocked() { 1400 if (mAppTaskThumbnailSize == null) { 1401 try { 1402 mAppTaskThumbnailSize = ActivityManagerNative.getDefault().getAppTaskThumbnailSize(); 1403 } catch (RemoteException e) { 1404 throw new IllegalStateException("System dead?", e); 1405 } 1406 } 1407 } 1408 1409 /** 1410 * Add a new {@link AppTask} for the calling application. This will create a new 1411 * recents entry that is added to the <b>end</b> of all existing recents. 1412 * 1413 * @param activity The activity that is adding the entry. This is used to help determine 1414 * the context that the new recents entry will be in. 1415 * @param intent The Intent that describes the recents entry. This is the same Intent that 1416 * you would have used to launch the activity for it. In generally you will want to set 1417 * both {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT} and 1418 * {@link Intent#FLAG_ACTIVITY_RETAIN_IN_RECENTS}; the latter is required since this recents 1419 * entry will exist without an activity, so it doesn't make sense to not retain it when 1420 * its activity disappears. The given Intent here also must have an explicit ComponentName 1421 * set on it. 1422 * @param description Optional additional description information. 1423 * @param thumbnail Thumbnail to use for the recents entry. Should be the size given by 1424 * {@link #getAppTaskThumbnailSize()}. If the bitmap is not that exact size, it will be 1425 * recreated in your process, probably in a way you don't like, before the recents entry 1426 * is added. 1427 * 1428 * @return Returns the task id of the newly added app task, or -1 if the add failed. The 1429 * most likely cause of failure is that there is no more room for more tasks for your app. 1430 */ 1431 public int addAppTask(@NonNull Activity activity, @NonNull Intent intent, 1432 @Nullable TaskDescription description, @NonNull Bitmap thumbnail) { 1433 Point size; 1434 synchronized (this) { 1435 ensureAppTaskThumbnailSizeLocked(); 1436 size = mAppTaskThumbnailSize; 1437 } 1438 final int tw = thumbnail.getWidth(); 1439 final int th = thumbnail.getHeight(); 1440 if (tw != size.x || th != size.y) { 1441 Bitmap bm = Bitmap.createBitmap(size.x, size.y, thumbnail.getConfig()); 1442 1443 // Use ScaleType.CENTER_CROP, except we leave the top edge at the top. 1444 float scale; 1445 float dx = 0, dy = 0; 1446 if (tw * size.x > size.y * th) { 1447 scale = (float) size.x / (float) th; 1448 dx = (size.y - tw * scale) * 0.5f; 1449 } else { 1450 scale = (float) size.y / (float) tw; 1451 dy = (size.x - th * scale) * 0.5f; 1452 } 1453 Matrix matrix = new Matrix(); 1454 matrix.setScale(scale, scale); 1455 matrix.postTranslate((int) (dx + 0.5f), 0); 1456 1457 Canvas canvas = new Canvas(bm); 1458 canvas.drawBitmap(thumbnail, matrix, null); 1459 canvas.setBitmap(null); 1460 1461 thumbnail = bm; 1462 } 1463 if (description == null) { 1464 description = new TaskDescription(); 1465 } 1466 try { 1467 return ActivityManagerNative.getDefault().addAppTask(activity.getActivityToken(), 1468 intent, description, thumbnail); 1469 } catch (RemoteException e) { 1470 throw new IllegalStateException("System dead?", e); 1471 } 1472 } 1473 1474 /** 1475 * Return a list of the tasks that are currently running, with 1476 * the most recent being first and older ones after in order. Note that 1477 * "running" does not mean any of the task's code is currently loaded or 1478 * activity -- the task may have been frozen by the system, so that it 1479 * can be restarted in its previous state when next brought to the 1480 * foreground. 1481 * 1482 * <p><b>Note: this method is only intended for debugging and presenting 1483 * task management user interfaces</b>. This should never be used for 1484 * core logic in an application, such as deciding between different 1485 * behaviors based on the information found here. Such uses are 1486 * <em>not</em> supported, and will likely break in the future. For 1487 * example, if multiple applications can be actively running at the 1488 * same time, assumptions made about the meaning of the data here for 1489 * purposes of control flow will be incorrect.</p> 1490 * 1491 * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method 1492 * is no longer available to third party 1493 * applications: the introduction of document-centric recents means 1494 * it can leak person information to the caller. For backwards compatibility, 1495 * it will still retu rn a small subset of its data: at least the caller's 1496 * own tasks, and possibly some other tasks 1497 * such as home that are known to not be sensitive. 1498 * 1499 * @param maxNum The maximum number of entries to return in the list. The 1500 * actual number returned may be smaller, depending on how many tasks the 1501 * user has started. 1502 * 1503 * @return Returns a list of RunningTaskInfo records describing each of 1504 * the running tasks. 1505 */ 1506 @Deprecated 1507 public List<RunningTaskInfo> getRunningTasks(int maxNum) 1508 throws SecurityException { 1509 try { 1510 return ActivityManagerNative.getDefault().getTasks(maxNum, 0); 1511 } catch (RemoteException e) { 1512 // System dead, we will be dead too soon! 1513 return null; 1514 } 1515 } 1516 1517 /** 1518 * Completely remove the given task. 1519 * 1520 * @param taskId Identifier of the task to be removed. 1521 * @return Returns true if the given task was found and removed. 1522 * 1523 * @hide 1524 */ 1525 public boolean removeTask(int taskId) throws SecurityException { 1526 try { 1527 return ActivityManagerNative.getDefault().removeTask(taskId); 1528 } catch (RemoteException e) { 1529 // System dead, we will be dead too soon! 1530 return false; 1531 } 1532 } 1533 1534 /** @hide */ 1535 public static class TaskThumbnail implements Parcelable { 1536 public Bitmap mainThumbnail; 1537 public ParcelFileDescriptor thumbnailFileDescriptor; 1538 1539 public TaskThumbnail() { 1540 } 1541 1542 public int describeContents() { 1543 if (thumbnailFileDescriptor != null) { 1544 return thumbnailFileDescriptor.describeContents(); 1545 } 1546 return 0; 1547 } 1548 1549 public void writeToParcel(Parcel dest, int flags) { 1550 if (mainThumbnail != null) { 1551 dest.writeInt(1); 1552 mainThumbnail.writeToParcel(dest, flags); 1553 } else { 1554 dest.writeInt(0); 1555 } 1556 if (thumbnailFileDescriptor != null) { 1557 dest.writeInt(1); 1558 thumbnailFileDescriptor.writeToParcel(dest, flags); 1559 } else { 1560 dest.writeInt(0); 1561 } 1562 } 1563 1564 public void readFromParcel(Parcel source) { 1565 if (source.readInt() != 0) { 1566 mainThumbnail = Bitmap.CREATOR.createFromParcel(source); 1567 } else { 1568 mainThumbnail = null; 1569 } 1570 if (source.readInt() != 0) { 1571 thumbnailFileDescriptor = ParcelFileDescriptor.CREATOR.createFromParcel(source); 1572 } else { 1573 thumbnailFileDescriptor = null; 1574 } 1575 } 1576 1577 public static final Creator<TaskThumbnail> CREATOR = new Creator<TaskThumbnail>() { 1578 public TaskThumbnail createFromParcel(Parcel source) { 1579 return new TaskThumbnail(source); 1580 } 1581 public TaskThumbnail[] newArray(int size) { 1582 return new TaskThumbnail[size]; 1583 } 1584 }; 1585 1586 private TaskThumbnail(Parcel source) { 1587 readFromParcel(source); 1588 } 1589 } 1590 1591 /** @hide */ 1592 public TaskThumbnail getTaskThumbnail(int id) throws SecurityException { 1593 try { 1594 return ActivityManagerNative.getDefault().getTaskThumbnail(id); 1595 } catch (RemoteException e) { 1596 // System dead, we will be dead too soon! 1597 return null; 1598 } 1599 } 1600 1601 /** @hide */ 1602 public boolean isInHomeStack(int taskId) { 1603 try { 1604 return ActivityManagerNative.getDefault().isInHomeStack(taskId); 1605 } catch (RemoteException e) { 1606 // System dead, we will be dead too soon! 1607 return false; 1608 } 1609 } 1610 1611 /** 1612 * Flag for {@link #moveTaskToFront(int, int)}: also move the "home" 1613 * activity along with the task, so it is positioned immediately behind 1614 * the task. 1615 */ 1616 public static final int MOVE_TASK_WITH_HOME = 0x00000001; 1617 1618 /** 1619 * Flag for {@link #moveTaskToFront(int, int)}: don't count this as a 1620 * user-instigated action, so the current activity will not receive a 1621 * hint that the user is leaving. 1622 */ 1623 public static final int MOVE_TASK_NO_USER_ACTION = 0x00000002; 1624 1625 /** 1626 * Equivalent to calling {@link #moveTaskToFront(int, int, Bundle)} 1627 * with a null options argument. 1628 * 1629 * @param taskId The identifier of the task to be moved, as found in 1630 * {@link RunningTaskInfo} or {@link RecentTaskInfo}. 1631 * @param flags Additional operational flags, 0 or more of 1632 * {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}. 1633 */ 1634 public void moveTaskToFront(int taskId, int flags) { 1635 moveTaskToFront(taskId, flags, null); 1636 } 1637 1638 /** 1639 * Ask that the task associated with a given task ID be moved to the 1640 * front of the stack, so it is now visible to the user. Requires that 1641 * the caller hold permission {@link android.Manifest.permission#REORDER_TASKS} 1642 * or a SecurityException will be thrown. 1643 * 1644 * @param taskId The identifier of the task to be moved, as found in 1645 * {@link RunningTaskInfo} or {@link RecentTaskInfo}. 1646 * @param flags Additional operational flags, 0 or more of 1647 * {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}. 1648 * @param options Additional options for the operation, either null or 1649 * as per {@link Context#startActivity(Intent, android.os.Bundle) 1650 * Context.startActivity(Intent, Bundle)}. 1651 */ 1652 public void moveTaskToFront(int taskId, int flags, Bundle options) { 1653 try { 1654 ActivityManagerNative.getDefault().moveTaskToFront(taskId, flags, options); 1655 } catch (RemoteException e) { 1656 // System dead, we will be dead too soon! 1657 } 1658 } 1659 1660 /** 1661 * Information you can retrieve about a particular Service that is 1662 * currently running in the system. 1663 */ 1664 public static class RunningServiceInfo implements Parcelable { 1665 /** 1666 * The service component. 1667 */ 1668 public ComponentName service; 1669 1670 /** 1671 * If non-zero, this is the process the service is running in. 1672 */ 1673 public int pid; 1674 1675 /** 1676 * The UID that owns this service. 1677 */ 1678 public int uid; 1679 1680 /** 1681 * The name of the process this service runs in. 1682 */ 1683 public String process; 1684 1685 /** 1686 * Set to true if the service has asked to run as a foreground process. 1687 */ 1688 public boolean foreground; 1689 1690 /** 1691 * The time when the service was first made active, either by someone 1692 * starting or binding to it. This 1693 * is in units of {@link android.os.SystemClock#elapsedRealtime()}. 1694 */ 1695 public long activeSince; 1696 1697 /** 1698 * Set to true if this service has been explicitly started. 1699 */ 1700 public boolean started; 1701 1702 /** 1703 * Number of clients connected to the service. 1704 */ 1705 public int clientCount; 1706 1707 /** 1708 * Number of times the service's process has crashed while the service 1709 * is running. 1710 */ 1711 public int crashCount; 1712 1713 /** 1714 * The time when there was last activity in the service (either 1715 * explicit requests to start it or clients binding to it). This 1716 * is in units of {@link android.os.SystemClock#uptimeMillis()}. 1717 */ 1718 public long lastActivityTime; 1719 1720 /** 1721 * If non-zero, this service is not currently running, but scheduled to 1722 * restart at the given time. 1723 */ 1724 public long restarting; 1725 1726 /** 1727 * Bit for {@link #flags}: set if this service has been 1728 * explicitly started. 1729 */ 1730 public static final int FLAG_STARTED = 1<<0; 1731 1732 /** 1733 * Bit for {@link #flags}: set if the service has asked to 1734 * run as a foreground process. 1735 */ 1736 public static final int FLAG_FOREGROUND = 1<<1; 1737 1738 /** 1739 * Bit for {@link #flags): set if the service is running in a 1740 * core system process. 1741 */ 1742 public static final int FLAG_SYSTEM_PROCESS = 1<<2; 1743 1744 /** 1745 * Bit for {@link #flags): set if the service is running in a 1746 * persistent process. 1747 */ 1748 public static final int FLAG_PERSISTENT_PROCESS = 1<<3; 1749 1750 /** 1751 * Running flags. 1752 */ 1753 public int flags; 1754 1755 /** 1756 * For special services that are bound to by system code, this is 1757 * the package that holds the binding. 1758 */ 1759 public String clientPackage; 1760 1761 /** 1762 * For special services that are bound to by system code, this is 1763 * a string resource providing a user-visible label for who the 1764 * client is. 1765 */ 1766 public int clientLabel; 1767 1768 public RunningServiceInfo() { 1769 } 1770 1771 public int describeContents() { 1772 return 0; 1773 } 1774 1775 public void writeToParcel(Parcel dest, int flags) { 1776 ComponentName.writeToParcel(service, dest); 1777 dest.writeInt(pid); 1778 dest.writeInt(uid); 1779 dest.writeString(process); 1780 dest.writeInt(foreground ? 1 : 0); 1781 dest.writeLong(activeSince); 1782 dest.writeInt(started ? 1 : 0); 1783 dest.writeInt(clientCount); 1784 dest.writeInt(crashCount); 1785 dest.writeLong(lastActivityTime); 1786 dest.writeLong(restarting); 1787 dest.writeInt(this.flags); 1788 dest.writeString(clientPackage); 1789 dest.writeInt(clientLabel); 1790 } 1791 1792 public void readFromParcel(Parcel source) { 1793 service = ComponentName.readFromParcel(source); 1794 pid = source.readInt(); 1795 uid = source.readInt(); 1796 process = source.readString(); 1797 foreground = source.readInt() != 0; 1798 activeSince = source.readLong(); 1799 started = source.readInt() != 0; 1800 clientCount = source.readInt(); 1801 crashCount = source.readInt(); 1802 lastActivityTime = source.readLong(); 1803 restarting = source.readLong(); 1804 flags = source.readInt(); 1805 clientPackage = source.readString(); 1806 clientLabel = source.readInt(); 1807 } 1808 1809 public static final Creator<RunningServiceInfo> CREATOR = new Creator<RunningServiceInfo>() { 1810 public RunningServiceInfo createFromParcel(Parcel source) { 1811 return new RunningServiceInfo(source); 1812 } 1813 public RunningServiceInfo[] newArray(int size) { 1814 return new RunningServiceInfo[size]; 1815 } 1816 }; 1817 1818 private RunningServiceInfo(Parcel source) { 1819 readFromParcel(source); 1820 } 1821 } 1822 1823 /** 1824 * Return a list of the services that are currently running. 1825 * 1826 * <p><b>Note: this method is only intended for debugging or implementing 1827 * service management type user interfaces.</b></p> 1828 * 1829 * @param maxNum The maximum number of entries to return in the list. The 1830 * actual number returned may be smaller, depending on how many services 1831 * are running. 1832 * 1833 * @return Returns a list of RunningServiceInfo records describing each of 1834 * the running tasks. 1835 */ 1836 public List<RunningServiceInfo> getRunningServices(int maxNum) 1837 throws SecurityException { 1838 try { 1839 return ActivityManagerNative.getDefault() 1840 .getServices(maxNum, 0); 1841 } catch (RemoteException e) { 1842 // System dead, we will be dead too soon! 1843 return null; 1844 } 1845 } 1846 1847 /** 1848 * Returns a PendingIntent you can start to show a control panel for the 1849 * given running service. If the service does not have a control panel, 1850 * null is returned. 1851 */ 1852 public PendingIntent getRunningServiceControlPanel(ComponentName service) 1853 throws SecurityException { 1854 try { 1855 return ActivityManagerNative.getDefault() 1856 .getRunningServiceControlPanel(service); 1857 } catch (RemoteException e) { 1858 // System dead, we will be dead too soon! 1859 return null; 1860 } 1861 } 1862 1863 /** 1864 * Information you can retrieve about the available memory through 1865 * {@link ActivityManager#getMemoryInfo}. 1866 */ 1867 public static class MemoryInfo implements Parcelable { 1868 /** 1869 * The available memory on the system. This number should not 1870 * be considered absolute: due to the nature of the kernel, a significant 1871 * portion of this memory is actually in use and needed for the overall 1872 * system to run well. 1873 */ 1874 public long availMem; 1875 1876 /** 1877 * The total memory accessible by the kernel. This is basically the 1878 * RAM size of the device, not including below-kernel fixed allocations 1879 * like DMA buffers, RAM for the baseband CPU, etc. 1880 */ 1881 public long totalMem; 1882 1883 /** 1884 * The threshold of {@link #availMem} at which we consider memory to be 1885 * low and start killing background services and other non-extraneous 1886 * processes. 1887 */ 1888 public long threshold; 1889 1890 /** 1891 * Set to true if the system considers itself to currently be in a low 1892 * memory situation. 1893 */ 1894 public boolean lowMemory; 1895 1896 /** @hide */ 1897 public long hiddenAppThreshold; 1898 /** @hide */ 1899 public long secondaryServerThreshold; 1900 /** @hide */ 1901 public long visibleAppThreshold; 1902 /** @hide */ 1903 public long foregroundAppThreshold; 1904 1905 public MemoryInfo() { 1906 } 1907 1908 public int describeContents() { 1909 return 0; 1910 } 1911 1912 public void writeToParcel(Parcel dest, int flags) { 1913 dest.writeLong(availMem); 1914 dest.writeLong(totalMem); 1915 dest.writeLong(threshold); 1916 dest.writeInt(lowMemory ? 1 : 0); 1917 dest.writeLong(hiddenAppThreshold); 1918 dest.writeLong(secondaryServerThreshold); 1919 dest.writeLong(visibleAppThreshold); 1920 dest.writeLong(foregroundAppThreshold); 1921 } 1922 1923 public void readFromParcel(Parcel source) { 1924 availMem = source.readLong(); 1925 totalMem = source.readLong(); 1926 threshold = source.readLong(); 1927 lowMemory = source.readInt() != 0; 1928 hiddenAppThreshold = source.readLong(); 1929 secondaryServerThreshold = source.readLong(); 1930 visibleAppThreshold = source.readLong(); 1931 foregroundAppThreshold = source.readLong(); 1932 } 1933 1934 public static final Creator<MemoryInfo> CREATOR 1935 = new Creator<MemoryInfo>() { 1936 public MemoryInfo createFromParcel(Parcel source) { 1937 return new MemoryInfo(source); 1938 } 1939 public MemoryInfo[] newArray(int size) { 1940 return new MemoryInfo[size]; 1941 } 1942 }; 1943 1944 private MemoryInfo(Parcel source) { 1945 readFromParcel(source); 1946 } 1947 } 1948 1949 /** 1950 * Return general information about the memory state of the system. This 1951 * can be used to help decide how to manage your own memory, though note 1952 * that polling is not recommended and 1953 * {@link android.content.ComponentCallbacks2#onTrimMemory(int) 1954 * ComponentCallbacks2.onTrimMemory(int)} is the preferred way to do this. 1955 * Also see {@link #getMyMemoryState} for how to retrieve the current trim 1956 * level of your process as needed, which gives a better hint for how to 1957 * manage its memory. 1958 */ 1959 public void getMemoryInfo(MemoryInfo outInfo) { 1960 try { 1961 ActivityManagerNative.getDefault().getMemoryInfo(outInfo); 1962 } catch (RemoteException e) { 1963 } 1964 } 1965 1966 /** 1967 * Information you can retrieve about an ActivityStack in the system. 1968 * @hide 1969 */ 1970 public static class StackInfo implements Parcelable { 1971 public int stackId; 1972 public Rect bounds = new Rect(); 1973 public int[] taskIds; 1974 public String[] taskNames; 1975 public Rect[] taskBounds; 1976 public int displayId; 1977 1978 @Override 1979 public int describeContents() { 1980 return 0; 1981 } 1982 1983 @Override 1984 public void writeToParcel(Parcel dest, int flags) { 1985 dest.writeInt(stackId); 1986 dest.writeInt(bounds.left); 1987 dest.writeInt(bounds.top); 1988 dest.writeInt(bounds.right); 1989 dest.writeInt(bounds.bottom); 1990 dest.writeIntArray(taskIds); 1991 dest.writeStringArray(taskNames); 1992 final int boundsCount = taskBounds == null ? 0 : taskBounds.length; 1993 dest.writeInt(boundsCount); 1994 for (int i = 0; i < boundsCount; i++) { 1995 dest.writeInt(taskBounds[i].left); 1996 dest.writeInt(taskBounds[i].top); 1997 dest.writeInt(taskBounds[i].right); 1998 dest.writeInt(taskBounds[i].bottom); 1999 } 2000 dest.writeInt(displayId); 2001 } 2002 2003 public void readFromParcel(Parcel source) { 2004 stackId = source.readInt(); 2005 bounds = new Rect( 2006 source.readInt(), source.readInt(), source.readInt(), source.readInt()); 2007 taskIds = source.createIntArray(); 2008 taskNames = source.createStringArray(); 2009 final int boundsCount = source.readInt(); 2010 if (boundsCount > 0) { 2011 taskBounds = new Rect[boundsCount]; 2012 for (int i = 0; i < boundsCount; i++) { 2013 taskBounds[i] = new Rect(); 2014 taskBounds[i].set( 2015 source.readInt(), source.readInt(), source.readInt(), source.readInt()); 2016 } 2017 } else { 2018 taskBounds = null; 2019 } 2020 displayId = source.readInt(); 2021 } 2022 2023 public static final Creator<StackInfo> CREATOR = new Creator<StackInfo>() { 2024 @Override 2025 public StackInfo createFromParcel(Parcel source) { 2026 return new StackInfo(source); 2027 } 2028 @Override 2029 public StackInfo[] newArray(int size) { 2030 return new StackInfo[size]; 2031 } 2032 }; 2033 2034 public StackInfo() { 2035 } 2036 2037 private StackInfo(Parcel source) { 2038 readFromParcel(source); 2039 } 2040 2041 public String toString(String prefix) { 2042 StringBuilder sb = new StringBuilder(256); 2043 sb.append(prefix); sb.append("Stack id="); sb.append(stackId); 2044 sb.append(" bounds="); sb.append(bounds.toShortString()); 2045 sb.append(" displayId="); sb.append(displayId); 2046 sb.append("\n"); 2047 prefix = prefix + " "; 2048 for (int i = 0; i < taskIds.length; ++i) { 2049 sb.append(prefix); sb.append("taskId="); sb.append(taskIds[i]); 2050 sb.append(": "); sb.append(taskNames[i]); 2051 if (taskBounds != null) { 2052 sb.append(" bounds="); sb.append(taskBounds[i].toShortString()); 2053 } 2054 sb.append("\n"); 2055 } 2056 return sb.toString(); 2057 } 2058 2059 @Override 2060 public String toString() { 2061 return toString(""); 2062 } 2063 } 2064 2065 /** 2066 * @hide 2067 */ 2068 public boolean clearApplicationUserData(String packageName, IPackageDataObserver observer) { 2069 try { 2070 return ActivityManagerNative.getDefault().clearApplicationUserData(packageName, 2071 observer, UserHandle.myUserId()); 2072 } catch (RemoteException e) { 2073 return false; 2074 } 2075 } 2076 2077 /** 2078 * Permits an application to erase its own data from disk. This is equivalent to 2079 * the user choosing to clear the app's data from within the device settings UI. It 2080 * erases all dynamic data associated with the app -- its private data and data in its 2081 * private area on external storage -- but does not remove the installed application 2082 * itself, nor any OBB files. 2083 * 2084 * @return {@code true} if the application successfully requested that the application's 2085 * data be erased; {@code false} otherwise. 2086 */ 2087 public boolean clearApplicationUserData() { 2088 return clearApplicationUserData(mContext.getPackageName(), null); 2089 } 2090 2091 /** 2092 * Information you can retrieve about any processes that are in an error condition. 2093 */ 2094 public static class ProcessErrorStateInfo implements Parcelable { 2095 /** 2096 * Condition codes 2097 */ 2098 public static final int NO_ERROR = 0; 2099 public static final int CRASHED = 1; 2100 public static final int NOT_RESPONDING = 2; 2101 2102 /** 2103 * The condition that the process is in. 2104 */ 2105 public int condition; 2106 2107 /** 2108 * The process name in which the crash or error occurred. 2109 */ 2110 public String processName; 2111 2112 /** 2113 * The pid of this process; 0 if none 2114 */ 2115 public int pid; 2116 2117 /** 2118 * The kernel user-ID that has been assigned to this process; 2119 * currently this is not a unique ID (multiple applications can have 2120 * the same uid). 2121 */ 2122 public int uid; 2123 2124 /** 2125 * The activity name associated with the error, if known. May be null. 2126 */ 2127 public String tag; 2128 2129 /** 2130 * A short message describing the error condition. 2131 */ 2132 public String shortMsg; 2133 2134 /** 2135 * A long message describing the error condition. 2136 */ 2137 public String longMsg; 2138 2139 /** 2140 * The stack trace where the error originated. May be null. 2141 */ 2142 public String stackTrace; 2143 2144 /** 2145 * to be deprecated: This value will always be null. 2146 */ 2147 public byte[] crashData = null; 2148 2149 public ProcessErrorStateInfo() { 2150 } 2151 2152 @Override 2153 public int describeContents() { 2154 return 0; 2155 } 2156 2157 @Override 2158 public void writeToParcel(Parcel dest, int flags) { 2159 dest.writeInt(condition); 2160 dest.writeString(processName); 2161 dest.writeInt(pid); 2162 dest.writeInt(uid); 2163 dest.writeString(tag); 2164 dest.writeString(shortMsg); 2165 dest.writeString(longMsg); 2166 dest.writeString(stackTrace); 2167 } 2168 2169 public void readFromParcel(Parcel source) { 2170 condition = source.readInt(); 2171 processName = source.readString(); 2172 pid = source.readInt(); 2173 uid = source.readInt(); 2174 tag = source.readString(); 2175 shortMsg = source.readString(); 2176 longMsg = source.readString(); 2177 stackTrace = source.readString(); 2178 } 2179 2180 public static final Creator<ProcessErrorStateInfo> CREATOR = 2181 new Creator<ProcessErrorStateInfo>() { 2182 public ProcessErrorStateInfo createFromParcel(Parcel source) { 2183 return new ProcessErrorStateInfo(source); 2184 } 2185 public ProcessErrorStateInfo[] newArray(int size) { 2186 return new ProcessErrorStateInfo[size]; 2187 } 2188 }; 2189 2190 private ProcessErrorStateInfo(Parcel source) { 2191 readFromParcel(source); 2192 } 2193 } 2194 2195 /** 2196 * Returns a list of any processes that are currently in an error condition. The result 2197 * will be null if all processes are running properly at this time. 2198 * 2199 * @return Returns a list of ProcessErrorStateInfo records, or null if there are no 2200 * current error conditions (it will not return an empty list). This list ordering is not 2201 * specified. 2202 */ 2203 public List<ProcessErrorStateInfo> getProcessesInErrorState() { 2204 try { 2205 return ActivityManagerNative.getDefault().getProcessesInErrorState(); 2206 } catch (RemoteException e) { 2207 return null; 2208 } 2209 } 2210 2211 /** 2212 * Information you can retrieve about a running process. 2213 */ 2214 public static class RunningAppProcessInfo implements Parcelable { 2215 /** 2216 * The name of the process that this object is associated with 2217 */ 2218 public String processName; 2219 2220 /** 2221 * The pid of this process; 0 if none 2222 */ 2223 public int pid; 2224 2225 /** 2226 * The user id of this process. 2227 */ 2228 public int uid; 2229 2230 /** 2231 * All packages that have been loaded into the process. 2232 */ 2233 public String pkgList[]; 2234 2235 /** 2236 * Constant for {@link #flags}: this is an app that is unable to 2237 * correctly save its state when going to the background, 2238 * so it can not be killed while in the background. 2239 * @hide 2240 */ 2241 public static final int FLAG_CANT_SAVE_STATE = 1<<0; 2242 2243 /** 2244 * Constant for {@link #flags}: this process is associated with a 2245 * persistent system app. 2246 * @hide 2247 */ 2248 public static final int FLAG_PERSISTENT = 1<<1; 2249 2250 /** 2251 * Constant for {@link #flags}: this process is associated with a 2252 * persistent system app. 2253 * @hide 2254 */ 2255 public static final int FLAG_HAS_ACTIVITIES = 1<<2; 2256 2257 /** 2258 * Flags of information. May be any of 2259 * {@link #FLAG_CANT_SAVE_STATE}. 2260 * @hide 2261 */ 2262 public int flags; 2263 2264 /** 2265 * Last memory trim level reported to the process: corresponds to 2266 * the values supplied to {@link android.content.ComponentCallbacks2#onTrimMemory(int) 2267 * ComponentCallbacks2.onTrimMemory(int)}. 2268 */ 2269 public int lastTrimLevel; 2270 2271 /** 2272 * Constant for {@link #importance}: This process is running the 2273 * foreground UI; that is, it is the thing currently at the top of the screen 2274 * that the user is interacting with. 2275 */ 2276 public static final int IMPORTANCE_FOREGROUND = 100; 2277 2278 /** 2279 * Constant for {@link #importance}: This process is running a foreground 2280 * service, for example to perform music playback even while the user is 2281 * not immediately in the app. This generally indicates that the process 2282 * is doing something the user actively cares about. 2283 */ 2284 public static final int IMPORTANCE_FOREGROUND_SERVICE = 125; 2285 2286 /** 2287 * Constant for {@link #importance}: This process is running the foreground 2288 * UI, but the device is asleep so it is not visible to the user. This means 2289 * the user is not really aware of the process, because they can not see or 2290 * interact with it, but it is quite important because it what they expect to 2291 * return to once unlocking the device. 2292 */ 2293 public static final int IMPORTANCE_TOP_SLEEPING = 150; 2294 2295 /** 2296 * Constant for {@link #importance}: This process is running something 2297 * that is actively visible to the user, though not in the immediate 2298 * foreground. This may be running a window that is behind the current 2299 * foreground (so paused and with its state saved, not interacting with 2300 * the user, but visible to them to some degree); it may also be running 2301 * other services under the system's control that it inconsiders important. 2302 */ 2303 public static final int IMPORTANCE_VISIBLE = 200; 2304 2305 /** 2306 * Constant for {@link #importance}: This process is not something the user 2307 * is directly aware of, but is otherwise perceptable to them to some degree. 2308 */ 2309 public static final int IMPORTANCE_PERCEPTIBLE = 130; 2310 2311 /** 2312 * Constant for {@link #importance}: This process is running an 2313 * application that can not save its state, and thus can't be killed 2314 * while in the background. 2315 * @hide 2316 */ 2317 public static final int IMPORTANCE_CANT_SAVE_STATE = 170; 2318 2319 /** 2320 * Constant for {@link #importance}: This process is contains services 2321 * that should remain running. These are background services apps have 2322 * started, not something the user is aware of, so they may be killed by 2323 * the system relatively freely (though it is generally desired that they 2324 * stay running as long as they want to). 2325 */ 2326 public static final int IMPORTANCE_SERVICE = 300; 2327 2328 /** 2329 * Constant for {@link #importance}: This process process contains 2330 * background code that is expendable. 2331 */ 2332 public static final int IMPORTANCE_BACKGROUND = 400; 2333 2334 /** 2335 * Constant for {@link #importance}: This process is empty of any 2336 * actively running code. 2337 */ 2338 public static final int IMPORTANCE_EMPTY = 500; 2339 2340 /** 2341 * Constant for {@link #importance}: This process does not exist. 2342 */ 2343 public static final int IMPORTANCE_GONE = 1000; 2344 2345 /** @hide */ 2346 public static int procStateToImportance(int procState) { 2347 if (procState == PROCESS_STATE_NONEXISTENT) { 2348 return IMPORTANCE_GONE; 2349 } else if (procState >= PROCESS_STATE_HOME) { 2350 return IMPORTANCE_BACKGROUND; 2351 } else if (procState >= PROCESS_STATE_SERVICE) { 2352 return IMPORTANCE_SERVICE; 2353 } else if (procState > PROCESS_STATE_HEAVY_WEIGHT) { 2354 return IMPORTANCE_CANT_SAVE_STATE; 2355 } else if (procState >= PROCESS_STATE_IMPORTANT_BACKGROUND) { 2356 return IMPORTANCE_PERCEPTIBLE; 2357 } else if (procState >= PROCESS_STATE_IMPORTANT_FOREGROUND) { 2358 return IMPORTANCE_VISIBLE; 2359 } else if (procState >= PROCESS_STATE_TOP_SLEEPING) { 2360 return IMPORTANCE_TOP_SLEEPING; 2361 } else if (procState >= PROCESS_STATE_FOREGROUND_SERVICE) { 2362 return IMPORTANCE_FOREGROUND_SERVICE; 2363 } else { 2364 return IMPORTANCE_FOREGROUND; 2365 } 2366 } 2367 2368 /** 2369 * The relative importance level that the system places on this 2370 * process. May be one of {@link #IMPORTANCE_FOREGROUND}, 2371 * {@link #IMPORTANCE_VISIBLE}, {@link #IMPORTANCE_SERVICE}, 2372 * {@link #IMPORTANCE_BACKGROUND}, or {@link #IMPORTANCE_EMPTY}. These 2373 * constants are numbered so that "more important" values are always 2374 * smaller than "less important" values. 2375 */ 2376 public int importance; 2377 2378 /** 2379 * An additional ordering within a particular {@link #importance} 2380 * category, providing finer-grained information about the relative 2381 * utility of processes within a category. This number means nothing 2382 * except that a smaller values are more recently used (and thus 2383 * more important). Currently an LRU value is only maintained for 2384 * the {@link #IMPORTANCE_BACKGROUND} category, though others may 2385 * be maintained in the future. 2386 */ 2387 public int lru; 2388 2389 /** 2390 * Constant for {@link #importanceReasonCode}: nothing special has 2391 * been specified for the reason for this level. 2392 */ 2393 public static final int REASON_UNKNOWN = 0; 2394 2395 /** 2396 * Constant for {@link #importanceReasonCode}: one of the application's 2397 * content providers is being used by another process. The pid of 2398 * the client process is in {@link #importanceReasonPid} and the 2399 * target provider in this process is in 2400 * {@link #importanceReasonComponent}. 2401 */ 2402 public static final int REASON_PROVIDER_IN_USE = 1; 2403 2404 /** 2405 * Constant for {@link #importanceReasonCode}: one of the application's 2406 * content providers is being used by another process. The pid of 2407 * the client process is in {@link #importanceReasonPid} and the 2408 * target provider in this process is in 2409 * {@link #importanceReasonComponent}. 2410 */ 2411 public static final int REASON_SERVICE_IN_USE = 2; 2412 2413 /** 2414 * The reason for {@link #importance}, if any. 2415 */ 2416 public int importanceReasonCode; 2417 2418 /** 2419 * For the specified values of {@link #importanceReasonCode}, this 2420 * is the process ID of the other process that is a client of this 2421 * process. This will be 0 if no other process is using this one. 2422 */ 2423 public int importanceReasonPid; 2424 2425 /** 2426 * For the specified values of {@link #importanceReasonCode}, this 2427 * is the name of the component that is being used in this process. 2428 */ 2429 public ComponentName importanceReasonComponent; 2430 2431 /** 2432 * When {@link #importanceReasonPid} is non-0, this is the importance 2433 * of the other pid. @hide 2434 */ 2435 public int importanceReasonImportance; 2436 2437 /** 2438 * Current process state, as per PROCESS_STATE_* constants. 2439 * @hide 2440 */ 2441 public int processState; 2442 2443 public RunningAppProcessInfo() { 2444 importance = IMPORTANCE_FOREGROUND; 2445 importanceReasonCode = REASON_UNKNOWN; 2446 processState = PROCESS_STATE_IMPORTANT_FOREGROUND; 2447 } 2448 2449 public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) { 2450 processName = pProcessName; 2451 pid = pPid; 2452 pkgList = pArr; 2453 } 2454 2455 public int describeContents() { 2456 return 0; 2457 } 2458 2459 public void writeToParcel(Parcel dest, int flags) { 2460 dest.writeString(processName); 2461 dest.writeInt(pid); 2462 dest.writeInt(uid); 2463 dest.writeStringArray(pkgList); 2464 dest.writeInt(this.flags); 2465 dest.writeInt(lastTrimLevel); 2466 dest.writeInt(importance); 2467 dest.writeInt(lru); 2468 dest.writeInt(importanceReasonCode); 2469 dest.writeInt(importanceReasonPid); 2470 ComponentName.writeToParcel(importanceReasonComponent, dest); 2471 dest.writeInt(importanceReasonImportance); 2472 dest.writeInt(processState); 2473 } 2474 2475 public void readFromParcel(Parcel source) { 2476 processName = source.readString(); 2477 pid = source.readInt(); 2478 uid = source.readInt(); 2479 pkgList = source.readStringArray(); 2480 flags = source.readInt(); 2481 lastTrimLevel = source.readInt(); 2482 importance = source.readInt(); 2483 lru = source.readInt(); 2484 importanceReasonCode = source.readInt(); 2485 importanceReasonPid = source.readInt(); 2486 importanceReasonComponent = ComponentName.readFromParcel(source); 2487 importanceReasonImportance = source.readInt(); 2488 processState = source.readInt(); 2489 } 2490 2491 public static final Creator<RunningAppProcessInfo> CREATOR = 2492 new Creator<RunningAppProcessInfo>() { 2493 public RunningAppProcessInfo createFromParcel(Parcel source) { 2494 return new RunningAppProcessInfo(source); 2495 } 2496 public RunningAppProcessInfo[] newArray(int size) { 2497 return new RunningAppProcessInfo[size]; 2498 } 2499 }; 2500 2501 private RunningAppProcessInfo(Parcel source) { 2502 readFromParcel(source); 2503 } 2504 } 2505 2506 /** 2507 * Returns a list of application processes installed on external media 2508 * that are running on the device. 2509 * 2510 * <p><b>Note: this method is only intended for debugging or building 2511 * a user-facing process management UI.</b></p> 2512 * 2513 * @return Returns a list of ApplicationInfo records, or null if none 2514 * This list ordering is not specified. 2515 * @hide 2516 */ 2517 public List<ApplicationInfo> getRunningExternalApplications() { 2518 try { 2519 return ActivityManagerNative.getDefault().getRunningExternalApplications(); 2520 } catch (RemoteException e) { 2521 return null; 2522 } 2523 } 2524 2525 /** 2526 * Sets the memory trim mode for a process and schedules a memory trim operation. 2527 * 2528 * <p><b>Note: this method is only intended for testing framework.</b></p> 2529 * 2530 * @return Returns true if successful. 2531 * @hide 2532 */ 2533 public boolean setProcessMemoryTrimLevel(String process, int userId, int level) { 2534 try { 2535 return ActivityManagerNative.getDefault().setProcessMemoryTrimLevel(process, userId, 2536 level); 2537 } catch (RemoteException e) { 2538 return false; 2539 } 2540 } 2541 2542 /** 2543 * Returns a list of application processes that are running on the device. 2544 * 2545 * <p><b>Note: this method is only intended for debugging or building 2546 * a user-facing process management UI.</b></p> 2547 * 2548 * @return Returns a list of RunningAppProcessInfo records, or null if there are no 2549 * running processes (it will not return an empty list). This list ordering is not 2550 * specified. 2551 */ 2552 public List<RunningAppProcessInfo> getRunningAppProcesses() { 2553 try { 2554 return ActivityManagerNative.getDefault().getRunningAppProcesses(); 2555 } catch (RemoteException e) { 2556 return null; 2557 } 2558 } 2559 2560 /** 2561 * Return the importance of a given package name, based on the processes that are 2562 * currently running. The return value is one of the importance constants defined 2563 * in {@link RunningAppProcessInfo}, giving you the highest importance of all the 2564 * processes that this package has code running inside of. If there are no processes 2565 * running its code, {@link RunningAppProcessInfo#IMPORTANCE_GONE} is returned. 2566 * @hide 2567 */ 2568 @SystemApi 2569 public int getPackageImportance(String packageName) { 2570 try { 2571 int procState = ActivityManagerNative.getDefault().getPackageProcessState(packageName, 2572 mContext.getOpPackageName()); 2573 return RunningAppProcessInfo.procStateToImportance(procState); 2574 } catch (RemoteException e) { 2575 return RunningAppProcessInfo.IMPORTANCE_GONE; 2576 } 2577 } 2578 2579 /** 2580 * Return global memory state information for the calling process. This 2581 * does not fill in all fields of the {@link RunningAppProcessInfo}. The 2582 * only fields that will be filled in are 2583 * {@link RunningAppProcessInfo#pid}, 2584 * {@link RunningAppProcessInfo#uid}, 2585 * {@link RunningAppProcessInfo#lastTrimLevel}, 2586 * {@link RunningAppProcessInfo#importance}, 2587 * {@link RunningAppProcessInfo#lru}, and 2588 * {@link RunningAppProcessInfo#importanceReasonCode}. 2589 */ 2590 static public void getMyMemoryState(RunningAppProcessInfo outState) { 2591 try { 2592 ActivityManagerNative.getDefault().getMyMemoryState(outState); 2593 } catch (RemoteException e) { 2594 } 2595 } 2596 2597 /** 2598 * Return information about the memory usage of one or more processes. 2599 * 2600 * <p><b>Note: this method is only intended for debugging or building 2601 * a user-facing process management UI.</b></p> 2602 * 2603 * @param pids The pids of the processes whose memory usage is to be 2604 * retrieved. 2605 * @return Returns an array of memory information, one for each 2606 * requested pid. 2607 */ 2608 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) { 2609 try { 2610 return ActivityManagerNative.getDefault().getProcessMemoryInfo(pids); 2611 } catch (RemoteException e) { 2612 return null; 2613 } 2614 } 2615 2616 /** 2617 * @deprecated This is now just a wrapper for 2618 * {@link #killBackgroundProcesses(String)}; the previous behavior here 2619 * is no longer available to applications because it allows them to 2620 * break other applications by removing their alarms, stopping their 2621 * services, etc. 2622 */ 2623 @Deprecated 2624 public void restartPackage(String packageName) { 2625 killBackgroundProcesses(packageName); 2626 } 2627 2628 /** 2629 * Have the system immediately kill all background processes associated 2630 * with the given package. This is the same as the kernel killing those 2631 * processes to reclaim memory; the system will take care of restarting 2632 * these processes in the future as needed. 2633 * 2634 * <p>You must hold the permission 2635 * {@link android.Manifest.permission#KILL_BACKGROUND_PROCESSES} to be able to 2636 * call this method. 2637 * 2638 * @param packageName The name of the package whose processes are to 2639 * be killed. 2640 */ 2641 public void killBackgroundProcesses(String packageName) { 2642 try { 2643 ActivityManagerNative.getDefault().killBackgroundProcesses(packageName, 2644 UserHandle.myUserId()); 2645 } catch (RemoteException e) { 2646 } 2647 } 2648 2649 /** 2650 * Kills the specified UID. 2651 * @param uid The UID to kill. 2652 * @param reason The reason for the kill. 2653 * 2654 * @hide 2655 */ 2656 @RequiresPermission(Manifest.permission.KILL_UID) 2657 public void killUid(int uid, String reason) { 2658 try { 2659 ActivityManagerNative.getDefault().killUid(UserHandle.getAppId(uid), 2660 UserHandle.getUserId(uid), reason); 2661 } catch (RemoteException e) { 2662 Log.e(TAG, "Couldn't kill uid:" + uid, e); 2663 } 2664 } 2665 2666 /** 2667 * Have the system perform a force stop of everything associated with 2668 * the given application package. All processes that share its uid 2669 * will be killed, all services it has running stopped, all activities 2670 * removed, etc. In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED} 2671 * broadcast will be sent, so that any of its registered alarms can 2672 * be stopped, notifications removed, etc. 2673 * 2674 * <p>You must hold the permission 2675 * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to 2676 * call this method. 2677 * 2678 * @param packageName The name of the package to be stopped. 2679 * @param userId The user for which the running package is to be stopped. 2680 * 2681 * @hide This is not available to third party applications due to 2682 * it allowing them to break other applications by stopping their 2683 * services, removing their alarms, etc. 2684 */ 2685 public void forceStopPackageAsUser(String packageName, int userId) { 2686 try { 2687 ActivityManagerNative.getDefault().forceStopPackage(packageName, userId); 2688 } catch (RemoteException e) { 2689 } 2690 } 2691 2692 /** 2693 * @see #forceStopPackageAsUser(String, int) 2694 * @hide 2695 */ 2696 public void forceStopPackage(String packageName) { 2697 forceStopPackageAsUser(packageName, UserHandle.myUserId()); 2698 } 2699 2700 /** 2701 * Get the device configuration attributes. 2702 */ 2703 public ConfigurationInfo getDeviceConfigurationInfo() { 2704 try { 2705 return ActivityManagerNative.getDefault().getDeviceConfigurationInfo(); 2706 } catch (RemoteException e) { 2707 } 2708 return null; 2709 } 2710 2711 /** 2712 * Get the preferred density of icons for the launcher. This is used when 2713 * custom drawables are created (e.g., for shortcuts). 2714 * 2715 * @return density in terms of DPI 2716 */ 2717 public int getLauncherLargeIconDensity() { 2718 final Resources res = mContext.getResources(); 2719 final int density = res.getDisplayMetrics().densityDpi; 2720 final int sw = res.getConfiguration().smallestScreenWidthDp; 2721 2722 if (sw < 600) { 2723 // Smaller than approx 7" tablets, use the regular icon size. 2724 return density; 2725 } 2726 2727 switch (density) { 2728 case DisplayMetrics.DENSITY_LOW: 2729 return DisplayMetrics.DENSITY_MEDIUM; 2730 case DisplayMetrics.DENSITY_MEDIUM: 2731 return DisplayMetrics.DENSITY_HIGH; 2732 case DisplayMetrics.DENSITY_TV: 2733 return DisplayMetrics.DENSITY_XHIGH; 2734 case DisplayMetrics.DENSITY_HIGH: 2735 return DisplayMetrics.DENSITY_XHIGH; 2736 case DisplayMetrics.DENSITY_XHIGH: 2737 return DisplayMetrics.DENSITY_XXHIGH; 2738 case DisplayMetrics.DENSITY_XXHIGH: 2739 return DisplayMetrics.DENSITY_XHIGH * 2; 2740 default: 2741 // The density is some abnormal value. Return some other 2742 // abnormal value that is a reasonable scaling of it. 2743 return (int)((density*1.5f)+.5f); 2744 } 2745 } 2746 2747 /** 2748 * Get the preferred launcher icon size. This is used when custom drawables 2749 * are created (e.g., for shortcuts). 2750 * 2751 * @return dimensions of square icons in terms of pixels 2752 */ 2753 public int getLauncherLargeIconSize() { 2754 return getLauncherLargeIconSizeInner(mContext); 2755 } 2756 2757 static int getLauncherLargeIconSizeInner(Context context) { 2758 final Resources res = context.getResources(); 2759 final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size); 2760 final int sw = res.getConfiguration().smallestScreenWidthDp; 2761 2762 if (sw < 600) { 2763 // Smaller than approx 7" tablets, use the regular icon size. 2764 return size; 2765 } 2766 2767 final int density = res.getDisplayMetrics().densityDpi; 2768 2769 switch (density) { 2770 case DisplayMetrics.DENSITY_LOW: 2771 return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW; 2772 case DisplayMetrics.DENSITY_MEDIUM: 2773 return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM; 2774 case DisplayMetrics.DENSITY_TV: 2775 return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH; 2776 case DisplayMetrics.DENSITY_HIGH: 2777 return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH; 2778 case DisplayMetrics.DENSITY_XHIGH: 2779 return (size * DisplayMetrics.DENSITY_XXHIGH) / DisplayMetrics.DENSITY_XHIGH; 2780 case DisplayMetrics.DENSITY_XXHIGH: 2781 return (size * DisplayMetrics.DENSITY_XHIGH*2) / DisplayMetrics.DENSITY_XXHIGH; 2782 default: 2783 // The density is some abnormal value. Return some other 2784 // abnormal value that is a reasonable scaling of it. 2785 return (int)((size*1.5f) + .5f); 2786 } 2787 } 2788 2789 /** 2790 * Returns "true" if the user interface is currently being messed with 2791 * by a monkey. 2792 */ 2793 public static boolean isUserAMonkey() { 2794 try { 2795 return ActivityManagerNative.getDefault().isUserAMonkey(); 2796 } catch (RemoteException e) { 2797 } 2798 return false; 2799 } 2800 2801 /** 2802 * Returns "true" if device is running in a test harness. 2803 */ 2804 public static boolean isRunningInTestHarness() { 2805 return SystemProperties.getBoolean("ro.test_harness", false); 2806 } 2807 2808 /** 2809 * Returns the launch count of each installed package. 2810 * 2811 * @hide 2812 */ 2813 /*public Map<String, Integer> getAllPackageLaunchCounts() { 2814 try { 2815 IUsageStats usageStatsService = IUsageStats.Stub.asInterface( 2816 ServiceManager.getService("usagestats")); 2817 if (usageStatsService == null) { 2818 return new HashMap<String, Integer>(); 2819 } 2820 2821 UsageStats.PackageStats[] allPkgUsageStats = usageStatsService.getAllPkgUsageStats( 2822 ActivityThread.currentPackageName()); 2823 if (allPkgUsageStats == null) { 2824 return new HashMap<String, Integer>(); 2825 } 2826 2827 Map<String, Integer> launchCounts = new HashMap<String, Integer>(); 2828 for (UsageStats.PackageStats pkgUsageStats : allPkgUsageStats) { 2829 launchCounts.put(pkgUsageStats.getPackageName(), pkgUsageStats.getLaunchCount()); 2830 } 2831 2832 return launchCounts; 2833 } catch (RemoteException e) { 2834 Log.w(TAG, "Could not query launch counts", e); 2835 return new HashMap<String, Integer>(); 2836 } 2837 }*/ 2838 2839 /** @hide */ 2840 public static int checkComponentPermission(String permission, int uid, 2841 int owningUid, boolean exported) { 2842 // Root, system server get to do everything. 2843 final int appId = UserHandle.getAppId(uid); 2844 if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) { 2845 return PackageManager.PERMISSION_GRANTED; 2846 } 2847 // Isolated processes don't get any permissions. 2848 if (UserHandle.isIsolated(uid)) { 2849 return PackageManager.PERMISSION_DENIED; 2850 } 2851 // If there is a uid that owns whatever is being accessed, it has 2852 // blanket access to it regardless of the permissions it requires. 2853 if (owningUid >= 0 && UserHandle.isSameApp(uid, owningUid)) { 2854 return PackageManager.PERMISSION_GRANTED; 2855 } 2856 // If the target is not exported, then nobody else can get to it. 2857 if (!exported) { 2858 /* 2859 RuntimeException here = new RuntimeException("here"); 2860 here.fillInStackTrace(); 2861 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid, 2862 here); 2863 */ 2864 return PackageManager.PERMISSION_DENIED; 2865 } 2866 if (permission == null) { 2867 return PackageManager.PERMISSION_GRANTED; 2868 } 2869 try { 2870 return AppGlobals.getPackageManager() 2871 .checkUidPermission(permission, uid); 2872 } catch (RemoteException e) { 2873 // Should never happen, but if it does... deny! 2874 Slog.e(TAG, "PackageManager is dead?!?", e); 2875 } 2876 return PackageManager.PERMISSION_DENIED; 2877 } 2878 2879 /** @hide */ 2880 public static int checkUidPermission(String permission, int uid) { 2881 try { 2882 return AppGlobals.getPackageManager() 2883 .checkUidPermission(permission, uid); 2884 } catch (RemoteException e) { 2885 // Should never happen, but if it does... deny! 2886 Slog.e(TAG, "PackageManager is dead?!?", e); 2887 } 2888 return PackageManager.PERMISSION_DENIED; 2889 } 2890 2891 /** 2892 * @hide 2893 * Helper for dealing with incoming user arguments to system service calls. 2894 * Takes care of checking permissions and converting USER_CURRENT to the 2895 * actual current user. 2896 * 2897 * @param callingPid The pid of the incoming call, as per Binder.getCallingPid(). 2898 * @param callingUid The uid of the incoming call, as per Binder.getCallingUid(). 2899 * @param userId The user id argument supplied by the caller -- this is the user 2900 * they want to run as. 2901 * @param allowAll If true, we will allow USER_ALL. This means you must be prepared 2902 * to get a USER_ALL returned and deal with it correctly. If false, 2903 * an exception will be thrown if USER_ALL is supplied. 2904 * @param requireFull If true, the caller must hold 2905 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} to be able to run as a 2906 * different user than their current process; otherwise they must hold 2907 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS}. 2908 * @param name Optional textual name of the incoming call; only for generating error messages. 2909 * @param callerPackage Optional package name of caller; only for error messages. 2910 * 2911 * @return Returns the user ID that the call should run as. Will always be a concrete 2912 * user number, unless <var>allowAll</var> is true in which case it could also be 2913 * USER_ALL. 2914 */ 2915 public static int handleIncomingUser(int callingPid, int callingUid, int userId, 2916 boolean allowAll, boolean requireFull, String name, String callerPackage) { 2917 if (UserHandle.getUserId(callingUid) == userId) { 2918 return userId; 2919 } 2920 try { 2921 return ActivityManagerNative.getDefault().handleIncomingUser(callingPid, 2922 callingUid, userId, allowAll, requireFull, name, callerPackage); 2923 } catch (RemoteException e) { 2924 throw new SecurityException("Failed calling activity manager", e); 2925 } 2926 } 2927 2928 /** 2929 * Gets the userId of the current foreground user. Requires system permissions. 2930 * @hide 2931 */ 2932 @SystemApi 2933 public static int getCurrentUser() { 2934 UserInfo ui; 2935 try { 2936 ui = ActivityManagerNative.getDefault().getCurrentUser(); 2937 return ui != null ? ui.id : 0; 2938 } catch (RemoteException e) { 2939 return 0; 2940 } 2941 } 2942 2943 /** 2944 * @param userid the user's id. Zero indicates the default user. 2945 * @hide 2946 */ 2947 public boolean switchUser(int userid) { 2948 try { 2949 return ActivityManagerNative.getDefault().switchUser(userid); 2950 } catch (RemoteException e) { 2951 return false; 2952 } 2953 } 2954 2955 /** 2956 * Return whether the given user is actively running. This means that 2957 * the user is in the "started" state, not "stopped" -- it is currently 2958 * allowed to run code through scheduled alarms, receiving broadcasts, 2959 * etc. A started user may be either the current foreground user or a 2960 * background user; the result here does not distinguish between the two. 2961 * @param userid the user's id. Zero indicates the default user. 2962 * @hide 2963 */ 2964 public boolean isUserRunning(int userid) { 2965 try { 2966 return ActivityManagerNative.getDefault().isUserRunning(userid, false); 2967 } catch (RemoteException e) { 2968 return false; 2969 } 2970 } 2971 2972 /** 2973 * Perform a system dump of various state associated with the given application 2974 * package name. This call blocks while the dump is being performed, so should 2975 * not be done on a UI thread. The data will be written to the given file 2976 * descriptor as text. An application must hold the 2977 * {@link android.Manifest.permission#DUMP} permission to make this call. 2978 * @param fd The file descriptor that the dump should be written to. The file 2979 * descriptor is <em>not</em> closed by this function; the caller continues to 2980 * own it. 2981 * @param packageName The name of the package that is to be dumped. 2982 */ 2983 public void dumpPackageState(FileDescriptor fd, String packageName) { 2984 dumpPackageStateStatic(fd, packageName); 2985 } 2986 2987 /** 2988 * @hide 2989 */ 2990 public static void dumpPackageStateStatic(FileDescriptor fd, String packageName) { 2991 FileOutputStream fout = new FileOutputStream(fd); 2992 PrintWriter pw = new FastPrintWriter(fout); 2993 dumpService(pw, fd, "package", new String[] { packageName }); 2994 pw.println(); 2995 dumpService(pw, fd, Context.ACTIVITY_SERVICE, new String[] { 2996 "-a", "package", packageName }); 2997 pw.println(); 2998 dumpService(pw, fd, "meminfo", new String[] { "--local", "--package", packageName }); 2999 pw.println(); 3000 dumpService(pw, fd, ProcessStats.SERVICE_NAME, new String[] { packageName }); 3001 pw.println(); 3002 dumpService(pw, fd, "usagestats", new String[] { "--packages", packageName }); 3003 pw.println(); 3004 dumpService(pw, fd, BatteryStats.SERVICE_NAME, new String[] { packageName }); 3005 pw.flush(); 3006 } 3007 3008 private static void dumpService(PrintWriter pw, FileDescriptor fd, String name, String[] args) { 3009 pw.print("DUMP OF SERVICE "); pw.print(name); pw.println(":"); 3010 IBinder service = ServiceManager.checkService(name); 3011 if (service == null) { 3012 pw.println(" (Service not found)"); 3013 return; 3014 } 3015 TransferPipe tp = null; 3016 try { 3017 pw.flush(); 3018 tp = new TransferPipe(); 3019 tp.setBufferPrefix(" "); 3020 service.dumpAsync(tp.getWriteFd().getFileDescriptor(), args); 3021 tp.go(fd, 10000); 3022 } catch (Throwable e) { 3023 if (tp != null) { 3024 tp.kill(); 3025 } 3026 pw.println("Failure dumping service:"); 3027 e.printStackTrace(pw); 3028 } 3029 } 3030 3031 /** 3032 * Request that the system start watching for the calling process to exceed a pss 3033 * size as given here. Once called, the system will look for any occasions where it 3034 * sees the associated process with a larger pss size and, when this happens, automatically 3035 * pull a heap dump from it and allow the user to share the data. Note that this request 3036 * continues running even if the process is killed and restarted. To remove the watch, 3037 * use {@link #clearWatchHeapLimit()}. 3038 * 3039 * <p>This API only work if the calling process has been marked as 3040 * {@link ApplicationInfo#FLAG_DEBUGGABLE} or this is running on a debuggable 3041 * (userdebug or eng) build.</p> 3042 * 3043 * <p>Callers can optionally implement {@link #ACTION_REPORT_HEAP_LIMIT} to directly 3044 * handle heap limit reports themselves.</p> 3045 * 3046 * @param pssSize The size in bytes to set the limit at. 3047 */ 3048 public void setWatchHeapLimit(long pssSize) { 3049 try { 3050 ActivityManagerNative.getDefault().setDumpHeapDebugLimit(null, 0, pssSize, 3051 mContext.getPackageName()); 3052 } catch (RemoteException e) { 3053 } 3054 } 3055 3056 /** 3057 * Action an app can implement to handle reports from {@link #setWatchHeapLimit(long)}. 3058 * If your package has an activity handling this action, it will be launched with the 3059 * heap data provided to it the same way as {@link Intent#ACTION_SEND}. Note that to 3060 * match the activty must support this action and a MIME type of "*/*". 3061 */ 3062 public static final String ACTION_REPORT_HEAP_LIMIT = "android.app.action.REPORT_HEAP_LIMIT"; 3063 3064 /** 3065 * Clear a heap watch limit previously set by {@link #setWatchHeapLimit(long)}. 3066 */ 3067 public void clearWatchHeapLimit() { 3068 try { 3069 ActivityManagerNative.getDefault().setDumpHeapDebugLimit(null, 0, 0, null); 3070 } catch (RemoteException e) { 3071 } 3072 } 3073 3074 /** 3075 * @hide 3076 */ 3077 public void startLockTaskMode(int taskId) { 3078 try { 3079 ActivityManagerNative.getDefault().startLockTaskMode(taskId); 3080 } catch (RemoteException e) { 3081 } 3082 } 3083 3084 /** 3085 * @hide 3086 */ 3087 public void stopLockTaskMode() { 3088 try { 3089 ActivityManagerNative.getDefault().stopLockTaskMode(); 3090 } catch (RemoteException e) { 3091 } 3092 } 3093 3094 /** 3095 * Return whether currently in lock task mode. When in this mode 3096 * no new tasks can be created or switched to. 3097 * 3098 * @see Activity#startLockTask() 3099 * 3100 * @deprecated Use {@link #getLockTaskModeState} instead. 3101 */ 3102 public boolean isInLockTaskMode() { 3103 return getLockTaskModeState() != LOCK_TASK_MODE_NONE; 3104 } 3105 3106 /** 3107 * Return the current state of task locking. The three possible outcomes 3108 * are {@link #LOCK_TASK_MODE_NONE}, {@link #LOCK_TASK_MODE_LOCKED} 3109 * and {@link #LOCK_TASK_MODE_PINNED}. 3110 * 3111 * @see Activity#startLockTask() 3112 */ 3113 public int getLockTaskModeState() { 3114 try { 3115 return ActivityManagerNative.getDefault().getLockTaskModeState(); 3116 } catch (RemoteException e) { 3117 return ActivityManager.LOCK_TASK_MODE_NONE; 3118 } 3119 } 3120 3121 /** 3122 * The AppTask allows you to manage your own application's tasks. 3123 * See {@link android.app.ActivityManager#getAppTasks()} 3124 */ 3125 public static class AppTask { 3126 private IAppTask mAppTaskImpl; 3127 3128 /** @hide */ 3129 public AppTask(IAppTask task) { 3130 mAppTaskImpl = task; 3131 } 3132 3133 /** 3134 * Finishes all activities in this task and removes it from the recent tasks list. 3135 */ 3136 public void finishAndRemoveTask() { 3137 try { 3138 mAppTaskImpl.finishAndRemoveTask(); 3139 } catch (RemoteException e) { 3140 Slog.e(TAG, "Invalid AppTask", e); 3141 } 3142 } 3143 3144 /** 3145 * Get the RecentTaskInfo associated with this task. 3146 * 3147 * @return The RecentTaskInfo for this task, or null if the task no longer exists. 3148 */ 3149 public RecentTaskInfo getTaskInfo() { 3150 try { 3151 return mAppTaskImpl.getTaskInfo(); 3152 } catch (RemoteException e) { 3153 Slog.e(TAG, "Invalid AppTask", e); 3154 return null; 3155 } 3156 } 3157 3158 /** 3159 * Bring this task to the foreground. If it contains activities, they will be 3160 * brought to the foreground with it and their instances re-created if needed. 3161 * If it doesn't contain activities, the root activity of the task will be 3162 * re-launched. 3163 */ 3164 public void moveToFront() { 3165 try { 3166 mAppTaskImpl.moveToFront(); 3167 } catch (RemoteException e) { 3168 Slog.e(TAG, "Invalid AppTask", e); 3169 } 3170 } 3171 3172 /** 3173 * Start an activity in this task. Brings the task to the foreground. If this task 3174 * is not currently active (that is, its id < 0), then a new activity for the given 3175 * Intent will be launched as the root of the task and the task brought to the 3176 * foreground. Otherwise, if this task is currently active and the Intent does not specify 3177 * an activity to launch in a new task, then a new activity for the given Intent will 3178 * be launched on top of the task and the task brought to the foreground. If this 3179 * task is currently active and the Intent specifies {@link Intent#FLAG_ACTIVITY_NEW_TASK} 3180 * or would otherwise be launched in to a new task, then the activity not launched but 3181 * this task be brought to the foreground and a new intent delivered to the top 3182 * activity if appropriate. 3183 * 3184 * <p>In other words, you generally want to use an Intent here that does not specify 3185 * {@link Intent#FLAG_ACTIVITY_NEW_TASK} or {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT}, 3186 * and let the system do the right thing.</p> 3187 * 3188 * @param intent The Intent describing the new activity to be launched on the task. 3189 * @param options Optional launch options. 3190 * 3191 * @see Activity#startActivity(android.content.Intent, android.os.Bundle) 3192 */ 3193 public void startActivity(Context context, Intent intent, Bundle options) { 3194 ActivityThread thread = ActivityThread.currentActivityThread(); 3195 thread.getInstrumentation().execStartActivityFromAppTask(context, 3196 thread.getApplicationThread(), mAppTaskImpl, intent, options); 3197 } 3198 3199 /** 3200 * Modify the {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag in the root 3201 * Intent of this AppTask. 3202 * 3203 * @param exclude If true, {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} will 3204 * be set; otherwise, it will be cleared. 3205 */ 3206 public void setExcludeFromRecents(boolean exclude) { 3207 try { 3208 mAppTaskImpl.setExcludeFromRecents(exclude); 3209 } catch (RemoteException e) { 3210 Slog.e(TAG, "Invalid AppTask", e); 3211 } 3212 } 3213 } 3214} 3215