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