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