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