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