ActivityManager.java revision 57f7a1486ecd26346d3f6495a1061e61d065e5c8
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     * @deprecated As of {@link android.os.Build.VERSION_CODES#O}, this method
2584     * is no longer available to third party applications.  For backwards compatibility,
2585     * it will still return the caller's own services.
2586     *
2587     * @param maxNum The maximum number of entries to return in the list.  The
2588     * actual number returned may be smaller, depending on how many services
2589     * are running.
2590     *
2591     * @return Returns a list of RunningServiceInfo records describing each of
2592     * the running tasks.
2593     */
2594    @Deprecated
2595    public List<RunningServiceInfo> getRunningServices(int maxNum)
2596            throws SecurityException {
2597        try {
2598            return getService()
2599                    .getServices(maxNum, 0);
2600        } catch (RemoteException e) {
2601            throw e.rethrowFromSystemServer();
2602        }
2603    }
2604
2605    /**
2606     * Returns a PendingIntent you can start to show a control panel for the
2607     * given running service.  If the service does not have a control panel,
2608     * null is returned.
2609     */
2610    public PendingIntent getRunningServiceControlPanel(ComponentName service)
2611            throws SecurityException {
2612        try {
2613            return getService()
2614                    .getRunningServiceControlPanel(service);
2615        } catch (RemoteException e) {
2616            throw e.rethrowFromSystemServer();
2617        }
2618    }
2619
2620    /**
2621     * Information you can retrieve about the available memory through
2622     * {@link ActivityManager#getMemoryInfo}.
2623     */
2624    public static class MemoryInfo implements Parcelable {
2625        /**
2626         * The available memory on the system.  This number should not
2627         * be considered absolute: due to the nature of the kernel, a significant
2628         * portion of this memory is actually in use and needed for the overall
2629         * system to run well.
2630         */
2631        public long availMem;
2632
2633        /**
2634         * The total memory accessible by the kernel.  This is basically the
2635         * RAM size of the device, not including below-kernel fixed allocations
2636         * like DMA buffers, RAM for the baseband CPU, etc.
2637         */
2638        public long totalMem;
2639
2640        /**
2641         * The threshold of {@link #availMem} at which we consider memory to be
2642         * low and start killing background services and other non-extraneous
2643         * processes.
2644         */
2645        public long threshold;
2646
2647        /**
2648         * Set to true if the system considers itself to currently be in a low
2649         * memory situation.
2650         */
2651        public boolean lowMemory;
2652
2653        /** @hide */
2654        public long hiddenAppThreshold;
2655        /** @hide */
2656        public long secondaryServerThreshold;
2657        /** @hide */
2658        public long visibleAppThreshold;
2659        /** @hide */
2660        public long foregroundAppThreshold;
2661
2662        public MemoryInfo() {
2663        }
2664
2665        public int describeContents() {
2666            return 0;
2667        }
2668
2669        public void writeToParcel(Parcel dest, int flags) {
2670            dest.writeLong(availMem);
2671            dest.writeLong(totalMem);
2672            dest.writeLong(threshold);
2673            dest.writeInt(lowMemory ? 1 : 0);
2674            dest.writeLong(hiddenAppThreshold);
2675            dest.writeLong(secondaryServerThreshold);
2676            dest.writeLong(visibleAppThreshold);
2677            dest.writeLong(foregroundAppThreshold);
2678        }
2679
2680        public void readFromParcel(Parcel source) {
2681            availMem = source.readLong();
2682            totalMem = source.readLong();
2683            threshold = source.readLong();
2684            lowMemory = source.readInt() != 0;
2685            hiddenAppThreshold = source.readLong();
2686            secondaryServerThreshold = source.readLong();
2687            visibleAppThreshold = source.readLong();
2688            foregroundAppThreshold = source.readLong();
2689        }
2690
2691        public static final Creator<MemoryInfo> CREATOR
2692                = new Creator<MemoryInfo>() {
2693            public MemoryInfo createFromParcel(Parcel source) {
2694                return new MemoryInfo(source);
2695            }
2696            public MemoryInfo[] newArray(int size) {
2697                return new MemoryInfo[size];
2698            }
2699        };
2700
2701        private MemoryInfo(Parcel source) {
2702            readFromParcel(source);
2703        }
2704    }
2705
2706    /**
2707     * Return general information about the memory state of the system.  This
2708     * can be used to help decide how to manage your own memory, though note
2709     * that polling is not recommended and
2710     * {@link android.content.ComponentCallbacks2#onTrimMemory(int)
2711     * ComponentCallbacks2.onTrimMemory(int)} is the preferred way to do this.
2712     * Also see {@link #getMyMemoryState} for how to retrieve the current trim
2713     * level of your process as needed, which gives a better hint for how to
2714     * manage its memory.
2715     */
2716    public void getMemoryInfo(MemoryInfo outInfo) {
2717        try {
2718            getService().getMemoryInfo(outInfo);
2719        } catch (RemoteException e) {
2720            throw e.rethrowFromSystemServer();
2721        }
2722    }
2723
2724    /**
2725     * Information you can retrieve about an ActivityStack in the system.
2726     * @hide
2727     */
2728    public static class StackInfo implements Parcelable {
2729        public int stackId;
2730        public Rect bounds = new Rect();
2731        public int[] taskIds;
2732        public String[] taskNames;
2733        public Rect[] taskBounds;
2734        public int[] taskUserIds;
2735        public ComponentName topActivity;
2736        public int displayId;
2737        public int userId;
2738        public boolean visible;
2739        // Index of the stack in the display's stack list, can be used for comparison of stack order
2740        public int position;
2741
2742        @Override
2743        public int describeContents() {
2744            return 0;
2745        }
2746
2747        @Override
2748        public void writeToParcel(Parcel dest, int flags) {
2749            dest.writeInt(stackId);
2750            dest.writeInt(bounds.left);
2751            dest.writeInt(bounds.top);
2752            dest.writeInt(bounds.right);
2753            dest.writeInt(bounds.bottom);
2754            dest.writeIntArray(taskIds);
2755            dest.writeStringArray(taskNames);
2756            final int boundsCount = taskBounds == null ? 0 : taskBounds.length;
2757            dest.writeInt(boundsCount);
2758            for (int i = 0; i < boundsCount; i++) {
2759                dest.writeInt(taskBounds[i].left);
2760                dest.writeInt(taskBounds[i].top);
2761                dest.writeInt(taskBounds[i].right);
2762                dest.writeInt(taskBounds[i].bottom);
2763            }
2764            dest.writeIntArray(taskUserIds);
2765            dest.writeInt(displayId);
2766            dest.writeInt(userId);
2767            dest.writeInt(visible ? 1 : 0);
2768            dest.writeInt(position);
2769            if (topActivity != null) {
2770                dest.writeInt(1);
2771                topActivity.writeToParcel(dest, 0);
2772            } else {
2773                dest.writeInt(0);
2774            }
2775        }
2776
2777        public void readFromParcel(Parcel source) {
2778            stackId = source.readInt();
2779            bounds = new Rect(
2780                    source.readInt(), source.readInt(), source.readInt(), source.readInt());
2781            taskIds = source.createIntArray();
2782            taskNames = source.createStringArray();
2783            final int boundsCount = source.readInt();
2784            if (boundsCount > 0) {
2785                taskBounds = new Rect[boundsCount];
2786                for (int i = 0; i < boundsCount; i++) {
2787                    taskBounds[i] = new Rect();
2788                    taskBounds[i].set(
2789                            source.readInt(), source.readInt(), source.readInt(), source.readInt());
2790                }
2791            } else {
2792                taskBounds = null;
2793            }
2794            taskUserIds = source.createIntArray();
2795            displayId = source.readInt();
2796            userId = source.readInt();
2797            visible = source.readInt() > 0;
2798            position = source.readInt();
2799            if (source.readInt() > 0) {
2800                topActivity = ComponentName.readFromParcel(source);
2801            }
2802        }
2803
2804        public static final Creator<StackInfo> CREATOR = new Creator<StackInfo>() {
2805            @Override
2806            public StackInfo createFromParcel(Parcel source) {
2807                return new StackInfo(source);
2808            }
2809            @Override
2810            public StackInfo[] newArray(int size) {
2811                return new StackInfo[size];
2812            }
2813        };
2814
2815        public StackInfo() {
2816        }
2817
2818        private StackInfo(Parcel source) {
2819            readFromParcel(source);
2820        }
2821
2822        public String toString(String prefix) {
2823            StringBuilder sb = new StringBuilder(256);
2824            sb.append(prefix); sb.append("Stack id="); sb.append(stackId);
2825                    sb.append(" bounds="); sb.append(bounds.toShortString());
2826                    sb.append(" displayId="); sb.append(displayId);
2827                    sb.append(" userId="); sb.append(userId);
2828                    sb.append("\n");
2829            prefix = prefix + "  ";
2830            for (int i = 0; i < taskIds.length; ++i) {
2831                sb.append(prefix); sb.append("taskId="); sb.append(taskIds[i]);
2832                        sb.append(": "); sb.append(taskNames[i]);
2833                        if (taskBounds != null) {
2834                            sb.append(" bounds="); sb.append(taskBounds[i].toShortString());
2835                        }
2836                        sb.append(" userId=").append(taskUserIds[i]);
2837                        sb.append(" visible=").append(visible);
2838                        if (topActivity != null) {
2839                            sb.append(" topActivity=").append(topActivity);
2840                        }
2841                        sb.append("\n");
2842            }
2843            return sb.toString();
2844        }
2845
2846        @Override
2847        public String toString() {
2848            return toString("");
2849        }
2850    }
2851
2852    /**
2853     * @hide
2854     */
2855    public boolean clearApplicationUserData(String packageName, IPackageDataObserver observer) {
2856        try {
2857            return getService().clearApplicationUserData(packageName,
2858                    observer, UserHandle.myUserId());
2859        } catch (RemoteException e) {
2860            throw e.rethrowFromSystemServer();
2861        }
2862    }
2863
2864    /**
2865     * Permits an application to erase its own data from disk.  This is equivalent to
2866     * the user choosing to clear the app's data from within the device settings UI.  It
2867     * erases all dynamic data associated with the app -- its private data and data in its
2868     * private area on external storage -- but does not remove the installed application
2869     * itself, nor any OBB files.
2870     *
2871     * @return {@code true} if the application successfully requested that the application's
2872     *     data be erased; {@code false} otherwise.
2873     */
2874    public boolean clearApplicationUserData() {
2875        return clearApplicationUserData(mContext.getPackageName(), null);
2876    }
2877
2878
2879    /**
2880     * Permits an application to get the persistent URI permissions granted to another.
2881     *
2882     * <p>Typically called by Settings.
2883     *
2884     * @param packageName application to look for the granted permissions
2885     * @return list of granted URI permissions
2886     *
2887     * @hide
2888     */
2889    public ParceledListSlice<UriPermission> getGrantedUriPermissions(String packageName) {
2890        try {
2891            return getService().getGrantedUriPermissions(packageName,
2892                    UserHandle.myUserId());
2893        } catch (RemoteException e) {
2894            throw e.rethrowFromSystemServer();
2895        }
2896    }
2897
2898    /**
2899     * Permits an application to clear the persistent URI permissions granted to another.
2900     *
2901     * <p>Typically called by Settings.
2902     *
2903     * @param packageName application to clear its granted permissions
2904     *
2905     * @hide
2906     */
2907    public void clearGrantedUriPermissions(String packageName) {
2908        try {
2909            getService().clearGrantedUriPermissions(packageName,
2910                    UserHandle.myUserId());
2911        } catch (RemoteException e) {
2912            throw e.rethrowFromSystemServer();
2913        }
2914    }
2915
2916    /**
2917     * Information you can retrieve about any processes that are in an error condition.
2918     */
2919    public static class ProcessErrorStateInfo implements Parcelable {
2920        /**
2921         * Condition codes
2922         */
2923        public static final int NO_ERROR = 0;
2924        public static final int CRASHED = 1;
2925        public static final int NOT_RESPONDING = 2;
2926
2927        /**
2928         * The condition that the process is in.
2929         */
2930        public int condition;
2931
2932        /**
2933         * The process name in which the crash or error occurred.
2934         */
2935        public String processName;
2936
2937        /**
2938         * The pid of this process; 0 if none
2939         */
2940        public int pid;
2941
2942        /**
2943         * The kernel user-ID that has been assigned to this process;
2944         * currently this is not a unique ID (multiple applications can have
2945         * the same uid).
2946         */
2947        public int uid;
2948
2949        /**
2950         * The activity name associated with the error, if known.  May be null.
2951         */
2952        public String tag;
2953
2954        /**
2955         * A short message describing the error condition.
2956         */
2957        public String shortMsg;
2958
2959        /**
2960         * A long message describing the error condition.
2961         */
2962        public String longMsg;
2963
2964        /**
2965         * The stack trace where the error originated.  May be null.
2966         */
2967        public String stackTrace;
2968
2969        /**
2970         * to be deprecated: This value will always be null.
2971         */
2972        public byte[] crashData = null;
2973
2974        public ProcessErrorStateInfo() {
2975        }
2976
2977        @Override
2978        public int describeContents() {
2979            return 0;
2980        }
2981
2982        @Override
2983        public void writeToParcel(Parcel dest, int flags) {
2984            dest.writeInt(condition);
2985            dest.writeString(processName);
2986            dest.writeInt(pid);
2987            dest.writeInt(uid);
2988            dest.writeString(tag);
2989            dest.writeString(shortMsg);
2990            dest.writeString(longMsg);
2991            dest.writeString(stackTrace);
2992        }
2993
2994        public void readFromParcel(Parcel source) {
2995            condition = source.readInt();
2996            processName = source.readString();
2997            pid = source.readInt();
2998            uid = source.readInt();
2999            tag = source.readString();
3000            shortMsg = source.readString();
3001            longMsg = source.readString();
3002            stackTrace = source.readString();
3003        }
3004
3005        public static final Creator<ProcessErrorStateInfo> CREATOR =
3006                new Creator<ProcessErrorStateInfo>() {
3007            public ProcessErrorStateInfo createFromParcel(Parcel source) {
3008                return new ProcessErrorStateInfo(source);
3009            }
3010            public ProcessErrorStateInfo[] newArray(int size) {
3011                return new ProcessErrorStateInfo[size];
3012            }
3013        };
3014
3015        private ProcessErrorStateInfo(Parcel source) {
3016            readFromParcel(source);
3017        }
3018    }
3019
3020    /**
3021     * Returns a list of any processes that are currently in an error condition.  The result
3022     * will be null if all processes are running properly at this time.
3023     *
3024     * @return Returns a list of ProcessErrorStateInfo records, or null if there are no
3025     * current error conditions (it will not return an empty list).  This list ordering is not
3026     * specified.
3027     */
3028    public List<ProcessErrorStateInfo> getProcessesInErrorState() {
3029        try {
3030            return getService().getProcessesInErrorState();
3031        } catch (RemoteException e) {
3032            throw e.rethrowFromSystemServer();
3033        }
3034    }
3035
3036    /**
3037     * Information you can retrieve about a running process.
3038     */
3039    public static class RunningAppProcessInfo implements Parcelable {
3040        /**
3041         * The name of the process that this object is associated with
3042         */
3043        public String processName;
3044
3045        /**
3046         * The pid of this process; 0 if none
3047         */
3048        public int pid;
3049
3050        /**
3051         * The user id of this process.
3052         */
3053        public int uid;
3054
3055        /**
3056         * All packages that have been loaded into the process.
3057         */
3058        public String pkgList[];
3059
3060        /**
3061         * Constant for {@link #flags}: this is an app that is unable to
3062         * correctly save its state when going to the background,
3063         * so it can not be killed while in the background.
3064         * @hide
3065         */
3066        public static final int FLAG_CANT_SAVE_STATE = 1<<0;
3067
3068        /**
3069         * Constant for {@link #flags}: this process is associated with a
3070         * persistent system app.
3071         * @hide
3072         */
3073        public static final int FLAG_PERSISTENT = 1<<1;
3074
3075        /**
3076         * Constant for {@link #flags}: this process is associated with a
3077         * persistent system app.
3078         * @hide
3079         */
3080        public static final int FLAG_HAS_ACTIVITIES = 1<<2;
3081
3082        /**
3083         * Flags of information.  May be any of
3084         * {@link #FLAG_CANT_SAVE_STATE}.
3085         * @hide
3086         */
3087        public int flags;
3088
3089        /**
3090         * Last memory trim level reported to the process: corresponds to
3091         * the values supplied to {@link android.content.ComponentCallbacks2#onTrimMemory(int)
3092         * ComponentCallbacks2.onTrimMemory(int)}.
3093         */
3094        public int lastTrimLevel;
3095
3096        /**
3097         * Constant for {@link #importance}: This process is running the
3098         * foreground UI; that is, it is the thing currently at the top of the screen
3099         * that the user is interacting with.
3100         */
3101        public static final int IMPORTANCE_FOREGROUND = 100;
3102
3103        /**
3104         * Constant for {@link #importance}: This process is running a foreground
3105         * service, for example to perform music playback even while the user is
3106         * not immediately in the app.  This generally indicates that the process
3107         * is doing something the user actively cares about.
3108         */
3109        public static final int IMPORTANCE_FOREGROUND_SERVICE = 125;
3110
3111        /**
3112         * Constant for {@link #importance}: This process is running the foreground
3113         * UI, but the device is asleep so it is not visible to the user.  This means
3114         * the user is not really aware of the process, because they can not see or
3115         * interact with it, but it is quite important because it what they expect to
3116         * return to once unlocking the device.
3117         */
3118        public static final int IMPORTANCE_TOP_SLEEPING = 150;
3119
3120        /**
3121         * Constant for {@link #importance}: This process is running something
3122         * that is actively visible to the user, though not in the immediate
3123         * foreground.  This may be running a window that is behind the current
3124         * foreground (so paused and with its state saved, not interacting with
3125         * the user, but visible to them to some degree); it may also be running
3126         * other services under the system's control that it inconsiders important.
3127         */
3128        public static final int IMPORTANCE_VISIBLE = 200;
3129
3130        /**
3131         * Constant for {@link #importance}: {@link #IMPORTANCE_PERCEPTIBLE} had this wrong value
3132         * before {@link Build.VERSION_CODES#O}.  Since the {@link Build.VERSION_CODES#O} SDK,
3133         * the value of {@link #IMPORTANCE_PERCEPTIBLE} has been fixed.
3134         *
3135         * @deprecated Use {@link #IMPORTANCE_PERCEPTIBLE} instead.
3136         */
3137        @Deprecated
3138        public static final int IMPORTANCE_PERCEPTIBLE_DEPRECATED = 130;
3139
3140        /**
3141         * Constant for {@link #importance}: This process is not something the user
3142         * is directly aware of, but is otherwise perceptible to them to some degree.
3143         */
3144        public static final int IMPORTANCE_PERCEPTIBLE = 230;
3145
3146        /**
3147         * Constant for {@link #importance}: {@link #IMPORTANCE_CANT_SAVE_STATE} had
3148         * this wrong value
3149         * before {@link Build.VERSION_CODES#O}.  Since the {@link Build.VERSION_CODES#O} SDK,
3150         * the value of {@link #IMPORTANCE_CANT_SAVE_STATE} has been fixed.
3151         *
3152         * @deprecated Use {@link #IMPORTANCE_CANT_SAVE_STATE} instead.
3153         * @hide
3154         */
3155        @Deprecated
3156        public static final int IMPORTANCE_CANT_SAVE_STATE_DEPRECATED = 170;
3157
3158        /**
3159         * Constant for {@link #importance}: This process is running an
3160         * application that can not save its state, and thus can't be killed
3161         * while in the background.
3162         * @hide
3163         */
3164        public static final int IMPORTANCE_CANT_SAVE_STATE= 270;
3165
3166        /**
3167         * Constant for {@link #importance}: This process is contains services
3168         * that should remain running.  These are background services apps have
3169         * started, not something the user is aware of, so they may be killed by
3170         * the system relatively freely (though it is generally desired that they
3171         * stay running as long as they want to).
3172         */
3173        public static final int IMPORTANCE_SERVICE = 300;
3174
3175        /**
3176         * Constant for {@link #importance}: This process process contains
3177         * cached code that is expendable, not actively running any app components
3178         * we care about.
3179         */
3180        public static final int IMPORTANCE_CACHED = 400;
3181
3182        /**
3183         * @deprecated Renamed to {@link #IMPORTANCE_CACHED}.
3184         */
3185        public static final int IMPORTANCE_BACKGROUND = IMPORTANCE_CACHED;
3186
3187        /**
3188         * Constant for {@link #importance}: This process is empty of any
3189         * actively running code.
3190         * @deprecated This value is no longer reported, use {@link #IMPORTANCE_CACHED} instead.
3191         */
3192        @Deprecated
3193        public static final int IMPORTANCE_EMPTY = 500;
3194
3195        /**
3196         * Constant for {@link #importance}: This process does not exist.
3197         */
3198        public static final int IMPORTANCE_GONE = 1000;
3199
3200        /**
3201         * Convert a proc state to the correspondent IMPORTANCE_* constant.  If the return value
3202         * will be passed to a client, use {@link #procStateToImportanceForClient}.
3203         * @hide
3204         */
3205        public static int procStateToImportance(int procState) {
3206            if (procState == PROCESS_STATE_NONEXISTENT) {
3207                return IMPORTANCE_GONE;
3208            } else if (procState >= PROCESS_STATE_HOME) {
3209                return IMPORTANCE_CACHED;
3210            } else if (procState >= PROCESS_STATE_SERVICE) {
3211                return IMPORTANCE_SERVICE;
3212            } else if (procState > PROCESS_STATE_HEAVY_WEIGHT) {
3213                return IMPORTANCE_CANT_SAVE_STATE;
3214            } else if (procState >= PROCESS_STATE_IMPORTANT_BACKGROUND) {
3215                return IMPORTANCE_PERCEPTIBLE;
3216            } else if (procState >= PROCESS_STATE_IMPORTANT_FOREGROUND) {
3217                return IMPORTANCE_VISIBLE;
3218            } else if (procState >= PROCESS_STATE_TOP_SLEEPING) {
3219                return IMPORTANCE_TOP_SLEEPING;
3220            } else if (procState >= PROCESS_STATE_FOREGROUND_SERVICE) {
3221                return IMPORTANCE_FOREGROUND_SERVICE;
3222            } else {
3223                return IMPORTANCE_FOREGROUND;
3224            }
3225        }
3226
3227        /**
3228         * Convert a proc state to the correspondent IMPORTANCE_* constant for a client represented
3229         * by a given {@link Context}, with converting {@link #IMPORTANCE_PERCEPTIBLE}
3230         * and {@link #IMPORTANCE_CANT_SAVE_STATE} to the corresponding "wrong" value if the
3231         * client's target SDK < {@link VERSION_CODES#O}.
3232         * @hide
3233         */
3234        public static int procStateToImportanceForClient(int procState, Context clientContext) {
3235            final int importance = procStateToImportance(procState);
3236
3237            // For pre O apps, convert to the old, wrong values.
3238            if (clientContext.getApplicationInfo().targetSdkVersion < VERSION_CODES.O) {
3239                switch (importance) {
3240                    case IMPORTANCE_PERCEPTIBLE:
3241                        return IMPORTANCE_PERCEPTIBLE_DEPRECATED;
3242                    case IMPORTANCE_CANT_SAVE_STATE:
3243                        return IMPORTANCE_CANT_SAVE_STATE_DEPRECATED;
3244                }
3245            }
3246            return importance;
3247        }
3248
3249        /** @hide */
3250        public static int importanceToProcState(int importance) {
3251            if (importance == IMPORTANCE_GONE) {
3252                return PROCESS_STATE_NONEXISTENT;
3253            } else if (importance >= IMPORTANCE_CACHED) {
3254                return PROCESS_STATE_HOME;
3255            } else if (importance >= IMPORTANCE_SERVICE) {
3256                return PROCESS_STATE_SERVICE;
3257            } else if (importance > IMPORTANCE_CANT_SAVE_STATE) {
3258                return PROCESS_STATE_HEAVY_WEIGHT;
3259            } else if (importance >= IMPORTANCE_PERCEPTIBLE) {
3260                return PROCESS_STATE_IMPORTANT_BACKGROUND;
3261            } else if (importance >= IMPORTANCE_VISIBLE) {
3262                return PROCESS_STATE_IMPORTANT_FOREGROUND;
3263            } else if (importance >= IMPORTANCE_TOP_SLEEPING) {
3264                return PROCESS_STATE_TOP_SLEEPING;
3265            } else if (importance >= IMPORTANCE_FOREGROUND_SERVICE) {
3266                return PROCESS_STATE_FOREGROUND_SERVICE;
3267            } else {
3268                return PROCESS_STATE_BOUND_FOREGROUND_SERVICE;
3269            }
3270        }
3271
3272        /**
3273         * The relative importance level that the system places on this
3274         * process.  May be one of {@link #IMPORTANCE_FOREGROUND},
3275         * {@link #IMPORTANCE_VISIBLE}, {@link #IMPORTANCE_SERVICE}, or
3276         * {@link #IMPORTANCE_CACHED}.  These
3277         * constants are numbered so that "more important" values are always
3278         * smaller than "less important" values.
3279         */
3280        public int importance;
3281
3282        /**
3283         * An additional ordering within a particular {@link #importance}
3284         * category, providing finer-grained information about the relative
3285         * utility of processes within a category.  This number means nothing
3286         * except that a smaller values are more recently used (and thus
3287         * more important).  Currently an LRU value is only maintained for
3288         * the {@link #IMPORTANCE_CACHED} category, though others may
3289         * be maintained in the future.
3290         */
3291        public int lru;
3292
3293        /**
3294         * Constant for {@link #importanceReasonCode}: nothing special has
3295         * been specified for the reason for this level.
3296         */
3297        public static final int REASON_UNKNOWN = 0;
3298
3299        /**
3300         * Constant for {@link #importanceReasonCode}: one of the application's
3301         * content providers is being used by another process.  The pid of
3302         * the client process is in {@link #importanceReasonPid} and the
3303         * target provider in this process is in
3304         * {@link #importanceReasonComponent}.
3305         */
3306        public static final int REASON_PROVIDER_IN_USE = 1;
3307
3308        /**
3309         * Constant for {@link #importanceReasonCode}: one of the application's
3310         * content providers is being used by another process.  The pid of
3311         * the client process is in {@link #importanceReasonPid} and the
3312         * target provider in this process is in
3313         * {@link #importanceReasonComponent}.
3314         */
3315        public static final int REASON_SERVICE_IN_USE = 2;
3316
3317        /**
3318         * The reason for {@link #importance}, if any.
3319         */
3320        public int importanceReasonCode;
3321
3322        /**
3323         * For the specified values of {@link #importanceReasonCode}, this
3324         * is the process ID of the other process that is a client of this
3325         * process.  This will be 0 if no other process is using this one.
3326         */
3327        public int importanceReasonPid;
3328
3329        /**
3330         * For the specified values of {@link #importanceReasonCode}, this
3331         * is the name of the component that is being used in this process.
3332         */
3333        public ComponentName importanceReasonComponent;
3334
3335        /**
3336         * When {@link #importanceReasonPid} is non-0, this is the importance
3337         * of the other pid. @hide
3338         */
3339        public int importanceReasonImportance;
3340
3341        /**
3342         * Current process state, as per PROCESS_STATE_* constants.
3343         * @hide
3344         */
3345        public int processState;
3346
3347        public RunningAppProcessInfo() {
3348            importance = IMPORTANCE_FOREGROUND;
3349            importanceReasonCode = REASON_UNKNOWN;
3350            processState = PROCESS_STATE_IMPORTANT_FOREGROUND;
3351        }
3352
3353        public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) {
3354            processName = pProcessName;
3355            pid = pPid;
3356            pkgList = pArr;
3357        }
3358
3359        public int describeContents() {
3360            return 0;
3361        }
3362
3363        public void writeToParcel(Parcel dest, int flags) {
3364            dest.writeString(processName);
3365            dest.writeInt(pid);
3366            dest.writeInt(uid);
3367            dest.writeStringArray(pkgList);
3368            dest.writeInt(this.flags);
3369            dest.writeInt(lastTrimLevel);
3370            dest.writeInt(importance);
3371            dest.writeInt(lru);
3372            dest.writeInt(importanceReasonCode);
3373            dest.writeInt(importanceReasonPid);
3374            ComponentName.writeToParcel(importanceReasonComponent, dest);
3375            dest.writeInt(importanceReasonImportance);
3376            dest.writeInt(processState);
3377        }
3378
3379        public void readFromParcel(Parcel source) {
3380            processName = source.readString();
3381            pid = source.readInt();
3382            uid = source.readInt();
3383            pkgList = source.readStringArray();
3384            flags = source.readInt();
3385            lastTrimLevel = source.readInt();
3386            importance = source.readInt();
3387            lru = source.readInt();
3388            importanceReasonCode = source.readInt();
3389            importanceReasonPid = source.readInt();
3390            importanceReasonComponent = ComponentName.readFromParcel(source);
3391            importanceReasonImportance = source.readInt();
3392            processState = source.readInt();
3393        }
3394
3395        public static final Creator<RunningAppProcessInfo> CREATOR =
3396            new Creator<RunningAppProcessInfo>() {
3397            public RunningAppProcessInfo createFromParcel(Parcel source) {
3398                return new RunningAppProcessInfo(source);
3399            }
3400            public RunningAppProcessInfo[] newArray(int size) {
3401                return new RunningAppProcessInfo[size];
3402            }
3403        };
3404
3405        private RunningAppProcessInfo(Parcel source) {
3406            readFromParcel(source);
3407        }
3408    }
3409
3410    /**
3411     * Returns a list of application processes installed on external media
3412     * that are running on the device.
3413     *
3414     * <p><b>Note: this method is only intended for debugging or building
3415     * a user-facing process management UI.</b></p>
3416     *
3417     * @return Returns a list of ApplicationInfo records, or null if none
3418     * This list ordering is not specified.
3419     * @hide
3420     */
3421    public List<ApplicationInfo> getRunningExternalApplications() {
3422        try {
3423            return getService().getRunningExternalApplications();
3424        } catch (RemoteException e) {
3425            throw e.rethrowFromSystemServer();
3426        }
3427    }
3428
3429    /**
3430     * Sets the memory trim mode for a process and schedules a memory trim operation.
3431     *
3432     * <p><b>Note: this method is only intended for testing framework.</b></p>
3433     *
3434     * @return Returns true if successful.
3435     * @hide
3436     */
3437    public boolean setProcessMemoryTrimLevel(String process, int userId, int level) {
3438        try {
3439            return getService().setProcessMemoryTrimLevel(process, userId,
3440                    level);
3441        } catch (RemoteException e) {
3442            throw e.rethrowFromSystemServer();
3443        }
3444    }
3445
3446    /**
3447     * Returns a list of application processes that are running on the device.
3448     *
3449     * <p><b>Note: this method is only intended for debugging or building
3450     * a user-facing process management UI.</b></p>
3451     *
3452     * @return Returns a list of RunningAppProcessInfo records, or null if there are no
3453     * running processes (it will not return an empty list).  This list ordering is not
3454     * specified.
3455     */
3456    public List<RunningAppProcessInfo> getRunningAppProcesses() {
3457        try {
3458            return getService().getRunningAppProcesses();
3459        } catch (RemoteException e) {
3460            throw e.rethrowFromSystemServer();
3461        }
3462    }
3463
3464    /**
3465     * Return the importance of a given package name, based on the processes that are
3466     * currently running.  The return value is one of the importance constants defined
3467     * in {@link RunningAppProcessInfo}, giving you the highest importance of all the
3468     * processes that this package has code running inside of.  If there are no processes
3469     * running its code, {@link RunningAppProcessInfo#IMPORTANCE_GONE} is returned.
3470     * @hide
3471     */
3472    @SystemApi @TestApi
3473    @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
3474    public int getPackageImportance(String packageName) {
3475        try {
3476            int procState = getService().getPackageProcessState(packageName,
3477                    mContext.getOpPackageName());
3478            return RunningAppProcessInfo.procStateToImportanceForClient(procState, mContext);
3479        } catch (RemoteException e) {
3480            throw e.rethrowFromSystemServer();
3481        }
3482    }
3483
3484    /**
3485     * Return the importance of a given uid, based on the processes that are
3486     * currently running.  The return value is one of the importance constants defined
3487     * in {@link RunningAppProcessInfo}, giving you the highest importance of all the
3488     * processes that this uid has running.  If there are no processes
3489     * running its code, {@link RunningAppProcessInfo#IMPORTANCE_GONE} is returned.
3490     * @hide
3491     */
3492    @SystemApi @TestApi
3493    @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
3494    public int getUidImportance(int uid) {
3495        try {
3496            int procState = getService().getUidProcessState(uid,
3497                    mContext.getOpPackageName());
3498            return RunningAppProcessInfo.procStateToImportanceForClient(procState, mContext);
3499        } catch (RemoteException e) {
3500            throw e.rethrowFromSystemServer();
3501        }
3502    }
3503
3504    /**
3505     * Callback to get reports about changes to the importance of a uid.  Use with
3506     * {@link #addOnUidImportanceListener}.
3507     * @hide
3508     */
3509    @SystemApi @TestApi
3510    public interface OnUidImportanceListener {
3511        /**
3512         * The importance if a given uid has changed.  Will be one of the importance
3513         * values in {@link RunningAppProcessInfo};
3514         * {@link RunningAppProcessInfo#IMPORTANCE_GONE IMPORTANCE_GONE} will be reported
3515         * when the uid is no longer running at all.  This callback will happen on a thread
3516         * from a thread pool, not the main UI thread.
3517         * @param uid The uid whose importance has changed.
3518         * @param importance The new importance value as per {@link RunningAppProcessInfo}.
3519         */
3520        void onUidImportance(int uid, int importance);
3521    }
3522
3523    /**
3524     * Start monitoring changes to the imoportance of uids running in the system.
3525     * @param listener The listener callback that will receive change reports.
3526     * @param importanceCutpoint The level of importance in which the caller is interested
3527     * in differences.  For example, if {@link RunningAppProcessInfo#IMPORTANCE_PERCEPTIBLE}
3528     * is used here, you will receive a call each time a uids importance transitions between
3529     * being <= {@link RunningAppProcessInfo#IMPORTANCE_PERCEPTIBLE} and
3530     * > {@link RunningAppProcessInfo#IMPORTANCE_PERCEPTIBLE}.
3531     *
3532     * <p>The caller must hold the {@link android.Manifest.permission#PACKAGE_USAGE_STATS}
3533     * permission to use this feature.</p>
3534     *
3535     * @throws IllegalArgumentException If the listener is already registered.
3536     * @throws SecurityException If the caller does not hold
3537     * {@link android.Manifest.permission#PACKAGE_USAGE_STATS}.
3538     * @hide
3539     */
3540    @SystemApi @TestApi
3541    public void addOnUidImportanceListener(OnUidImportanceListener listener,
3542            int importanceCutpoint) {
3543        synchronized (this) {
3544            if (mImportanceListeners.containsKey(listener)) {
3545                throw new IllegalArgumentException("Listener already registered: " + listener);
3546            }
3547            // TODO: implement the cut point in the system process to avoid IPCs.
3548            UidObserver observer = new UidObserver(listener, mContext);
3549            try {
3550                getService().registerUidObserver(observer,
3551                        UID_OBSERVER_PROCSTATE | UID_OBSERVER_GONE,
3552                        RunningAppProcessInfo.importanceToProcState(importanceCutpoint),
3553                        mContext.getOpPackageName());
3554            } catch (RemoteException e) {
3555                throw e.rethrowFromSystemServer();
3556            }
3557            mImportanceListeners.put(listener, observer);
3558        }
3559    }
3560
3561    /**
3562     * Remove an importance listener that was previously registered with
3563     * {@link #addOnUidImportanceListener}.
3564     *
3565     * @throws IllegalArgumentException If the listener is not registered.
3566     * @hide
3567     */
3568    @SystemApi @TestApi
3569    public void removeOnUidImportanceListener(OnUidImportanceListener listener) {
3570        synchronized (this) {
3571            UidObserver observer = mImportanceListeners.remove(listener);
3572            if (observer == null) {
3573                throw new IllegalArgumentException("Listener not registered: " + listener);
3574            }
3575            try {
3576                getService().unregisterUidObserver(observer);
3577            } catch (RemoteException e) {
3578                throw e.rethrowFromSystemServer();
3579            }
3580        }
3581    }
3582
3583    /**
3584     * Return global memory state information for the calling process.  This
3585     * does not fill in all fields of the {@link RunningAppProcessInfo}.  The
3586     * only fields that will be filled in are
3587     * {@link RunningAppProcessInfo#pid},
3588     * {@link RunningAppProcessInfo#uid},
3589     * {@link RunningAppProcessInfo#lastTrimLevel},
3590     * {@link RunningAppProcessInfo#importance},
3591     * {@link RunningAppProcessInfo#lru}, and
3592     * {@link RunningAppProcessInfo#importanceReasonCode}.
3593     */
3594    static public void getMyMemoryState(RunningAppProcessInfo outState) {
3595        try {
3596            getService().getMyMemoryState(outState);
3597        } catch (RemoteException e) {
3598            throw e.rethrowFromSystemServer();
3599        }
3600    }
3601
3602    /**
3603     * Return information about the memory usage of one or more processes.
3604     *
3605     * <p><b>Note: this method is only intended for debugging or building
3606     * a user-facing process management UI.</b></p>
3607     *
3608     * @param pids The pids of the processes whose memory usage is to be
3609     * retrieved.
3610     * @return Returns an array of memory information, one for each
3611     * requested pid.
3612     */
3613    public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
3614        try {
3615            return getService().getProcessMemoryInfo(pids);
3616        } catch (RemoteException e) {
3617            throw e.rethrowFromSystemServer();
3618        }
3619    }
3620
3621    /**
3622     * @deprecated This is now just a wrapper for
3623     * {@link #killBackgroundProcesses(String)}; the previous behavior here
3624     * is no longer available to applications because it allows them to
3625     * break other applications by removing their alarms, stopping their
3626     * services, etc.
3627     */
3628    @Deprecated
3629    public void restartPackage(String packageName) {
3630        killBackgroundProcesses(packageName);
3631    }
3632
3633    /**
3634     * Have the system immediately kill all background processes associated
3635     * with the given package.  This is the same as the kernel killing those
3636     * processes to reclaim memory; the system will take care of restarting
3637     * these processes in the future as needed.
3638     *
3639     * <p>You must hold the permission
3640     * {@link android.Manifest.permission#KILL_BACKGROUND_PROCESSES} to be able to
3641     * call this method.
3642     *
3643     * @param packageName The name of the package whose processes are to
3644     * be killed.
3645     */
3646    public void killBackgroundProcesses(String packageName) {
3647        try {
3648            getService().killBackgroundProcesses(packageName,
3649                    UserHandle.myUserId());
3650        } catch (RemoteException e) {
3651            throw e.rethrowFromSystemServer();
3652        }
3653    }
3654
3655    /**
3656     * Kills the specified UID.
3657     * @param uid The UID to kill.
3658     * @param reason The reason for the kill.
3659     *
3660     * @hide
3661     */
3662    @SystemApi
3663    @RequiresPermission(Manifest.permission.KILL_UID)
3664    public void killUid(int uid, String reason) {
3665        try {
3666            getService().killUid(UserHandle.getAppId(uid),
3667                    UserHandle.getUserId(uid), reason);
3668        } catch (RemoteException e) {
3669            throw e.rethrowFromSystemServer();
3670        }
3671    }
3672
3673    /**
3674     * Have the system perform a force stop of everything associated with
3675     * the given application package.  All processes that share its uid
3676     * will be killed, all services it has running stopped, all activities
3677     * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
3678     * broadcast will be sent, so that any of its registered alarms can
3679     * be stopped, notifications removed, etc.
3680     *
3681     * <p>You must hold the permission
3682     * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
3683     * call this method.
3684     *
3685     * @param packageName The name of the package to be stopped.
3686     * @param userId The user for which the running package is to be stopped.
3687     *
3688     * @hide This is not available to third party applications due to
3689     * it allowing them to break other applications by stopping their
3690     * services, removing their alarms, etc.
3691     */
3692    public void forceStopPackageAsUser(String packageName, int userId) {
3693        try {
3694            getService().forceStopPackage(packageName, userId);
3695        } catch (RemoteException e) {
3696            throw e.rethrowFromSystemServer();
3697        }
3698    }
3699
3700    /**
3701     * @see #forceStopPackageAsUser(String, int)
3702     * @hide
3703     */
3704    @SystemApi
3705    @RequiresPermission(Manifest.permission.FORCE_STOP_PACKAGES)
3706    public void forceStopPackage(String packageName) {
3707        forceStopPackageAsUser(packageName, UserHandle.myUserId());
3708    }
3709
3710    /**
3711     * Get the device configuration attributes.
3712     */
3713    public ConfigurationInfo getDeviceConfigurationInfo() {
3714        try {
3715            return getService().getDeviceConfigurationInfo();
3716        } catch (RemoteException e) {
3717            throw e.rethrowFromSystemServer();
3718        }
3719    }
3720
3721    /**
3722     * Get the preferred density of icons for the launcher. This is used when
3723     * custom drawables are created (e.g., for shortcuts).
3724     *
3725     * @return density in terms of DPI
3726     */
3727    public int getLauncherLargeIconDensity() {
3728        final Resources res = mContext.getResources();
3729        final int density = res.getDisplayMetrics().densityDpi;
3730        final int sw = res.getConfiguration().smallestScreenWidthDp;
3731
3732        if (sw < 600) {
3733            // Smaller than approx 7" tablets, use the regular icon size.
3734            return density;
3735        }
3736
3737        switch (density) {
3738            case DisplayMetrics.DENSITY_LOW:
3739                return DisplayMetrics.DENSITY_MEDIUM;
3740            case DisplayMetrics.DENSITY_MEDIUM:
3741                return DisplayMetrics.DENSITY_HIGH;
3742            case DisplayMetrics.DENSITY_TV:
3743                return DisplayMetrics.DENSITY_XHIGH;
3744            case DisplayMetrics.DENSITY_HIGH:
3745                return DisplayMetrics.DENSITY_XHIGH;
3746            case DisplayMetrics.DENSITY_XHIGH:
3747                return DisplayMetrics.DENSITY_XXHIGH;
3748            case DisplayMetrics.DENSITY_XXHIGH:
3749                return DisplayMetrics.DENSITY_XHIGH * 2;
3750            default:
3751                // The density is some abnormal value.  Return some other
3752                // abnormal value that is a reasonable scaling of it.
3753                return (int)((density*1.5f)+.5f);
3754        }
3755    }
3756
3757    /**
3758     * Get the preferred launcher icon size. This is used when custom drawables
3759     * are created (e.g., for shortcuts).
3760     *
3761     * @return dimensions of square icons in terms of pixels
3762     */
3763    public int getLauncherLargeIconSize() {
3764        return getLauncherLargeIconSizeInner(mContext);
3765    }
3766
3767    static int getLauncherLargeIconSizeInner(Context context) {
3768        final Resources res = context.getResources();
3769        final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size);
3770        final int sw = res.getConfiguration().smallestScreenWidthDp;
3771
3772        if (sw < 600) {
3773            // Smaller than approx 7" tablets, use the regular icon size.
3774            return size;
3775        }
3776
3777        final int density = res.getDisplayMetrics().densityDpi;
3778
3779        switch (density) {
3780            case DisplayMetrics.DENSITY_LOW:
3781                return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW;
3782            case DisplayMetrics.DENSITY_MEDIUM:
3783                return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM;
3784            case DisplayMetrics.DENSITY_TV:
3785                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
3786            case DisplayMetrics.DENSITY_HIGH:
3787                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
3788            case DisplayMetrics.DENSITY_XHIGH:
3789                return (size * DisplayMetrics.DENSITY_XXHIGH) / DisplayMetrics.DENSITY_XHIGH;
3790            case DisplayMetrics.DENSITY_XXHIGH:
3791                return (size * DisplayMetrics.DENSITY_XHIGH*2) / DisplayMetrics.DENSITY_XXHIGH;
3792            default:
3793                // The density is some abnormal value.  Return some other
3794                // abnormal value that is a reasonable scaling of it.
3795                return (int)((size*1.5f) + .5f);
3796        }
3797    }
3798
3799    /**
3800     * Returns "true" if the user interface is currently being messed with
3801     * by a monkey.
3802     */
3803    public static boolean isUserAMonkey() {
3804        try {
3805            return getService().isUserAMonkey();
3806        } catch (RemoteException e) {
3807            throw e.rethrowFromSystemServer();
3808        }
3809    }
3810
3811    /**
3812     * Returns "true" if device is running in a test harness.
3813     */
3814    public static boolean isRunningInTestHarness() {
3815        return SystemProperties.getBoolean("ro.test_harness", false);
3816    }
3817
3818    /**
3819     * Returns the launch count of each installed package.
3820     *
3821     * @hide
3822     */
3823    /*public Map<String, Integer> getAllPackageLaunchCounts() {
3824        try {
3825            IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
3826                    ServiceManager.getService("usagestats"));
3827            if (usageStatsService == null) {
3828                return new HashMap<String, Integer>();
3829            }
3830
3831            UsageStats.PackageStats[] allPkgUsageStats = usageStatsService.getAllPkgUsageStats(
3832                    ActivityThread.currentPackageName());
3833            if (allPkgUsageStats == null) {
3834                return new HashMap<String, Integer>();
3835            }
3836
3837            Map<String, Integer> launchCounts = new HashMap<String, Integer>();
3838            for (UsageStats.PackageStats pkgUsageStats : allPkgUsageStats) {
3839                launchCounts.put(pkgUsageStats.getPackageName(), pkgUsageStats.getLaunchCount());
3840            }
3841
3842            return launchCounts;
3843        } catch (RemoteException e) {
3844            Log.w(TAG, "Could not query launch counts", e);
3845            return new HashMap<String, Integer>();
3846        }
3847    }*/
3848
3849    /** @hide */
3850    public static int checkComponentPermission(String permission, int uid,
3851            int owningUid, boolean exported) {
3852        // Root, system server get to do everything.
3853        final int appId = UserHandle.getAppId(uid);
3854        if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) {
3855            return PackageManager.PERMISSION_GRANTED;
3856        }
3857        // Isolated processes don't get any permissions.
3858        if (UserHandle.isIsolated(uid)) {
3859            return PackageManager.PERMISSION_DENIED;
3860        }
3861        // If there is a uid that owns whatever is being accessed, it has
3862        // blanket access to it regardless of the permissions it requires.
3863        if (owningUid >= 0 && UserHandle.isSameApp(uid, owningUid)) {
3864            return PackageManager.PERMISSION_GRANTED;
3865        }
3866        // If the target is not exported, then nobody else can get to it.
3867        if (!exported) {
3868            /*
3869            RuntimeException here = new RuntimeException("here");
3870            here.fillInStackTrace();
3871            Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid,
3872                    here);
3873            */
3874            return PackageManager.PERMISSION_DENIED;
3875        }
3876        if (permission == null) {
3877            return PackageManager.PERMISSION_GRANTED;
3878        }
3879        try {
3880            return AppGlobals.getPackageManager()
3881                    .checkUidPermission(permission, uid);
3882        } catch (RemoteException e) {
3883            throw e.rethrowFromSystemServer();
3884        }
3885    }
3886
3887    /** @hide */
3888    public static int checkUidPermission(String permission, int uid) {
3889        try {
3890            return AppGlobals.getPackageManager()
3891                    .checkUidPermission(permission, uid);
3892        } catch (RemoteException e) {
3893            throw e.rethrowFromSystemServer();
3894        }
3895    }
3896
3897    /**
3898     * @hide
3899     * Helper for dealing with incoming user arguments to system service calls.
3900     * Takes care of checking permissions and converting USER_CURRENT to the
3901     * actual current user.
3902     *
3903     * @param callingPid The pid of the incoming call, as per Binder.getCallingPid().
3904     * @param callingUid The uid of the incoming call, as per Binder.getCallingUid().
3905     * @param userId The user id argument supplied by the caller -- this is the user
3906     * they want to run as.
3907     * @param allowAll If true, we will allow USER_ALL.  This means you must be prepared
3908     * to get a USER_ALL returned and deal with it correctly.  If false,
3909     * an exception will be thrown if USER_ALL is supplied.
3910     * @param requireFull If true, the caller must hold
3911     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} to be able to run as a
3912     * different user than their current process; otherwise they must hold
3913     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS}.
3914     * @param name Optional textual name of the incoming call; only for generating error messages.
3915     * @param callerPackage Optional package name of caller; only for error messages.
3916     *
3917     * @return Returns the user ID that the call should run as.  Will always be a concrete
3918     * user number, unless <var>allowAll</var> is true in which case it could also be
3919     * USER_ALL.
3920     */
3921    public static int handleIncomingUser(int callingPid, int callingUid, int userId,
3922            boolean allowAll, boolean requireFull, String name, String callerPackage) {
3923        if (UserHandle.getUserId(callingUid) == userId) {
3924            return userId;
3925        }
3926        try {
3927            return getService().handleIncomingUser(callingPid,
3928                    callingUid, userId, allowAll, requireFull, name, callerPackage);
3929        } catch (RemoteException e) {
3930            throw e.rethrowFromSystemServer();
3931        }
3932    }
3933
3934    /**
3935     * Gets the userId of the current foreground user. Requires system permissions.
3936     * @hide
3937     */
3938    @SystemApi
3939    public static int getCurrentUser() {
3940        UserInfo ui;
3941        try {
3942            ui = getService().getCurrentUser();
3943            return ui != null ? ui.id : 0;
3944        } catch (RemoteException e) {
3945            throw e.rethrowFromSystemServer();
3946        }
3947    }
3948
3949    /**
3950     * @param userid the user's id. Zero indicates the default user.
3951     * @hide
3952     */
3953    public boolean switchUser(int userid) {
3954        try {
3955            return getService().switchUser(userid);
3956        } catch (RemoteException e) {
3957            throw e.rethrowFromSystemServer();
3958        }
3959    }
3960
3961    /**
3962     * Logs out current current foreground user by switching to the system user and stopping the
3963     * user being switched from.
3964     * @hide
3965     */
3966    public static void logoutCurrentUser() {
3967        int currentUser = ActivityManager.getCurrentUser();
3968        if (currentUser != UserHandle.USER_SYSTEM) {
3969            try {
3970                getService().switchUser(UserHandle.USER_SYSTEM);
3971                getService().stopUser(currentUser, /* force= */ false, null);
3972            } catch (RemoteException e) {
3973                e.rethrowFromSystemServer();
3974            }
3975        }
3976    }
3977
3978    /** {@hide} */
3979    public static final int FLAG_OR_STOPPED = 1 << 0;
3980    /** {@hide} */
3981    public static final int FLAG_AND_LOCKED = 1 << 1;
3982    /** {@hide} */
3983    public static final int FLAG_AND_UNLOCKED = 1 << 2;
3984    /** {@hide} */
3985    public static final int FLAG_AND_UNLOCKING_OR_UNLOCKED = 1 << 3;
3986
3987    /**
3988     * Return whether the given user is actively running.  This means that
3989     * the user is in the "started" state, not "stopped" -- it is currently
3990     * allowed to run code through scheduled alarms, receiving broadcasts,
3991     * etc.  A started user may be either the current foreground user or a
3992     * background user; the result here does not distinguish between the two.
3993     * @param userId the user's id. Zero indicates the default user.
3994     * @hide
3995     */
3996    public boolean isUserRunning(int userId) {
3997        try {
3998            return getService().isUserRunning(userId, 0);
3999        } catch (RemoteException e) {
4000            throw e.rethrowFromSystemServer();
4001        }
4002    }
4003
4004    /** {@hide} */
4005    public boolean isVrModePackageEnabled(ComponentName component) {
4006        try {
4007            return getService().isVrModePackageEnabled(component);
4008        } catch (RemoteException e) {
4009            throw e.rethrowFromSystemServer();
4010        }
4011    }
4012
4013    /**
4014     * Perform a system dump of various state associated with the given application
4015     * package name.  This call blocks while the dump is being performed, so should
4016     * not be done on a UI thread.  The data will be written to the given file
4017     * descriptor as text.  An application must hold the
4018     * {@link android.Manifest.permission#DUMP} permission to make this call.
4019     * @param fd The file descriptor that the dump should be written to.  The file
4020     * descriptor is <em>not</em> closed by this function; the caller continues to
4021     * own it.
4022     * @param packageName The name of the package that is to be dumped.
4023     */
4024    public void dumpPackageState(FileDescriptor fd, String packageName) {
4025        dumpPackageStateStatic(fd, packageName);
4026    }
4027
4028    /**
4029     * @hide
4030     */
4031    public static void dumpPackageStateStatic(FileDescriptor fd, String packageName) {
4032        FileOutputStream fout = new FileOutputStream(fd);
4033        PrintWriter pw = new FastPrintWriter(fout);
4034        dumpService(pw, fd, "package", new String[] { packageName });
4035        pw.println();
4036        dumpService(pw, fd, Context.ACTIVITY_SERVICE, new String[] {
4037                "-a", "package", packageName });
4038        pw.println();
4039        dumpService(pw, fd, "meminfo", new String[] { "--local", "--package", packageName });
4040        pw.println();
4041        dumpService(pw, fd, ProcessStats.SERVICE_NAME, new String[] { packageName });
4042        pw.println();
4043        dumpService(pw, fd, "usagestats", new String[] { "--packages", packageName });
4044        pw.println();
4045        dumpService(pw, fd, BatteryStats.SERVICE_NAME, new String[] { packageName });
4046        pw.flush();
4047    }
4048
4049    /**
4050     * @hide
4051     */
4052    public static boolean isSystemReady() {
4053        if (!sSystemReady) {
4054            if (ActivityThread.isSystem()) {
4055                sSystemReady =
4056                        LocalServices.getService(ActivityManagerInternal.class).isSystemReady();
4057            } else {
4058                // Since this is being called from outside system server, system should be
4059                // ready by now.
4060                sSystemReady = true;
4061            }
4062        }
4063        return sSystemReady;
4064    }
4065
4066    /**
4067     * @hide
4068     */
4069    public static void broadcastStickyIntent(Intent intent, int userId) {
4070        broadcastStickyIntent(intent, AppOpsManager.OP_NONE, userId);
4071    }
4072
4073    /**
4074     * Convenience for sending a sticky broadcast.  For internal use only.
4075     *
4076     * @hide
4077     */
4078    public static void broadcastStickyIntent(Intent intent, int appOp, int userId) {
4079        try {
4080            getService().broadcastIntent(
4081                    null, intent, null, null, Activity.RESULT_OK, null, null,
4082                    null /*permission*/, appOp, null, false, true, userId);
4083        } catch (RemoteException ex) {
4084        }
4085    }
4086
4087    /**
4088     * @hide
4089     */
4090    public static void noteWakeupAlarm(PendingIntent ps, int sourceUid, String sourcePkg,
4091            String tag) {
4092        try {
4093            getService().noteWakeupAlarm((ps != null) ? ps.getTarget() : null,
4094                    sourceUid, sourcePkg, tag);
4095        } catch (RemoteException ex) {
4096        }
4097    }
4098
4099    /**
4100     * @hide
4101     */
4102    public static void noteAlarmStart(PendingIntent ps, int sourceUid, String tag) {
4103        try {
4104            getService().noteAlarmStart((ps != null) ? ps.getTarget() : null, sourceUid, tag);
4105        } catch (RemoteException ex) {
4106        }
4107    }
4108
4109    /**
4110     * @hide
4111     */
4112    public static void noteAlarmFinish(PendingIntent ps, int sourceUid, String tag) {
4113        try {
4114            getService().noteAlarmFinish((ps != null) ? ps.getTarget() : null, sourceUid, tag);
4115        } catch (RemoteException ex) {
4116        }
4117    }
4118
4119    /**
4120     * @hide
4121     */
4122    public static IActivityManager getService() {
4123        return IActivityManagerSingleton.get();
4124    }
4125
4126    private static final Singleton<IActivityManager> IActivityManagerSingleton =
4127            new Singleton<IActivityManager>() {
4128                @Override
4129                protected IActivityManager create() {
4130                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
4131                    final IActivityManager am = IActivityManager.Stub.asInterface(b);
4132                    return am;
4133                }
4134            };
4135
4136    private static void dumpService(PrintWriter pw, FileDescriptor fd, String name, String[] args) {
4137        pw.print("DUMP OF SERVICE "); pw.print(name); pw.println(":");
4138        IBinder service = ServiceManager.checkService(name);
4139        if (service == null) {
4140            pw.println("  (Service not found)");
4141            return;
4142        }
4143        TransferPipe tp = null;
4144        try {
4145            pw.flush();
4146            tp = new TransferPipe();
4147            tp.setBufferPrefix("  ");
4148            service.dumpAsync(tp.getWriteFd().getFileDescriptor(), args);
4149            tp.go(fd, 10000);
4150        } catch (Throwable e) {
4151            if (tp != null) {
4152                tp.kill();
4153            }
4154            pw.println("Failure dumping service:");
4155            e.printStackTrace(pw);
4156        }
4157    }
4158
4159    /**
4160     * Request that the system start watching for the calling process to exceed a pss
4161     * size as given here.  Once called, the system will look for any occasions where it
4162     * sees the associated process with a larger pss size and, when this happens, automatically
4163     * pull a heap dump from it and allow the user to share the data.  Note that this request
4164     * continues running even if the process is killed and restarted.  To remove the watch,
4165     * use {@link #clearWatchHeapLimit()}.
4166     *
4167     * <p>This API only work if the calling process has been marked as
4168     * {@link ApplicationInfo#FLAG_DEBUGGABLE} or this is running on a debuggable
4169     * (userdebug or eng) build.</p>
4170     *
4171     * <p>Callers can optionally implement {@link #ACTION_REPORT_HEAP_LIMIT} to directly
4172     * handle heap limit reports themselves.</p>
4173     *
4174     * @param pssSize The size in bytes to set the limit at.
4175     */
4176    public void setWatchHeapLimit(long pssSize) {
4177        try {
4178            getService().setDumpHeapDebugLimit(null, 0, pssSize,
4179                    mContext.getPackageName());
4180        } catch (RemoteException e) {
4181            throw e.rethrowFromSystemServer();
4182        }
4183    }
4184
4185    /**
4186     * Action an app can implement to handle reports from {@link #setWatchHeapLimit(long)}.
4187     * If your package has an activity handling this action, it will be launched with the
4188     * heap data provided to it the same way as {@link Intent#ACTION_SEND}.  Note that to
4189     * match the activty must support this action and a MIME type of "*&#47;*".
4190     */
4191    public static final String ACTION_REPORT_HEAP_LIMIT = "android.app.action.REPORT_HEAP_LIMIT";
4192
4193    /**
4194     * Clear a heap watch limit previously set by {@link #setWatchHeapLimit(long)}.
4195     */
4196    public void clearWatchHeapLimit() {
4197        try {
4198            getService().setDumpHeapDebugLimit(null, 0, 0, null);
4199        } catch (RemoteException e) {
4200            throw e.rethrowFromSystemServer();
4201        }
4202    }
4203
4204    /**
4205     * @hide
4206     */
4207    public void startLockTaskMode(int taskId) {
4208        try {
4209            getService().startLockTaskModeById(taskId);
4210        } catch (RemoteException e) {
4211            throw e.rethrowFromSystemServer();
4212        }
4213    }
4214
4215    /**
4216     * @hide
4217     */
4218    public void stopLockTaskMode() {
4219        try {
4220            getService().stopLockTaskMode();
4221        } catch (RemoteException e) {
4222            throw e.rethrowFromSystemServer();
4223        }
4224    }
4225
4226    /**
4227     * Return whether currently in lock task mode.  When in this mode
4228     * no new tasks can be created or switched to.
4229     *
4230     * @see Activity#startLockTask()
4231     *
4232     * @deprecated Use {@link #getLockTaskModeState} instead.
4233     */
4234    @Deprecated
4235    public boolean isInLockTaskMode() {
4236        return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
4237    }
4238
4239    /**
4240     * Return the current state of task locking. The three possible outcomes
4241     * are {@link #LOCK_TASK_MODE_NONE}, {@link #LOCK_TASK_MODE_LOCKED}
4242     * and {@link #LOCK_TASK_MODE_PINNED}.
4243     *
4244     * @see Activity#startLockTask()
4245     */
4246    public int getLockTaskModeState() {
4247        try {
4248            return getService().getLockTaskModeState();
4249        } catch (RemoteException e) {
4250            throw e.rethrowFromSystemServer();
4251        }
4252    }
4253
4254    /**
4255     * Enable more aggressive scheduling for latency-sensitive low-runtime VR threads. Only one
4256     * thread can be a VR thread in a process at a time, and that thread may be subject to
4257     * restrictions on the amount of time it can run.
4258     *
4259     * If persistent VR mode is set, whatever thread has been granted aggressive scheduling via this
4260     * method will return to normal operation, and calling this method will do nothing while
4261     * persistent VR mode is enabled.
4262     *
4263     * To reset the VR thread for an application, a tid of 0 can be passed.
4264     *
4265     * @see android.os.Process#myTid()
4266     * @param tid tid of the VR thread
4267     */
4268    public static void setVrThread(int tid) {
4269        try {
4270            getService().setVrThread(tid);
4271        } catch (RemoteException e) {
4272            // pass
4273        }
4274    }
4275
4276    /**
4277     * Enable more aggressive scheduling for latency-sensitive low-runtime VR threads that persist
4278     * beyond a single process. It requires holding the
4279     * {@link android.Manifest.permission#RESTRICTED_VR_ACCESS} permission. Only one thread can be a
4280     * persistent VR thread at a time, and that thread may be subject to restrictions on the amount
4281     * of time it can run. Calling this method will disable aggressive scheduling for non-persistent
4282     * VR threads set via {@link #setVrThread}. If persistent VR mode is disabled then the
4283     * persistent VR thread loses its new scheduling priority; this method must be called again to
4284     * set the persistent thread.
4285     *
4286     * To reset the persistent VR thread, a tid of 0 can be passed.
4287     *
4288     * @see android.os.Process#myTid()
4289     * @param tid tid of the VR thread
4290     * @hide
4291     */
4292    @RequiresPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
4293    public static void setPersistentVrThread(int tid) {
4294        try {
4295            getService().setPersistentVrThread(tid);
4296        } catch (RemoteException e) {
4297            // pass
4298        }
4299    }
4300
4301    /**
4302     * The AppTask allows you to manage your own application's tasks.
4303     * See {@link android.app.ActivityManager#getAppTasks()}
4304     */
4305    public static class AppTask {
4306        private IAppTask mAppTaskImpl;
4307
4308        /** @hide */
4309        public AppTask(IAppTask task) {
4310            mAppTaskImpl = task;
4311        }
4312
4313        /**
4314         * Finishes all activities in this task and removes it from the recent tasks list.
4315         */
4316        public void finishAndRemoveTask() {
4317            try {
4318                mAppTaskImpl.finishAndRemoveTask();
4319            } catch (RemoteException e) {
4320                throw e.rethrowFromSystemServer();
4321            }
4322        }
4323
4324        /**
4325         * Get the RecentTaskInfo associated with this task.
4326         *
4327         * @return The RecentTaskInfo for this task, or null if the task no longer exists.
4328         */
4329        public RecentTaskInfo getTaskInfo() {
4330            try {
4331                return mAppTaskImpl.getTaskInfo();
4332            } catch (RemoteException e) {
4333                throw e.rethrowFromSystemServer();
4334            }
4335        }
4336
4337        /**
4338         * Bring this task to the foreground.  If it contains activities, they will be
4339         * brought to the foreground with it and their instances re-created if needed.
4340         * If it doesn't contain activities, the root activity of the task will be
4341         * re-launched.
4342         */
4343        public void moveToFront() {
4344            try {
4345                mAppTaskImpl.moveToFront();
4346            } catch (RemoteException e) {
4347                throw e.rethrowFromSystemServer();
4348            }
4349        }
4350
4351        /**
4352         * Start an activity in this task.  Brings the task to the foreground.  If this task
4353         * is not currently active (that is, its id < 0), then a new activity for the given
4354         * Intent will be launched as the root of the task and the task brought to the
4355         * foreground.  Otherwise, if this task is currently active and the Intent does not specify
4356         * an activity to launch in a new task, then a new activity for the given Intent will
4357         * be launched on top of the task and the task brought to the foreground.  If this
4358         * task is currently active and the Intent specifies {@link Intent#FLAG_ACTIVITY_NEW_TASK}
4359         * or would otherwise be launched in to a new task, then the activity not launched but
4360         * this task be brought to the foreground and a new intent delivered to the top
4361         * activity if appropriate.
4362         *
4363         * <p>In other words, you generally want to use an Intent here that does not specify
4364         * {@link Intent#FLAG_ACTIVITY_NEW_TASK} or {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT},
4365         * and let the system do the right thing.</p>
4366         *
4367         * @param intent The Intent describing the new activity to be launched on the task.
4368         * @param options Optional launch options.
4369         *
4370         * @see Activity#startActivity(android.content.Intent, android.os.Bundle)
4371         */
4372        public void startActivity(Context context, Intent intent, Bundle options) {
4373            ActivityThread thread = ActivityThread.currentActivityThread();
4374            thread.getInstrumentation().execStartActivityFromAppTask(context,
4375                    thread.getApplicationThread(), mAppTaskImpl, intent, options);
4376        }
4377
4378        /**
4379         * Modify the {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag in the root
4380         * Intent of this AppTask.
4381         *
4382         * @param exclude If true, {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} will
4383         * be set; otherwise, it will be cleared.
4384         */
4385        public void setExcludeFromRecents(boolean exclude) {
4386            try {
4387                mAppTaskImpl.setExcludeFromRecents(exclude);
4388            } catch (RemoteException e) {
4389                throw e.rethrowFromSystemServer();
4390            }
4391        }
4392    }
4393}
4394