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