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