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