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