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