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