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