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