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