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