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