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