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