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