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