Debian Codegraph @

core/java/android/app/ActivityManager.java

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