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