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