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