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