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