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