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