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