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