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