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