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