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