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