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