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