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