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