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 17 package android.app; 18 19 import android.annotation.NonNull; 20 import android.annotation.Nullable; 21 import android.annotation.SystemApi; 22 import android.graphics.Canvas; 23 import android.graphics.Matrix; 24 import android.graphics.Point; 25 import android.os.BatteryStats; 26 import android.os.IBinder; 27 import android.os.ParcelFileDescriptor; 28 29 import com.android.internal.app.ProcessStats; 30 import com.android.internal.os.TransferPipe; 31 import com.android.internal.util.FastPrintWriter; 32 33 import android.content.ComponentName; 34 import android.content.Context; 35 import android.content.Intent; 36 import android.content.pm.ApplicationInfo; 37 import android.content.pm.ConfigurationInfo; 38 import android.content.pm.IPackageDataObserver; 39 import android.content.pm.PackageManager; 40 import android.content.pm.UserInfo; 41 import android.content.res.Resources; 42 import android.graphics.Bitmap; 43 import android.graphics.Color; 44 import android.graphics.Rect; 45 import android.os.Bundle; 46 import android.os.Debug; 47 import android.os.Handler; 48 import android.os.Parcel; 49 import android.os.Parcelable; 50 import android.os.Process; 51 import android.os.RemoteException; 52 import android.os.ServiceManager; 53 import android.os.SystemProperties; 54 import android.os.UserHandle; 55 import android.text.TextUtils; 56 import android.util.DisplayMetrics; 57 import android.util.Size; 58 import android.util.Slog; 59 import org.xmlpull.v1.XmlSerializer; 60 61 import java.io.FileDescriptor; 62 import java.io.FileOutputStream; 63 import java.io.IOException; 64 import java.io.PrintWriter; 65 import java.util.ArrayList; 66 import java.util.List; 67 68 /** 69 * Interact with the overall activities running in the system. 70 */ 71 public 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 * Type for IActivityManaqer.getIntentSender: this PendingIntent is 217 * for a sendBroadcast operation. 218 * @hide 219 */ 220 public static final int INTENT_SENDER_BROADCAST = 1; 221 222 /** 223 * Type for IActivityManaqer.getIntentSender: this PendingIntent is 224 * for a startActivity operation. 225 * @hide 226 */ 227 public static final int INTENT_SENDER_ACTIVITY = 2; 228 229 /** 230 * Type for IActivityManaqer.getIntentSender: this PendingIntent is 231 * for an activity result operation. 232 * @hide 233 */ 234 public static final int INTENT_SENDER_ACTIVITY_RESULT = 3; 235 236 /** 237 * Type for IActivityManaqer.getIntentSender: this PendingIntent is 238 * for a startService operation. 239 * @hide 240 */ 241 public static final int INTENT_SENDER_SERVICE = 4; 242 243 /** @hide User operation call: success! */ 244 public static final int USER_OP_SUCCESS = 0; 245 246 /** @hide User operation call: given user id is not known. */ 247 public static final int USER_OP_UNKNOWN_USER = -1; 248 249 /** @hide User operation call: given user id is the current user, can't be stopped. */ 250 public static final int USER_OP_IS_CURRENT = -2; 251 252 /** @hide Process is a persistent system process. */ 253 public static final int PROCESS_STATE_PERSISTENT = 0; 254 255 /** @hide Process is a persistent system process and is doing UI. */ 256 public static final int PROCESS_STATE_PERSISTENT_UI = 1; 257 258 /** @hide Process is hosting the current top activities. Note that this covers 259 * all activities that are visible to the user. */ 260 public static final int PROCESS_STATE_TOP = 2; 261 262 /** @hide Process is important to the user, and something they are aware of. */ 263 public static final int PROCESS_STATE_IMPORTANT_FOREGROUND = 3; 264 265 /** @hide Process is important to the user, but not something they are aware of. */ 266 public static final int PROCESS_STATE_IMPORTANT_BACKGROUND = 4; 267 268 /** @hide Process is in the background running a backup/restore operation. */ 269 public static final int PROCESS_STATE_BACKUP = 5; 270 271 /** @hide Process is in the background, but it can't restore its state so we want 272 * to try to avoid killing it. */ 273 public static final int PROCESS_STATE_HEAVY_WEIGHT = 6; 274 275 /** @hide Process is in the background running a service. Unlike oom_adj, this level 276 * is used for both the normal running in background state and the executing 277 * operations state. */ 278 public static final int PROCESS_STATE_SERVICE = 7; 279 280 /** @hide Process is in the background running a receiver. Note that from the 281 * perspective of oom_adj receivers run at a higher foreground level, but for our 282 * prioritization here that is not necessary and putting them below services means 283 * many fewer changes in some process states as they receive broadcasts. */ 284 public static final int PROCESS_STATE_RECEIVER = 8; 285 286 /** @hide Process is in the background but hosts the home activity. */ 287 public static final int PROCESS_STATE_HOME = 9; 288 289 /** @hide Process is in the background but hosts the last shown activity. */ 290 public static final int PROCESS_STATE_LAST_ACTIVITY = 10; 291 292 /** @hide Process is being cached for later use and contains activities. */ 293 public static final int PROCESS_STATE_CACHED_ACTIVITY = 11; 294 295 /** @hide Process is being cached for later use and is a client of another cached 296 * process that contains activities. */ 297 public static final int PROCESS_STATE_CACHED_ACTIVITY_CLIENT = 12; 298 299 /** @hide Process is being cached for later use and is empty. */ 300 public static final int PROCESS_STATE_CACHED_EMPTY = 13; 301 302 Point mAppTaskThumbnailSize; 303 304 /*package*/ ActivityManager(Context context, Handler handler) { 305 mContext = context; 306 mHandler = handler; 307 } 308 309 /** 310 * Screen compatibility mode: the application most always run in 311 * compatibility mode. 312 * @hide 313 */ 314 public static final int COMPAT_MODE_ALWAYS = -1; 315 316 /** 317 * Screen compatibility mode: the application can never run in 318 * compatibility mode. 319 * @hide 320 */ 321 public static final int COMPAT_MODE_NEVER = -2; 322 323 /** 324 * Screen compatibility mode: unknown. 325 * @hide 326 */ 327 public static final int COMPAT_MODE_UNKNOWN = -3; 328 329 /** 330 * Screen compatibility mode: the application currently has compatibility 331 * mode disabled. 332 * @hide 333 */ 334 public static final int COMPAT_MODE_DISABLED = 0; 335 336 /** 337 * Screen compatibility mode: the application currently has compatibility 338 * mode enabled. 339 * @hide 340 */ 341 public static final int COMPAT_MODE_ENABLED = 1; 342 343 /** 344 * Screen compatibility mode: request to toggle the application's 345 * compatibility mode. 346 * @hide 347 */ 348 public static final int COMPAT_MODE_TOGGLE = 2; 349 350 /** @hide */ 351 public int getFrontActivityScreenCompatMode() { 352 try { 353 return ActivityManagerNative.getDefault().getFrontActivityScreenCompatMode(); 354 } catch (RemoteException e) { 355 // System dead, we will be dead too soon! 356 return 0; 357 } 358 } 359 360 /** @hide */ 361 public void setFrontActivityScreenCompatMode(int mode) { 362 try { 363 ActivityManagerNative.getDefault().setFrontActivityScreenCompatMode(mode); 364 } catch (RemoteException e) { 365 // System dead, we will be dead too soon! 366 } 367 } 368 369 /** @hide */ 370 public int getPackageScreenCompatMode(String packageName) { 371 try { 372 return ActivityManagerNative.getDefault().getPackageScreenCompatMode(packageName); 373 } catch (RemoteException e) { 374 // System dead, we will be dead too soon! 375 return 0; 376 } 377 } 378 379 /** @hide */ 380 public void setPackageScreenCompatMode(String packageName, int mode) { 381 try { 382 ActivityManagerNative.getDefault().setPackageScreenCompatMode(packageName, mode); 383 } catch (RemoteException e) { 384 // System dead, we will be dead too soon! 385 } 386 } 387 388 /** @hide */ 389 public boolean getPackageAskScreenCompat(String packageName) { 390 try { 391 return ActivityManagerNative.getDefault().getPackageAskScreenCompat(packageName); 392 } catch (RemoteException e) { 393 // System dead, we will be dead too soon! 394 return false; 395 } 396 } 397 398 /** @hide */ 399 public void setPackageAskScreenCompat(String packageName, boolean ask) { 400 try { 401 ActivityManagerNative.getDefault().setPackageAskScreenCompat(packageName, ask); 402 } catch (RemoteException e) { 403 // System dead, we will be dead too soon! 404 } 405 } 406 407 /** 408 * Return the approximate per-application memory class of the current 409 * device. This gives you an idea of how hard a memory limit you should 410 * impose on your application to let the overall system work best. The 411 * returned value is in megabytes; the baseline Android memory class is 412 * 16 (which happens to be the Java heap limit of those devices); some 413 * device with more memory may return 24 or even higher numbers. 414 */ 415 public int getMemoryClass() { 416 return staticGetMemoryClass(); 417 } 418 419 /** @hide */ 420 static public int staticGetMemoryClass() { 421 // Really brain dead right now -- just take this from the configured 422 // vm heap size, and assume it is in megabytes and thus ends with "m". 423 String vmHeapSize = SystemProperties.get("dalvik.vm.heapgrowthlimit", ""); 424 if (vmHeapSize != null && !"".equals(vmHeapSize)) { 425 return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1)); 426 } 427 return staticGetLargeMemoryClass(); 428 } 429 430 /** 431 * Return the approximate per-application memory class of the current 432 * device when an application is running with a large heap. This is the 433 * space available for memory-intensive applications; most applications 434 * should not need this amount of memory, and should instead stay with the 435 * {@link #getMemoryClass()} limit. The returned value is in megabytes. 436 * This may be the same size as {@link #getMemoryClass()} on memory 437 * constrained devices, or it may be significantly larger on devices with 438 * a large amount of available RAM. 439 * 440 * <p>The is the size of the application's Dalvik heap if it has 441 * specified <code>android:largeHeap="true"</code> in its manifest. 442 */ 443 public int getLargeMemoryClass() { 444 return staticGetLargeMemoryClass(); 445 } 446 447 /** @hide */ 448 static public int staticGetLargeMemoryClass() { 449 // Really brain dead right now -- just take this from the configured 450 // vm heap size, and assume it is in megabytes and thus ends with "m". 451 String vmHeapSize = SystemProperties.get("dalvik.vm.heapsize", "16m"); 452 return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length() - 1)); 453 } 454 455 /** 456 * Returns true if this is a low-RAM device. Exactly whether a device is low-RAM 457 * is ultimately up to the device configuration, but currently it generally means 458 * something in the class of a 512MB device with about a 800x480 or less screen. 459 * This is mostly intended to be used by apps to determine whether they should turn 460 * off certain features that require more RAM. 461 */ 462 public boolean isLowRamDevice() { 463 return isLowRamDeviceStatic(); 464 } 465 466 /** @hide */ 467 public static boolean isLowRamDeviceStatic() { 468 return "true".equals(SystemProperties.get("ro.config.low_ram", "false")); 469 } 470 471 /** 472 * Used by persistent processes to determine if they are running on a 473 * higher-end device so should be okay using hardware drawing acceleration 474 * (which tends to consume a lot more RAM). 475 * @hide 476 */ 477 static public boolean isHighEndGfx() { 478 return !isLowRamDeviceStatic() && 479 !Resources.getSystem().getBoolean(com.android.internal.R.bool.config_avoidGfxAccel); 480 } 481 482 /** 483 * Return the maximum number of recents entries that we will maintain and show. 484 * @hide 485 */ 486 static public int getMaxRecentTasksStatic() { 487 if (gMaxRecentTasks < 0) { 488 return gMaxRecentTasks = isLowRamDeviceStatic() ? 50 : 100; 489 } 490 return gMaxRecentTasks; 491 } 492 493 /** 494 * Return the default limit on the number of recents that an app can make. 495 * @hide 496 */ 497 static public int getDefaultAppRecentsLimitStatic() { 498 return getMaxRecentTasksStatic() / 6; 499 } 500 501 /** 502 * Return the maximum limit on the number of recents that an app can make. 503 * @hide 504 */ 505 static public int getMaxAppRecentsLimitStatic() { 506 return getMaxRecentTasksStatic() / 2; 507 } 508 509 /** 510 * Information you can set and retrieve about the current activity within the recent task list. 511 */ 512 public static class TaskDescription implements Parcelable { 513 /** @hide */ 514 public static final String ATTR_TASKDESCRIPTION_PREFIX = "task_description_"; 515 private static final String ATTR_TASKDESCRIPTIONLABEL = 516 ATTR_TASKDESCRIPTION_PREFIX + "label"; 517 private static final String ATTR_TASKDESCRIPTIONCOLOR = 518 ATTR_TASKDESCRIPTION_PREFIX + "color"; 519 private static final String ATTR_TASKDESCRIPTIONICONFILENAME = 520 ATTR_TASKDESCRIPTION_PREFIX + "icon_filename"; 521 522 private String mLabel; 523 private Bitmap mIcon; 524 private String mIconFilename; 525 private int mColorPrimary; 526 527 /** 528 * Creates the TaskDescription to the specified values. 529 * 530 * @param label A label and description of the current state of this task. 531 * @param icon An icon that represents the current state of this task. 532 * @param colorPrimary A color to override the theme's primary color. This color must be opaque. 533 */ 534 public TaskDescription(String label, Bitmap icon, int colorPrimary) { 535 if ((colorPrimary != 0) && (Color.alpha(colorPrimary) != 255)) { 536 throw new RuntimeException("A TaskDescription's primary color should be opaque"); 537 } 538 539 mLabel = label; 540 mIcon = icon; 541 mColorPrimary = colorPrimary; 542 } 543 544 /** @hide */ 545 public TaskDescription(String label, int colorPrimary, String iconFilename) { 546 this(label, null, colorPrimary); 547 mIconFilename = iconFilename; 548 } 549 550 /** 551 * Creates the TaskDescription to the specified values. 552 * 553 * @param label A label and description of the current state of this activity. 554 * @param icon An icon that represents the current state of this activity. 555 */ 556 public TaskDescription(String label, Bitmap icon) { 557 this(label, icon, 0); 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 */ 565 public TaskDescription(String label) { 566 this(label, null, 0); 567 } 568 569 /** 570 * Creates an empty TaskDescription. 571 */ 572 public TaskDescription() { 573 this(null, null, 0); 574 } 575 576 /** 577 * Creates a copy of another TaskDescription. 578 */ 579 public TaskDescription(TaskDescription td) { 580 mLabel = td.mLabel; 581 mIcon = td.mIcon; 582 mColorPrimary = td.mColorPrimary; 583 mIconFilename = td.mIconFilename; 584 } 585 586 private TaskDescription(Parcel source) { 587 readFromParcel(source); 588 } 589 590 /** 591 * Sets the label for this task description. 592 * @hide 593 */ 594 public void setLabel(String label) { 595 mLabel = label; 596 } 597 598 /** 599 * Sets the primary color for this task description. 600 * @hide 601 */ 602 public void setPrimaryColor(int primaryColor) { 603 // Ensure that the given color is valid 604 if ((primaryColor != 0) && (Color.alpha(primaryColor) != 255)) { 605 throw new RuntimeException("A TaskDescription's primary color should be opaque"); 606 } 607 mColorPrimary = primaryColor; 608 } 609 610 /** 611 * Sets the icon for this task description. 612 * @hide 613 */ 614 public void setIcon(Bitmap icon) { 615 mIcon = icon; 616 } 617 618 /** 619 * Moves the icon bitmap reference from an actual Bitmap to a file containing the 620 * bitmap. 621 * @hide 622 */ 623 public void setIconFilename(String iconFilename) { 624 mIconFilename = iconFilename; 625 mIcon = null; 626 } 627 628 /** 629 * @return The label and description of the current state of this task. 630 */ 631 public String getLabel() { 632 return mLabel; 633 } 634 635 /** 636 * @return The icon that represents the current state of this task. 637 */ 638 public Bitmap getIcon() { 639 if (mIcon != null) { 640 return mIcon; 641 } 642 return loadTaskDescriptionIcon(mIconFilename); 643 } 644 645 /** @hide */ 646 public String getIconFilename() { 647 return mIconFilename; 648 } 649 650 /** @hide */ 651 public Bitmap getInMemoryIcon() { 652 return mIcon; 653 } 654 655 /** @hide */ 656 public static Bitmap loadTaskDescriptionIcon(String iconFilename) { 657 if (iconFilename != null) { 658 try { 659 return ActivityManagerNative.getDefault(). 660 getTaskDescriptionIcon(iconFilename); 661 } catch (RemoteException e) { 662 } 663 } 664 return null; 665 } 666 667 /** 668 * @return The color override on the theme's primary color. 669 */ 670 public int getPrimaryColor() { 671 return mColorPrimary; 672 } 673 674 /** @hide */ 675 public void saveToXml(XmlSerializer out) throws IOException { 676 if (mLabel != null) { 677 out.attribute(null, ATTR_TASKDESCRIPTIONLABEL, mLabel); 678 } 679 if (mColorPrimary != 0) { 680 out.attribute(null, ATTR_TASKDESCRIPTIONCOLOR, Integer.toHexString(mColorPrimary)); 681 } 682 if (mIconFilename != null) { 683 out.attribute(null, ATTR_TASKDESCRIPTIONICONFILENAME, mIconFilename); 684 } 685 } 686 687 /** @hide */ 688 public void restoreFromXml(String attrName, String attrValue) { 689 if (ATTR_TASKDESCRIPTIONLABEL.equals(attrName)) { 690 setLabel(attrValue); 691 } else if (ATTR_TASKDESCRIPTIONCOLOR.equals(attrName)) { 692 setPrimaryColor((int) Long.parseLong(attrValue, 16)); 693 } else if (ATTR_TASKDESCRIPTIONICONFILENAME.equals(attrName)) { 694 setIconFilename(attrValue); 695 } 696 } 697 698 @Override 699 public int describeContents() { 700 return 0; 701 } 702 703 @Override 704 public void writeToParcel(Parcel dest, int flags) { 705 if (mLabel == null) { 706 dest.writeInt(0); 707 } else { 708 dest.writeInt(1); 709 dest.writeString(mLabel); 710 } 711 if (mIcon == null) { 712 dest.writeInt(0); 713 } else { 714 dest.writeInt(1); 715 mIcon.writeToParcel(dest, 0); 716 } 717 dest.writeInt(mColorPrimary); 718 if (mIconFilename == null) { 719 dest.writeInt(0); 720 } else { 721 dest.writeInt(1); 722 dest.writeString(mIconFilename); 723 } 724 } 725 726 public void readFromParcel(Parcel source) { 727 mLabel = source.readInt() > 0 ? source.readString() : null; 728 mIcon = source.readInt() > 0 ? Bitmap.CREATOR.createFromParcel(source) : null; 729 mColorPrimary = source.readInt(); 730 mIconFilename = source.readInt() > 0 ? source.readString() : null; 731 } 732 733 public static final Creator<TaskDescription> CREATOR 734 = new Creator<TaskDescription>() { 735 public TaskDescription createFromParcel(Parcel source) { 736 return new TaskDescription(source); 737 } 738 public TaskDescription[] newArray(int size) { 739 return new TaskDescription[size]; 740 } 741 }; 742 743 @Override 744 public String toString() { 745 return "TaskDescription Label: " + mLabel + " Icon: " + mIcon + 746 " colorPrimary: " + mColorPrimary; 747 } 748 } 749 750 /** 751 * Information you can retrieve about tasks that the user has most recently 752 * started or visited. 753 */ 754 public static class RecentTaskInfo implements Parcelable { 755 /** 756 * If this task is currently running, this is the identifier for it. 757 * If it is not running, this will be -1. 758 */ 759 public int id; 760 761 /** 762 * The true identifier of this task, valid even if it is not running. 763 */ 764 public int persistentId; 765 766 /** 767 * The original Intent used to launch the task. You can use this 768 * Intent to re-launch the task (if it is no longer running) or bring 769 * the current task to the front. 770 */ 771 public Intent baseIntent; 772 773 /** 774 * If this task was started from an alias, this is the actual 775 * activity component that was initially started; the component of 776 * the baseIntent in this case is the name of the actual activity 777 * implementation that the alias referred to. Otherwise, this is null. 778 */ 779 public ComponentName origActivity; 780 781 /** 782 * Description of the task's last state. 783 */ 784 public CharSequence description; 785 786 /** 787 * The id of the ActivityStack this Task was on most recently. 788 * @hide 789 */ 790 public int stackId; 791 792 /** 793 * The id of the user the task was running as. 794 * @hide 795 */ 796 public int userId; 797 798 /** 799 * The first time this task was active. 800 * @hide 801 */ 802 public long firstActiveTime; 803 804 /** 805 * The last time this task was active. 806 * @hide 807 */ 808 public long lastActiveTime; 809 810 /** 811 * The recent activity values for the highest activity in the stack to have set the values. 812 * {@link Activity#setTaskDescription(android.app.ActivityManager.TaskDescription)}. 813 */ 814 public TaskDescription taskDescription; 815 816 /** 817 * Task affiliation for grouping with other tasks. 818 */ 819 public int affiliatedTaskId; 820 821 /** 822 * Task affiliation color of the source task with the affiliated task id. 823 * 824 * @hide 825 */ 826 public int affiliatedTaskColor; 827 828 public RecentTaskInfo() { 829 } 830 831 @Override 832 public int describeContents() { 833 return 0; 834 } 835 836 @Override 837 public void writeToParcel(Parcel dest, int flags) { 838 dest.writeInt(id); 839 dest.writeInt(persistentId); 840 if (baseIntent != null) { 841 dest.writeInt(1); 842 baseIntent.writeToParcel(dest, 0); 843 } else { 844 dest.writeInt(0); 845 } 846 ComponentName.writeToParcel(origActivity, dest); 847 TextUtils.writeToParcel(description, dest, 848 Parcelable.PARCELABLE_WRITE_RETURN_VALUE); 849 if (taskDescription != null) { 850 dest.writeInt(1); 851 taskDescription.writeToParcel(dest, 0); 852 } else { 853 dest.writeInt(0); 854 } 855 dest.writeInt(stackId); 856 dest.writeInt(userId); 857 dest.writeLong(firstActiveTime); 858 dest.writeLong(lastActiveTime); 859 dest.writeInt(affiliatedTaskId); 860 dest.writeInt(affiliatedTaskColor); 861 } 862 863 public void readFromParcel(Parcel source) { 864 id = source.readInt(); 865 persistentId = source.readInt(); 866 baseIntent = source.readInt() > 0 ? Intent.CREATOR.createFromParcel(source) : null; 867 origActivity = ComponentName.readFromParcel(source); 868 description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source); 869 taskDescription = source.readInt() > 0 ? 870 TaskDescription.CREATOR.createFromParcel(source) : null; 871 stackId = source.readInt(); 872 userId = source.readInt(); 873 firstActiveTime = source.readLong(); 874 lastActiveTime = source.readLong(); 875 affiliatedTaskId = source.readInt(); 876 affiliatedTaskColor = source.readInt(); 877 } 878 879 public static final Creator<RecentTaskInfo> CREATOR 880 = new Creator<RecentTaskInfo>() { 881 public RecentTaskInfo createFromParcel(Parcel source) { 882 return new RecentTaskInfo(source); 883 } 884 public RecentTaskInfo[] newArray(int size) { 885 return new RecentTaskInfo[size]; 886 } 887 }; 888 889 private RecentTaskInfo(Parcel source) { 890 readFromParcel(source); 891 } 892 } 893 894 /** 895 * Flag for use with {@link #getRecentTasks}: return all tasks, even those 896 * that have set their 897 * {@link android.content.Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag. 898 */ 899 public static final int RECENT_WITH_EXCLUDED = 0x0001; 900 901 /** 902 * Provides a list that does not contain any 903 * recent tasks that currently are not available to the user. 904 */ 905 public static final int RECENT_IGNORE_UNAVAILABLE = 0x0002; 906 907 /** 908 * Provides a list that contains recent tasks for all 909 * profiles of a user. 910 * @hide 911 */ 912 public static final int RECENT_INCLUDE_PROFILES = 0x0004; 913 914 /** 915 * Ignores all tasks that are on the home stack. 916 * @hide 917 */ 918 public static final int RECENT_IGNORE_HOME_STACK_TASKS = 0x0008; 919 920 /** 921 * <p></p>Return a list of the tasks that the user has recently launched, with 922 * the most recent being first and older ones after in order. 923 * 924 * <p><b>Note: this method is only intended for debugging and presenting 925 * task management user interfaces</b>. This should never be used for 926 * core logic in an application, such as deciding between different 927 * behaviors based on the information found here. Such uses are 928 * <em>not</em> supported, and will likely break in the future. For 929 * example, if multiple applications can be actively running at the 930 * same time, assumptions made about the meaning of the data here for 931 * purposes of control flow will be incorrect.</p> 932 * 933 * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method is 934 * no longer available to third party applications: the introduction of 935 * document-centric recents means 936 * it can leak personal information to the caller. For backwards compatibility, 937 * it will still return a small subset of its data: at least the caller's 938 * own tasks (though see {@link #getAppTasks()} for the correct supported 939 * way to retrieve that information), and possibly some other tasks 940 * such as home that are known to not be sensitive. 941 * 942 * @param maxNum The maximum number of entries to return in the list. The 943 * actual number returned may be smaller, depending on how many tasks the 944 * user has started and the maximum number the system can remember. 945 * @param flags Information about what to return. May be any combination 946 * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}. 947 * 948 * @return Returns a list of RecentTaskInfo records describing each of 949 * the recent tasks. 950 */ 951 @Deprecated 952 public List<RecentTaskInfo> getRecentTasks(int maxNum, int flags) 953 throws SecurityException { 954 try { 955 return ActivityManagerNative.getDefault().getRecentTasks(maxNum, 956 flags, UserHandle.myUserId()); 957 } catch (RemoteException e) { 958 // System dead, we will be dead too soon! 959 return null; 960 } 961 } 962 963 /** 964 * Same as {@link #getRecentTasks(int, int)} but returns the recent tasks for a 965 * specific user. It requires holding 966 * the {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission. 967 * @param maxNum The maximum number of entries to return in the list. The 968 * actual number returned may be smaller, depending on how many tasks the 969 * user has started and the maximum number the system can remember. 970 * @param flags Information about what to return. May be any combination 971 * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}. 972 * 973 * @return Returns a list of RecentTaskInfo records describing each of 974 * the recent tasks. 975 * 976 * @hide 977 */ 978 public List<RecentTaskInfo> getRecentTasksForUser(int maxNum, int flags, int userId) 979 throws SecurityException { 980 try { 981 return ActivityManagerNative.getDefault().getRecentTasks(maxNum, 982 flags, userId); 983 } catch (RemoteException e) { 984 // System dead, we will be dead too soon! 985 return null; 986 } 987 } 988 989 /** 990 * Information you can retrieve about a particular task that is currently 991 * "running" in the system. Note that a running task does not mean the 992 * given task actually has a process it is actively running in; it simply 993 * means that the user has gone to it and never closed it, but currently 994 * the system may have killed its process and is only holding on to its 995 * last state in order to restart it when the user returns. 996 */ 997 public static class RunningTaskInfo implements Parcelable { 998 /** 999 * A unique identifier for this task. 1000 */ 1001 public int id; 1002 1003 /** 1004 * The component launched as the first activity in the task. This can 1005 * be considered the "application" of this task. 1006 */ 1007 public ComponentName baseActivity; 1008 1009 /** 1010 * The activity component at the top of the history stack of the task. 1011 * This is what the user is currently doing. 1012 */ 1013 public ComponentName topActivity; 1014 1015 /** 1016 * Thumbnail representation of the task's current state. Currently 1017 * always null. 1018 */ 1019 public Bitmap thumbnail; 1020 1021 /** 1022 * Description of the task's current state. 1023 */ 1024 public CharSequence description; 1025 1026 /** 1027 * Number of activities in this task. 1028 */ 1029 public int numActivities; 1030 1031 /** 1032 * Number of activities that are currently running (not stopped 1033 * and persisted) in this task. 1034 */ 1035 public int numRunning; 1036 1037 /** 1038 * Last time task was run. For sorting. 1039 * @hide 1040 */ 1041 public long lastActiveTime; 1042 1043 public RunningTaskInfo() { 1044 } 1045 1046 public int describeContents() { 1047 return 0; 1048 } 1049 1050 public void writeToParcel(Parcel dest, int flags) { 1051 dest.writeInt(id); 1052 ComponentName.writeToParcel(baseActivity, dest); 1053 ComponentName.writeToParcel(topActivity, dest); 1054 if (thumbnail != null) { 1055 dest.writeInt(1); 1056 thumbnail.writeToParcel(dest, 0); 1057 } else { 1058 dest.writeInt(0); 1059 } 1060 TextUtils.writeToParcel(description, dest, 1061 Parcelable.PARCELABLE_WRITE_RETURN_VALUE); 1062 dest.writeInt(numActivities); 1063 dest.writeInt(numRunning); 1064 } 1065 1066 public void readFromParcel(Parcel source) { 1067 id = source.readInt(); 1068 baseActivity = ComponentName.readFromParcel(source); 1069 topActivity = ComponentName.readFromParcel(source); 1070 if (source.readInt() != 0) { 1071 thumbnail = Bitmap.CREATOR.createFromParcel(source); 1072 } else { 1073 thumbnail = null; 1074 } 1075 description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source); 1076 numActivities = source.readInt(); 1077 numRunning = source.readInt(); 1078 } 1079 1080 public static final Creator<RunningTaskInfo> CREATOR = new Creator<RunningTaskInfo>() { 1081 public RunningTaskInfo createFromParcel(Parcel source) { 1082 return new RunningTaskInfo(source); 1083 } 1084 public RunningTaskInfo[] newArray(int size) { 1085 return new RunningTaskInfo[size]; 1086 } 1087 }; 1088 1089 private RunningTaskInfo(Parcel source) { 1090 readFromParcel(source); 1091 } 1092 } 1093 1094 /** 1095 * Get the list of tasks associated with the calling application. 1096 * 1097 * @return The list of tasks associated with the application making this call. 1098 * @throws SecurityException 1099 */ 1100 public List<ActivityManager.AppTask> getAppTasks() { 1101 ArrayList<AppTask> tasks = new ArrayList<AppTask>(); 1102 List<IAppTask> appTasks; 1103 try { 1104 appTasks = ActivityManagerNative.getDefault().getAppTasks(mContext.getPackageName()); 1105 } catch (RemoteException e) { 1106 // System dead, we will be dead too soon! 1107 return null; 1108 } 1109 int numAppTasks = appTasks.size(); 1110 for (int i = 0; i < numAppTasks; i++) { 1111 tasks.add(new AppTask(appTasks.get(i))); 1112 } 1113 return tasks; 1114 } 1115 1116 /** 1117 * Return the current design dimensions for {@link AppTask} thumbnails, for use 1118 * with {@link #addAppTask}. 1119 */ 1120 public Size getAppTaskThumbnailSize() { 1121 synchronized (this) { 1122 ensureAppTaskThumbnailSizeLocked(); 1123 return new Size(mAppTaskThumbnailSize.x, mAppTaskThumbnailSize.y); 1124 } 1125 } 1126 1127 private void ensureAppTaskThumbnailSizeLocked() { 1128 if (mAppTaskThumbnailSize == null) { 1129 try { 1130 mAppTaskThumbnailSize = ActivityManagerNative.getDefault().getAppTaskThumbnailSize(); 1131 } catch (RemoteException e) { 1132 throw new IllegalStateException("System dead?", e); 1133 } 1134 } 1135 } 1136 1137 /** 1138 * Add a new {@link AppTask} for the calling application. This will create a new 1139 * recents entry that is added to the <b>end</b> of all existing recents. 1140 * 1141 * @param activity The activity that is adding the entry. This is used to help determine 1142 * the context that the new recents entry will be in. 1143 * @param intent The Intent that describes the recents entry. This is the same Intent that 1144 * you would have used to launch the activity for it. In generally you will want to set 1145 * both {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT} and 1146 * {@link Intent#FLAG_ACTIVITY_RETAIN_IN_RECENTS}; the latter is required since this recents 1147 * entry will exist without an activity, so it doesn't make sense to not retain it when 1148 * its activity disappears. The given Intent here also must have an explicit ComponentName 1149 * set on it. 1150 * @param description Optional additional description information. 1151 * @param thumbnail Thumbnail to use for the recents entry. Should be the size given by 1152 * {@link #getAppTaskThumbnailSize()}. If the bitmap is not that exact size, it will be 1153 * recreated in your process, probably in a way you don't like, before the recents entry 1154 * is added. 1155 * 1156 * @return Returns the task id of the newly added app task, or -1 if the add failed. The 1157 * most likely cause of failure is that there is no more room for more tasks for your app. 1158 */ 1159 public int addAppTask(@NonNull Activity activity, @NonNull Intent intent, 1160 @Nullable TaskDescription description, @NonNull Bitmap thumbnail) { 1161 Point size; 1162 synchronized (this) { 1163 ensureAppTaskThumbnailSizeLocked(); 1164 size = mAppTaskThumbnailSize; 1165 } 1166 final int tw = thumbnail.getWidth(); 1167 final int th = thumbnail.getHeight(); 1168 if (tw != size.x || th != size.y) { 1169 Bitmap bm = Bitmap.createBitmap(size.x, size.y, thumbnail.getConfig()); 1170 1171 // Use ScaleType.CENTER_CROP, except we leave the top edge at the top. 1172 float scale; 1173 float dx = 0, dy = 0; 1174 if (tw * size.x > size.y * th) { 1175 scale = (float) size.x / (float) th; 1176 dx = (size.y - tw * scale) * 0.5f; 1177 } else { 1178 scale = (float) size.y / (float) tw; 1179 dy = (size.x - th * scale) * 0.5f; 1180 } 1181 Matrix matrix = new Matrix(); 1182 matrix.setScale(scale, scale); 1183 matrix.postTranslate((int) (dx + 0.5f), 0); 1184 1185 Canvas canvas = new Canvas(bm); 1186 canvas.drawBitmap(thumbnail, matrix, null); 1187 canvas.setBitmap(null); 1188 1189 thumbnail = bm; 1190 } 1191 if (description == null) { 1192 description = new TaskDescription(); 1193 } 1194 try { 1195 return ActivityManagerNative.getDefault().addAppTask(activity.getActivityToken(), 1196 intent, description, thumbnail); 1197 } catch (RemoteException e) { 1198 throw new IllegalStateException("System dead?", e); 1199 } 1200 } 1201 1202 /** 1203 * Return a list of the tasks that are currently running, with 1204 * the most recent being first and older ones after in order. Note that 1205 * "running" does not mean any of the task's code is currently loaded or 1206 * activity -- the task may have been frozen by the system, so that it 1207 * can be restarted in its previous state when next brought to the 1208 * foreground. 1209 * 1210 * <p><b>Note: this method is only intended for debugging and presenting 1211 * task management user interfaces</b>. This should never be used for 1212 * core logic in an application, such as deciding between different 1213 * behaviors based on the information found here. Such uses are 1214 * <em>not</em> supported, and will likely break in the future. For 1215 * example, if multiple applications can be actively running at the 1216 * same time, assumptions made about the meaning of the data here for 1217 * purposes of control flow will be incorrect.</p> 1218 * 1219 * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method 1220 * is no longer available to third party 1221 * applications: the introduction of document-centric recents means 1222 * it can leak person information to the caller. For backwards compatibility, 1223 * it will still retu rn a small subset of its data: at least the caller's 1224 * own tasks, and possibly some other tasks 1225 * such as home that are known to not be sensitive. 1226 * 1227 * @param maxNum The maximum number of entries to return in the list. The 1228 * actual number returned may be smaller, depending on how many tasks the 1229 * user has started. 1230 * 1231 * @return Returns a list of RunningTaskInfo records describing each of 1232 * the running tasks. 1233 */ 1234 @Deprecated 1235 public List<RunningTaskInfo> getRunningTasks(int maxNum) 1236 throws SecurityException { 1237 try { 1238 return ActivityManagerNative.getDefault().getTasks(maxNum, 0); 1239 } catch (RemoteException e) { 1240 // System dead, we will be dead too soon! 1241 return null; 1242 } 1243 } 1244 1245 /** 1246 * If set, the process of the root activity of the task will be killed 1247 * as part of removing the task. 1248 * @hide 1249 */ 1250 public static final int REMOVE_TASK_KILL_PROCESS = 0x0001; 1251 1252 /** 1253 * Completely remove the given task. 1254 * 1255 * @param taskId Identifier of the task to be removed. 1256 * @param flags Additional operational flags. May be 0 or 1257 * {@link #REMOVE_TASK_KILL_PROCESS}. 1258 * @return Returns true if the given task was found and removed. 1259 * 1260 * @hide 1261 */ 1262 public boolean removeTask(int taskId, int flags) 1263 throws SecurityException { 1264 try { 1265 return ActivityManagerNative.getDefault().removeTask(taskId, flags); 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