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