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