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