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