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