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