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