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