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