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