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