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