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