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