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