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