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