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