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