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