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