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