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