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