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