ActivityManager.java revision 91268cf21eace600792d04db1ac62e9268f48002
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.os.BatteryStats;
20import android.os.IBinder;
21import com.android.internal.app.IUsageStats;
22import com.android.internal.os.PkgUsageStats;
23import com.android.internal.os.TransferPipe;
24import com.android.internal.util.MemInfoReader;
25
26import android.content.ComponentName;
27import android.content.Context;
28import android.content.Intent;
29import android.content.pm.ApplicationInfo;
30import android.content.pm.ConfigurationInfo;
31import android.content.pm.IPackageDataObserver;
32import android.content.pm.PackageManager;
33import android.content.pm.UserInfo;
34import android.content.res.Resources;
35import android.graphics.Bitmap;
36import android.graphics.Point;
37import android.graphics.Rect;
38import android.hardware.display.DisplayManagerGlobal;
39import android.os.Bundle;
40import android.os.Debug;
41import android.os.Handler;
42import android.os.Parcel;
43import android.os.Parcelable;
44import android.os.Process;
45import android.os.RemoteException;
46import android.os.ServiceManager;
47import android.os.SystemProperties;
48import android.os.UserHandle;
49import android.text.TextUtils;
50import android.util.DisplayMetrics;
51import android.util.Log;
52import android.util.Slog;
53import android.view.Display;
54
55import java.io.FileDescriptor;
56import java.io.FileOutputStream;
57import java.io.PrintWriter;
58import java.util.HashMap;
59import java.util.List;
60import java.util.Map;
61
62/**
63 * Interact with the overall activities running in the system.
64 */
65public class ActivityManager {
66    private static String TAG = "ActivityManager";
67    private static boolean localLOGV = false;
68
69    private final Context mContext;
70    private final Handler mHandler;
71
72    /**
73     * Result for IActivityManager.startActivity: an error where the
74     * start had to be canceled.
75     * @hide
76     */
77    public static final int START_CANCELED = -6;
78
79    /**
80     * Result for IActivityManager.startActivity: an error where the
81     * thing being started is not an activity.
82     * @hide
83     */
84    public static final int START_NOT_ACTIVITY = -5;
85
86    /**
87     * Result for IActivityManager.startActivity: an error where the
88     * caller does not have permission to start the activity.
89     * @hide
90     */
91    public static final int START_PERMISSION_DENIED = -4;
92
93    /**
94     * Result for IActivityManager.startActivity: an error where the
95     * caller has requested both to forward a result and to receive
96     * a result.
97     * @hide
98     */
99    public static final int START_FORWARD_AND_REQUEST_CONFLICT = -3;
100
101    /**
102     * Result for IActivityManager.startActivity: an error where the
103     * requested class is not found.
104     * @hide
105     */
106    public static final int START_CLASS_NOT_FOUND = -2;
107
108    /**
109     * Result for IActivityManager.startActivity: an error where the
110     * given Intent could not be resolved to an activity.
111     * @hide
112     */
113    public static final int START_INTENT_NOT_RESOLVED = -1;
114
115    /**
116     * Result for IActivityManaqer.startActivity: the activity was started
117     * successfully as normal.
118     * @hide
119     */
120    public static final int START_SUCCESS = 0;
121
122    /**
123     * Result for IActivityManaqer.startActivity: the caller asked that the Intent not
124     * be executed if it is the recipient, and that is indeed the case.
125     * @hide
126     */
127    public static final int START_RETURN_INTENT_TO_CALLER = 1;
128
129    /**
130     * Result for IActivityManaqer.startActivity: activity wasn't really started, but
131     * a task was simply brought to the foreground.
132     * @hide
133     */
134    public static final int START_TASK_TO_FRONT = 2;
135
136    /**
137     * Result for IActivityManaqer.startActivity: activity wasn't really started, but
138     * the given Intent was given to the existing top activity.
139     * @hide
140     */
141    public static final int START_DELIVERED_TO_TOP = 3;
142
143    /**
144     * Result for IActivityManaqer.startActivity: request was canceled because
145     * app switches are temporarily canceled to ensure the user's last request
146     * (such as pressing home) is performed.
147     * @hide
148     */
149    public static final int START_SWITCHES_CANCELED = 4;
150
151    /**
152     * Flag for IActivityManaqer.startActivity: do special start mode where
153     * a new activity is launched only if it is needed.
154     * @hide
155     */
156    public static final int START_FLAG_ONLY_IF_NEEDED = 1<<0;
157
158    /**
159     * Flag for IActivityManaqer.startActivity: launch the app for
160     * debugging.
161     * @hide
162     */
163    public static final int START_FLAG_DEBUG = 1<<1;
164
165    /**
166     * Flag for IActivityManaqer.startActivity: launch the app for
167     * OpenGL tracing.
168     * @hide
169     */
170    public static final int START_FLAG_OPENGL_TRACES = 1<<2;
171
172    /**
173     * Flag for IActivityManaqer.startActivity: if the app is being
174     * launched for profiling, automatically stop the profiler once done.
175     * @hide
176     */
177    public static final int START_FLAG_AUTO_STOP_PROFILER = 1<<3;
178
179    /**
180     * Result for IActivityManaqer.broadcastIntent: success!
181     * @hide
182     */
183    public static final int BROADCAST_SUCCESS = 0;
184
185    /**
186     * Result for IActivityManaqer.broadcastIntent: attempt to broadcast
187     * a sticky intent without appropriate permission.
188     * @hide
189     */
190    public static final int BROADCAST_STICKY_CANT_HAVE_PERMISSION = -1;
191
192    /**
193     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
194     * for a sendBroadcast operation.
195     * @hide
196     */
197    public static final int INTENT_SENDER_BROADCAST = 1;
198
199    /**
200     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
201     * for a startActivity operation.
202     * @hide
203     */
204    public static final int INTENT_SENDER_ACTIVITY = 2;
205
206    /**
207     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
208     * for an activity result operation.
209     * @hide
210     */
211    public static final int INTENT_SENDER_ACTIVITY_RESULT = 3;
212
213    /**
214     * Type for IActivityManaqer.getIntentSender: this PendingIntent is
215     * for a startService operation.
216     * @hide
217     */
218    public static final int INTENT_SENDER_SERVICE = 4;
219
220    /** @hide User operation call: success! */
221    public static final int USER_OP_SUCCESS = 0;
222
223    /** @hide User operation call: given user id is not known. */
224    public static final int USER_OP_UNKNOWN_USER = -1;
225
226    /** @hide User operation call: given user id is the current user, can't be stopped. */
227    public static final int USER_OP_IS_CURRENT = -2;
228
229    /*package*/ ActivityManager(Context context, Handler handler) {
230        mContext = context;
231        mHandler = handler;
232    }
233
234    /**
235     * Screen compatibility mode: the application most always run in
236     * compatibility mode.
237     * @hide
238     */
239    public static final int COMPAT_MODE_ALWAYS = -1;
240
241    /**
242     * Screen compatibility mode: the application can never run in
243     * compatibility mode.
244     * @hide
245     */
246    public static final int COMPAT_MODE_NEVER = -2;
247
248    /**
249     * Screen compatibility mode: unknown.
250     * @hide
251     */
252    public static final int COMPAT_MODE_UNKNOWN = -3;
253
254    /**
255     * Screen compatibility mode: the application currently has compatibility
256     * mode disabled.
257     * @hide
258     */
259    public static final int COMPAT_MODE_DISABLED = 0;
260
261    /**
262     * Screen compatibility mode: the application currently has compatibility
263     * mode enabled.
264     * @hide
265     */
266    public static final int COMPAT_MODE_ENABLED = 1;
267
268    /**
269     * Screen compatibility mode: request to toggle the application's
270     * compatibility mode.
271     * @hide
272     */
273    public static final int COMPAT_MODE_TOGGLE = 2;
274
275    /** @hide */
276    public int getFrontActivityScreenCompatMode() {
277        try {
278            return ActivityManagerNative.getDefault().getFrontActivityScreenCompatMode();
279        } catch (RemoteException e) {
280            // System dead, we will be dead too soon!
281            return 0;
282        }
283    }
284
285    /** @hide */
286    public void setFrontActivityScreenCompatMode(int mode) {
287        try {
288            ActivityManagerNative.getDefault().setFrontActivityScreenCompatMode(mode);
289        } catch (RemoteException e) {
290            // System dead, we will be dead too soon!
291        }
292    }
293
294    /** @hide */
295    public int getPackageScreenCompatMode(String packageName) {
296        try {
297            return ActivityManagerNative.getDefault().getPackageScreenCompatMode(packageName);
298        } catch (RemoteException e) {
299            // System dead, we will be dead too soon!
300            return 0;
301        }
302    }
303
304    /** @hide */
305    public void setPackageScreenCompatMode(String packageName, int mode) {
306        try {
307            ActivityManagerNative.getDefault().setPackageScreenCompatMode(packageName, mode);
308        } catch (RemoteException e) {
309            // System dead, we will be dead too soon!
310        }
311    }
312
313    /** @hide */
314    public boolean getPackageAskScreenCompat(String packageName) {
315        try {
316            return ActivityManagerNative.getDefault().getPackageAskScreenCompat(packageName);
317        } catch (RemoteException e) {
318            // System dead, we will be dead too soon!
319            return false;
320        }
321    }
322
323    /** @hide */
324    public void setPackageAskScreenCompat(String packageName, boolean ask) {
325        try {
326            ActivityManagerNative.getDefault().setPackageAskScreenCompat(packageName, ask);
327        } catch (RemoteException e) {
328            // System dead, we will be dead too soon!
329        }
330    }
331
332    /**
333     * Return the approximate per-application memory class of the current
334     * device.  This gives you an idea of how hard a memory limit you should
335     * impose on your application to let the overall system work best.  The
336     * returned value is in megabytes; the baseline Android memory class is
337     * 16 (which happens to be the Java heap limit of those devices); some
338     * device with more memory may return 24 or even higher numbers.
339     */
340    public int getMemoryClass() {
341        return staticGetMemoryClass();
342    }
343
344    /** @hide */
345    static public int staticGetMemoryClass() {
346        // Really brain dead right now -- just take this from the configured
347        // vm heap size, and assume it is in megabytes and thus ends with "m".
348        String vmHeapSize = SystemProperties.get("dalvik.vm.heapgrowthlimit", "");
349        if (vmHeapSize != null && !"".equals(vmHeapSize)) {
350            return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1));
351        }
352        return staticGetLargeMemoryClass();
353    }
354
355    /**
356     * Return the approximate per-application memory class of the current
357     * device when an application is running with a large heap.  This is the
358     * space available for memory-intensive applications; most applications
359     * should not need this amount of memory, and should instead stay with the
360     * {@link #getMemoryClass()} limit.  The returned value is in megabytes.
361     * This may be the same size as {@link #getMemoryClass()} on memory
362     * constrained devices, or it may be significantly larger on devices with
363     * a large amount of available RAM.
364     *
365     * <p>The is the size of the application's Dalvik heap if it has
366     * specified <code>android:largeHeap="true"</code> in its manifest.
367     */
368    public int getLargeMemoryClass() {
369        return staticGetLargeMemoryClass();
370    }
371
372    /** @hide */
373    static public int staticGetLargeMemoryClass() {
374        // Really brain dead right now -- just take this from the configured
375        // vm heap size, and assume it is in megabytes and thus ends with "m".
376        String vmHeapSize = SystemProperties.get("dalvik.vm.heapsize", "16m");
377        return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1));
378    }
379
380    /**
381     * Used by persistent processes to determine if they are running on a
382     * higher-end device so should be okay using hardware drawing acceleration
383     * (which tends to consume a lot more RAM).
384     * @hide
385     */
386    static public boolean isHighEndGfx() {
387        MemInfoReader reader = new MemInfoReader();
388        reader.readMemInfo();
389        if (reader.getTotalSize() >= (512*1024*1024)) {
390            // If the device has at least 512MB RAM available to the kernel,
391            // we can afford the overhead of graphics acceleration.
392            return true;
393        }
394
395        Display display = DisplayManagerGlobal.getInstance().getRealDisplay(
396                Display.DEFAULT_DISPLAY);
397        Point p = new Point();
398        display.getRealSize(p);
399        int pixels = p.x * p.y;
400        if (pixels >= (1024*600)) {
401            // If this is a sufficiently large screen, then there are enough
402            // pixels on it that we'd really like to use hw drawing.
403            return true;
404        }
405        return false;
406    }
407
408    /**
409     * Use to decide whether the running device can be considered a "large
410     * RAM" device.  Exactly what memory limit large RAM is will vary, but
411     * it essentially means there is plenty of RAM to have lots of background
412     * processes running under decent loads.
413     * @hide
414     */
415    static public boolean isLargeRAM() {
416        MemInfoReader reader = new MemInfoReader();
417        reader.readMemInfo();
418        if (reader.getTotalSize() >= (640*1024*1024)) {
419            // Currently 640MB RAM available to the kernel is the point at
420            // which we have plenty of RAM to spare.
421            return true;
422        }
423        return false;
424    }
425
426    /**
427     * Information you can retrieve about tasks that the user has most recently
428     * started or visited.
429     */
430    public static class RecentTaskInfo implements Parcelable {
431        /**
432         * If this task is currently running, this is the identifier for it.
433         * If it is not running, this will be -1.
434         */
435        public int id;
436
437        /**
438         * The true identifier of this task, valid even if it is not running.
439         */
440        public int persistentId;
441
442        /**
443         * The original Intent used to launch the task.  You can use this
444         * Intent to re-launch the task (if it is no longer running) or bring
445         * the current task to the front.
446         */
447        public Intent baseIntent;
448
449        /**
450         * If this task was started from an alias, this is the actual
451         * activity component that was initially started; the component of
452         * the baseIntent in this case is the name of the actual activity
453         * implementation that the alias referred to.  Otherwise, this is null.
454         */
455        public ComponentName origActivity;
456
457        /**
458         * Description of the task's last state.
459         */
460        public CharSequence description;
461
462        /**
463         * The id of the ActivityStack this Task was on most recently.
464         */
465        public int stackId;
466
467        public RecentTaskInfo() {
468        }
469
470        @Override
471        public int describeContents() {
472            return 0;
473        }
474
475        @Override
476        public void writeToParcel(Parcel dest, int flags) {
477            dest.writeInt(id);
478            dest.writeInt(persistentId);
479            if (baseIntent != null) {
480                dest.writeInt(1);
481                baseIntent.writeToParcel(dest, 0);
482            } else {
483                dest.writeInt(0);
484            }
485            ComponentName.writeToParcel(origActivity, dest);
486            TextUtils.writeToParcel(description, dest,
487                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
488            dest.writeInt(stackId);
489        }
490
491        public void readFromParcel(Parcel source) {
492            id = source.readInt();
493            persistentId = source.readInt();
494            if (source.readInt() != 0) {
495                baseIntent = Intent.CREATOR.createFromParcel(source);
496            } else {
497                baseIntent = null;
498            }
499            origActivity = ComponentName.readFromParcel(source);
500            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
501            stackId = source.readInt();
502        }
503
504        public static final Creator<RecentTaskInfo> CREATOR
505                = new Creator<RecentTaskInfo>() {
506            public RecentTaskInfo createFromParcel(Parcel source) {
507                return new RecentTaskInfo(source);
508            }
509            public RecentTaskInfo[] newArray(int size) {
510                return new RecentTaskInfo[size];
511            }
512        };
513
514        private RecentTaskInfo(Parcel source) {
515            readFromParcel(source);
516        }
517    }
518
519    /**
520     * Flag for use with {@link #getRecentTasks}: return all tasks, even those
521     * that have set their
522     * {@link android.content.Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag.
523     */
524    public static final int RECENT_WITH_EXCLUDED = 0x0001;
525
526    /**
527     * Provides a list that does not contain any
528     * recent tasks that currently are not available to the user.
529     */
530    public static final int RECENT_IGNORE_UNAVAILABLE = 0x0002;
531
532    /**
533     * Return a list of the tasks that the user has recently launched, with
534     * the most recent being first and older ones after in order.
535     *
536     * <p><b>Note: this method is only intended for debugging and presenting
537     * task management user interfaces</b>.  This should never be used for
538     * core logic in an application, such as deciding between different
539     * behaviors based on the information found here.  Such uses are
540     * <em>not</em> supported, and will likely break in the future.  For
541     * example, if multiple applications can be actively running at the
542     * same time, assumptions made about the meaning of the data here for
543     * purposes of control flow will be incorrect.</p>
544     *
545     * @param maxNum The maximum number of entries to return in the list.  The
546     * actual number returned may be smaller, depending on how many tasks the
547     * user has started and the maximum number the system can remember.
548     * @param flags Information about what to return.  May be any combination
549     * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
550     *
551     * @return Returns a list of RecentTaskInfo records describing each of
552     * the recent tasks.
553     *
554     * @throws SecurityException Throws SecurityException if the caller does
555     * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
556     */
557    public List<RecentTaskInfo> getRecentTasks(int maxNum, int flags)
558            throws SecurityException {
559        try {
560            return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
561                    flags, UserHandle.myUserId());
562        } catch (RemoteException e) {
563            // System dead, we will be dead too soon!
564            return null;
565        }
566    }
567
568    /**
569     * Same as {@link #getRecentTasks(int, int)} but returns the recent tasks for a
570     * specific user. It requires holding
571     * the {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
572     * @param maxNum The maximum number of entries to return in the list.  The
573     * actual number returned may be smaller, depending on how many tasks the
574     * user has started and the maximum number the system can remember.
575     * @param flags Information about what to return.  May be any combination
576     * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
577     *
578     * @return Returns a list of RecentTaskInfo records describing each of
579     * the recent tasks.
580     *
581     * @throws SecurityException Throws SecurityException if the caller does
582     * not hold the {@link android.Manifest.permission#GET_TASKS} or the
583     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permissions.
584     * @hide
585     */
586    public List<RecentTaskInfo> getRecentTasksForUser(int maxNum, int flags, int userId)
587            throws SecurityException {
588        try {
589            return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
590                    flags, userId);
591        } catch (RemoteException e) {
592            // System dead, we will be dead too soon!
593            return null;
594        }
595    }
596
597    /**
598     * Information you can retrieve about a particular task that is currently
599     * "running" in the system.  Note that a running task does not mean the
600     * given task actually has a process it is actively running in; it simply
601     * means that the user has gone to it and never closed it, but currently
602     * the system may have killed its process and is only holding on to its
603     * last state in order to restart it when the user returns.
604     */
605    public static class RunningTaskInfo implements Parcelable {
606        /**
607         * A unique identifier for this task.
608         */
609        public int id;
610
611        /**
612         * The component launched as the first activity in the task.  This can
613         * be considered the "application" of this task.
614         */
615        public ComponentName baseActivity;
616
617        /**
618         * The activity component at the top of the history stack of the task.
619         * This is what the user is currently doing.
620         */
621        public ComponentName topActivity;
622
623        /**
624         * Thumbnail representation of the task's current state.  Currently
625         * always null.
626         */
627        public Bitmap thumbnail;
628
629        /**
630         * Description of the task's current state.
631         */
632        public CharSequence description;
633
634        /**
635         * Number of activities in this task.
636         */
637        public int numActivities;
638
639        /**
640         * Number of activities that are currently running (not stopped
641         * and persisted) in this task.
642         */
643        public int numRunning;
644
645        public RunningTaskInfo() {
646        }
647
648        public int describeContents() {
649            return 0;
650        }
651
652        public void writeToParcel(Parcel dest, int flags) {
653            dest.writeInt(id);
654            ComponentName.writeToParcel(baseActivity, dest);
655            ComponentName.writeToParcel(topActivity, dest);
656            if (thumbnail != null) {
657                dest.writeInt(1);
658                thumbnail.writeToParcel(dest, 0);
659            } else {
660                dest.writeInt(0);
661            }
662            TextUtils.writeToParcel(description, dest,
663                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
664            dest.writeInt(numActivities);
665            dest.writeInt(numRunning);
666        }
667
668        public void readFromParcel(Parcel source) {
669            id = source.readInt();
670            baseActivity = ComponentName.readFromParcel(source);
671            topActivity = ComponentName.readFromParcel(source);
672            if (source.readInt() != 0) {
673                thumbnail = Bitmap.CREATOR.createFromParcel(source);
674            } else {
675                thumbnail = null;
676            }
677            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
678            numActivities = source.readInt();
679            numRunning = source.readInt();
680        }
681
682        public static final Creator<RunningTaskInfo> CREATOR = new Creator<RunningTaskInfo>() {
683            public RunningTaskInfo createFromParcel(Parcel source) {
684                return new RunningTaskInfo(source);
685            }
686            public RunningTaskInfo[] newArray(int size) {
687                return new RunningTaskInfo[size];
688            }
689        };
690
691        private RunningTaskInfo(Parcel source) {
692            readFromParcel(source);
693        }
694    }
695
696    /**
697     * Return a list of the tasks that are currently running, with
698     * the most recent being first and older ones after in order.  Note that
699     * "running" does not mean any of the task's code is currently loaded or
700     * activity -- the task may have been frozen by the system, so that it
701     * can be restarted in its previous state when next brought to the
702     * foreground.
703     *
704     * @param maxNum The maximum number of entries to return in the list.  The
705     * actual number returned may be smaller, depending on how many tasks the
706     * user has started.
707     *
708     * @param flags Optional flags
709     * @param receiver Optional receiver for delayed thumbnails
710     *
711     * @return Returns a list of RunningTaskInfo records describing each of
712     * the running tasks.
713     *
714     * Some thumbnails may not be available at the time of this call. The optional
715     * receiver may be used to receive those thumbnails.
716     *
717     * @throws SecurityException Throws SecurityException if the caller does
718     * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
719     *
720     * @hide
721     */
722    public List<RunningTaskInfo> getRunningTasks(int maxNum, int flags, IThumbnailReceiver receiver)
723            throws SecurityException {
724        try {
725            return ActivityManagerNative.getDefault().getTasks(maxNum, flags, receiver);
726        } catch (RemoteException e) {
727            // System dead, we will be dead too soon!
728            return null;
729        }
730    }
731
732    /**
733     * Return a list of the tasks that are currently running, with
734     * the most recent being first and older ones after in order.  Note that
735     * "running" does not mean any of the task's code is currently loaded or
736     * activity -- the task may have been frozen by the system, so that it
737     * can be restarted in its previous state when next brought to the
738     * foreground.
739     *
740     * <p><b>Note: this method is only intended for debugging and presenting
741     * task management user interfaces</b>.  This should never be used for
742     * core logic in an application, such as deciding between different
743     * behaviors based on the information found here.  Such uses are
744     * <em>not</em> supported, and will likely break in the future.  For
745     * example, if multiple applications can be actively running at the
746     * same time, assumptions made about the meaning of the data here for
747     * purposes of control flow will be incorrect.</p>
748     *
749     * @param maxNum The maximum number of entries to return in the list.  The
750     * actual number returned may be smaller, depending on how many tasks the
751     * user has started.
752     *
753     * @return Returns a list of RunningTaskInfo records describing each of
754     * the running tasks.
755     *
756     * @throws SecurityException Throws SecurityException if the caller does
757     * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
758     */
759    public List<RunningTaskInfo> getRunningTasks(int maxNum)
760            throws SecurityException {
761        return getRunningTasks(maxNum, 0, null);
762    }
763
764    /**
765     * Remove some end of a task's activity stack that is not part of
766     * the main application.  The selected activities will be finished, so
767     * they are no longer part of the main task.
768     *
769     * @param taskId The identifier of the task.
770     * @param subTaskIndex The number of the sub-task; this corresponds
771     * to the index of the thumbnail returned by {@link #getTaskThumbnails(int)}.
772     * @return Returns true if the sub-task was found and was removed.
773     *
774     * @hide
775     */
776    public boolean removeSubTask(int taskId, int subTaskIndex)
777            throws SecurityException {
778        try {
779            return ActivityManagerNative.getDefault().removeSubTask(taskId, subTaskIndex);
780        } catch (RemoteException e) {
781            // System dead, we will be dead too soon!
782            return false;
783        }
784    }
785
786    /**
787     * If set, the process of the root activity of the task will be killed
788     * as part of removing the task.
789     * @hide
790     */
791    public static final int REMOVE_TASK_KILL_PROCESS = 0x0001;
792
793    /**
794     * Completely remove the given task.
795     *
796     * @param taskId Identifier of the task to be removed.
797     * @param flags Additional operational flags.  May be 0 or
798     * {@link #REMOVE_TASK_KILL_PROCESS}.
799     * @return Returns true if the given task was found and removed.
800     *
801     * @hide
802     */
803    public boolean removeTask(int taskId, int flags)
804            throws SecurityException {
805        try {
806            return ActivityManagerNative.getDefault().removeTask(taskId, flags);
807        } catch (RemoteException e) {
808            // System dead, we will be dead too soon!
809            return false;
810        }
811    }
812
813    /** @hide */
814    public static class TaskThumbnails implements Parcelable {
815        public Bitmap mainThumbnail;
816
817        public int numSubThumbbails;
818
819        /** @hide */
820        public IThumbnailRetriever retriever;
821
822        public TaskThumbnails() {
823        }
824
825        public Bitmap getSubThumbnail(int index) {
826            try {
827                return retriever.getThumbnail(index);
828            } catch (RemoteException e) {
829                return null;
830            }
831        }
832
833        public int describeContents() {
834            return 0;
835        }
836
837        public void writeToParcel(Parcel dest, int flags) {
838            if (mainThumbnail != null) {
839                dest.writeInt(1);
840                mainThumbnail.writeToParcel(dest, 0);
841            } else {
842                dest.writeInt(0);
843            }
844            dest.writeInt(numSubThumbbails);
845            dest.writeStrongInterface(retriever);
846        }
847
848        public void readFromParcel(Parcel source) {
849            if (source.readInt() != 0) {
850                mainThumbnail = Bitmap.CREATOR.createFromParcel(source);
851            } else {
852                mainThumbnail = null;
853            }
854            numSubThumbbails = source.readInt();
855            retriever = IThumbnailRetriever.Stub.asInterface(source.readStrongBinder());
856        }
857
858        public static final Creator<TaskThumbnails> CREATOR = new Creator<TaskThumbnails>() {
859            public TaskThumbnails createFromParcel(Parcel source) {
860                return new TaskThumbnails(source);
861            }
862            public TaskThumbnails[] newArray(int size) {
863                return new TaskThumbnails[size];
864            }
865        };
866
867        private TaskThumbnails(Parcel source) {
868            readFromParcel(source);
869        }
870    }
871
872    /** @hide */
873    public TaskThumbnails getTaskThumbnails(int id) throws SecurityException {
874        try {
875            return ActivityManagerNative.getDefault().getTaskThumbnails(id);
876        } catch (RemoteException e) {
877            // System dead, we will be dead too soon!
878            return null;
879        }
880    }
881
882    /** @hide */
883    public Bitmap getTaskTopThumbnail(int id) throws SecurityException {
884        try {
885            return ActivityManagerNative.getDefault().getTaskTopThumbnail(id);
886        } catch (RemoteException e) {
887            // System dead, we will be dead too soon!
888            return null;
889        }
890    }
891
892    /**
893     * Flag for {@link #moveTaskToFront(int, int)}: also move the "home"
894     * activity along with the task, so it is positioned immediately behind
895     * the task.
896     */
897    public static final int MOVE_TASK_WITH_HOME = 0x00000001;
898
899    /**
900     * Flag for {@link #moveTaskToFront(int, int)}: don't count this as a
901     * user-instigated action, so the current activity will not receive a
902     * hint that the user is leaving.
903     */
904    public static final int MOVE_TASK_NO_USER_ACTION = 0x00000002;
905
906    /**
907     * Equivalent to calling {@link #moveTaskToFront(int, int, Bundle)}
908     * with a null options argument.
909     *
910     * @param taskId The identifier of the task to be moved, as found in
911     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
912     * @param flags Additional operational flags, 0 or more of
913     * {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}.
914     */
915    public void moveTaskToFront(int taskId, int flags) {
916        moveTaskToFront(taskId, flags, null);
917    }
918
919    /**
920     * Ask that the task associated with a given task ID be moved to the
921     * front of the stack, so it is now visible to the user.  Requires that
922     * the caller hold permission {@link android.Manifest.permission#REORDER_TASKS}
923     * or a SecurityException will be thrown.
924     *
925     * @param taskId The identifier of the task to be moved, as found in
926     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
927     * @param flags Additional operational flags, 0 or more of
928     * {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}.
929     * @param options Additional options for the operation, either null or
930     * as per {@link Context#startActivity(Intent, android.os.Bundle)
931     * Context.startActivity(Intent, Bundle)}.
932     */
933    public void moveTaskToFront(int taskId, int flags, Bundle options) {
934        try {
935            ActivityManagerNative.getDefault().moveTaskToFront(taskId, flags, options);
936        } catch (RemoteException e) {
937            // System dead, we will be dead too soon!
938        }
939    }
940
941    /**
942     * Information you can retrieve about a particular Service that is
943     * currently running in the system.
944     */
945    public static class RunningServiceInfo implements Parcelable {
946        /**
947         * The service component.
948         */
949        public ComponentName service;
950
951        /**
952         * If non-zero, this is the process the service is running in.
953         */
954        public int pid;
955
956        /**
957         * The UID that owns this service.
958         */
959        public int uid;
960
961        /**
962         * The name of the process this service runs in.
963         */
964        public String process;
965
966        /**
967         * Set to true if the service has asked to run as a foreground process.
968         */
969        public boolean foreground;
970
971        /**
972         * The time when the service was first made active, either by someone
973         * starting or binding to it.  This
974         * is in units of {@link android.os.SystemClock#elapsedRealtime()}.
975         */
976        public long activeSince;
977
978        /**
979         * Set to true if this service has been explicitly started.
980         */
981        public boolean started;
982
983        /**
984         * Number of clients connected to the service.
985         */
986        public int clientCount;
987
988        /**
989         * Number of times the service's process has crashed while the service
990         * is running.
991         */
992        public int crashCount;
993
994        /**
995         * The time when there was last activity in the service (either
996         * explicit requests to start it or clients binding to it).  This
997         * is in units of {@link android.os.SystemClock#uptimeMillis()}.
998         */
999        public long lastActivityTime;
1000
1001        /**
1002         * If non-zero, this service is not currently running, but scheduled to
1003         * restart at the given time.
1004         */
1005        public long restarting;
1006
1007        /**
1008         * Bit for {@link #flags}: set if this service has been
1009         * explicitly started.
1010         */
1011        public static final int FLAG_STARTED = 1<<0;
1012
1013        /**
1014         * Bit for {@link #flags}: set if the service has asked to
1015         * run as a foreground process.
1016         */
1017        public static final int FLAG_FOREGROUND = 1<<1;
1018
1019        /**
1020         * Bit for {@link #flags): set if the service is running in a
1021         * core system process.
1022         */
1023        public static final int FLAG_SYSTEM_PROCESS = 1<<2;
1024
1025        /**
1026         * Bit for {@link #flags): set if the service is running in a
1027         * persistent process.
1028         */
1029        public static final int FLAG_PERSISTENT_PROCESS = 1<<3;
1030
1031        /**
1032         * Running flags.
1033         */
1034        public int flags;
1035
1036        /**
1037         * For special services that are bound to by system code, this is
1038         * the package that holds the binding.
1039         */
1040        public String clientPackage;
1041
1042        /**
1043         * For special services that are bound to by system code, this is
1044         * a string resource providing a user-visible label for who the
1045         * client is.
1046         */
1047        public int clientLabel;
1048
1049        public RunningServiceInfo() {
1050        }
1051
1052        public int describeContents() {
1053            return 0;
1054        }
1055
1056        public void writeToParcel(Parcel dest, int flags) {
1057            ComponentName.writeToParcel(service, dest);
1058            dest.writeInt(pid);
1059            dest.writeInt(uid);
1060            dest.writeString(process);
1061            dest.writeInt(foreground ? 1 : 0);
1062            dest.writeLong(activeSince);
1063            dest.writeInt(started ? 1 : 0);
1064            dest.writeInt(clientCount);
1065            dest.writeInt(crashCount);
1066            dest.writeLong(lastActivityTime);
1067            dest.writeLong(restarting);
1068            dest.writeInt(this.flags);
1069            dest.writeString(clientPackage);
1070            dest.writeInt(clientLabel);
1071        }
1072
1073        public void readFromParcel(Parcel source) {
1074            service = ComponentName.readFromParcel(source);
1075            pid = source.readInt();
1076            uid = source.readInt();
1077            process = source.readString();
1078            foreground = source.readInt() != 0;
1079            activeSince = source.readLong();
1080            started = source.readInt() != 0;
1081            clientCount = source.readInt();
1082            crashCount = source.readInt();
1083            lastActivityTime = source.readLong();
1084            restarting = source.readLong();
1085            flags = source.readInt();
1086            clientPackage = source.readString();
1087            clientLabel = source.readInt();
1088        }
1089
1090        public static final Creator<RunningServiceInfo> CREATOR = new Creator<RunningServiceInfo>() {
1091            public RunningServiceInfo createFromParcel(Parcel source) {
1092                return new RunningServiceInfo(source);
1093            }
1094            public RunningServiceInfo[] newArray(int size) {
1095                return new RunningServiceInfo[size];
1096            }
1097        };
1098
1099        private RunningServiceInfo(Parcel source) {
1100            readFromParcel(source);
1101        }
1102    }
1103
1104    /**
1105     * Return a list of the services that are currently running.
1106     *
1107     * <p><b>Note: this method is only intended for debugging or implementing
1108     * service management type user interfaces.</b></p>
1109     *
1110     * @param maxNum The maximum number of entries to return in the list.  The
1111     * actual number returned may be smaller, depending on how many services
1112     * are running.
1113     *
1114     * @return Returns a list of RunningServiceInfo records describing each of
1115     * the running tasks.
1116     */
1117    public List<RunningServiceInfo> getRunningServices(int maxNum)
1118            throws SecurityException {
1119        try {
1120            return ActivityManagerNative.getDefault()
1121                    .getServices(maxNum, 0);
1122        } catch (RemoteException e) {
1123            // System dead, we will be dead too soon!
1124            return null;
1125        }
1126    }
1127
1128    /**
1129     * Returns a PendingIntent you can start to show a control panel for the
1130     * given running service.  If the service does not have a control panel,
1131     * null is returned.
1132     */
1133    public PendingIntent getRunningServiceControlPanel(ComponentName service)
1134            throws SecurityException {
1135        try {
1136            return ActivityManagerNative.getDefault()
1137                    .getRunningServiceControlPanel(service);
1138        } catch (RemoteException e) {
1139            // System dead, we will be dead too soon!
1140            return null;
1141        }
1142    }
1143
1144    /**
1145     * Information you can retrieve about the available memory through
1146     * {@link ActivityManager#getMemoryInfo}.
1147     */
1148    public static class MemoryInfo implements Parcelable {
1149        /**
1150         * The available memory on the system.  This number should not
1151         * be considered absolute: due to the nature of the kernel, a significant
1152         * portion of this memory is actually in use and needed for the overall
1153         * system to run well.
1154         */
1155        public long availMem;
1156
1157        /**
1158         * The total memory accessible by the kernel.  This is basically the
1159         * RAM size of the device, not including below-kernel fixed allocations
1160         * like DMA buffers, RAM for the baseband CPU, etc.
1161         */
1162        public long totalMem;
1163
1164        /**
1165         * The threshold of {@link #availMem} at which we consider memory to be
1166         * low and start killing background services and other non-extraneous
1167         * processes.
1168         */
1169        public long threshold;
1170
1171        /**
1172         * Set to true if the system considers itself to currently be in a low
1173         * memory situation.
1174         */
1175        public boolean lowMemory;
1176
1177        /** @hide */
1178        public long hiddenAppThreshold;
1179        /** @hide */
1180        public long secondaryServerThreshold;
1181        /** @hide */
1182        public long visibleAppThreshold;
1183        /** @hide */
1184        public long foregroundAppThreshold;
1185
1186        public MemoryInfo() {
1187        }
1188
1189        public int describeContents() {
1190            return 0;
1191        }
1192
1193        public void writeToParcel(Parcel dest, int flags) {
1194            dest.writeLong(availMem);
1195            dest.writeLong(totalMem);
1196            dest.writeLong(threshold);
1197            dest.writeInt(lowMemory ? 1 : 0);
1198            dest.writeLong(hiddenAppThreshold);
1199            dest.writeLong(secondaryServerThreshold);
1200            dest.writeLong(visibleAppThreshold);
1201            dest.writeLong(foregroundAppThreshold);
1202        }
1203
1204        public void readFromParcel(Parcel source) {
1205            availMem = source.readLong();
1206            totalMem = source.readLong();
1207            threshold = source.readLong();
1208            lowMemory = source.readInt() != 0;
1209            hiddenAppThreshold = source.readLong();
1210            secondaryServerThreshold = source.readLong();
1211            visibleAppThreshold = source.readLong();
1212            foregroundAppThreshold = source.readLong();
1213        }
1214
1215        public static final Creator<MemoryInfo> CREATOR
1216                = new Creator<MemoryInfo>() {
1217            public MemoryInfo createFromParcel(Parcel source) {
1218                return new MemoryInfo(source);
1219            }
1220            public MemoryInfo[] newArray(int size) {
1221                return new MemoryInfo[size];
1222            }
1223        };
1224
1225        private MemoryInfo(Parcel source) {
1226            readFromParcel(source);
1227        }
1228    }
1229
1230    /**
1231     * Return general information about the memory state of the system.  This
1232     * can be used to help decide how to manage your own memory, though note
1233     * that polling is not recommended and
1234     * {@link android.content.ComponentCallbacks2#onTrimMemory(int)
1235     * ComponentCallbacks2.onTrimMemory(int)} is the preferred way to do this.
1236     * Also see {@link #getMyMemoryState} for how to retrieve the current trim
1237     * level of your process as needed, which gives a better hint for how to
1238     * manage its memory.
1239     */
1240    public void getMemoryInfo(MemoryInfo outInfo) {
1241        try {
1242            ActivityManagerNative.getDefault().getMemoryInfo(outInfo);
1243        } catch (RemoteException e) {
1244        }
1245    }
1246
1247    /**
1248     * Information you can retrieve about the WindowManager StackBox hierarchy.
1249     * @hide
1250     */
1251    public static class StackBoxInfo implements Parcelable {
1252        public int stackBoxId;
1253        public float weight;
1254        public boolean vertical;
1255        public Rect bounds;
1256        public StackBoxInfo[] children;
1257        public int stackId;
1258        public StackInfo stack;
1259
1260        @Override
1261        public int describeContents() {
1262            return 0;
1263        }
1264
1265        @Override
1266        public void writeToParcel(Parcel dest, int flags) {
1267            dest.writeInt(stackBoxId);
1268            dest.writeFloat(weight);
1269            dest.writeInt(vertical ? 1 : 0);
1270            bounds.writeToParcel(dest, flags);
1271            dest.writeInt(stackId);
1272            if (children != null) {
1273                children[0].writeToParcel(dest, flags);
1274                children[1].writeToParcel(dest, flags);
1275            } else {
1276                stack.writeToParcel(dest, flags);
1277            }
1278        }
1279
1280        public void readFromParcel(Parcel source) {
1281            stackBoxId = source.readInt();
1282            weight = source.readFloat();
1283            vertical = source.readInt() == 1;
1284            bounds = Rect.CREATOR.createFromParcel(source);
1285            stackId = source.readInt();
1286            if (stackId == -1) {
1287                children = new StackBoxInfo[2];
1288                children[0] = StackBoxInfo.CREATOR.createFromParcel(source);
1289                children[1] = StackBoxInfo.CREATOR.createFromParcel(source);
1290            } else {
1291                stack = StackInfo.CREATOR.createFromParcel(source);
1292            }
1293        }
1294
1295        public static final Creator<StackBoxInfo> CREATOR =
1296                new Creator<ActivityManager.StackBoxInfo>() {
1297
1298            @Override
1299            public StackBoxInfo createFromParcel(Parcel source) {
1300                return new StackBoxInfo(source);
1301            }
1302
1303            @Override
1304            public StackBoxInfo[] newArray(int size) {
1305                return new StackBoxInfo[size];
1306            }
1307        };
1308
1309        public StackBoxInfo() {
1310        }
1311
1312        public StackBoxInfo(Parcel source) {
1313            readFromParcel(source);
1314        }
1315
1316        public String toString(String prefix) {
1317            StringBuilder sb = new StringBuilder(256);
1318            sb.append(prefix); sb.append("Box id=" + stackBoxId); sb.append(" weight=" + weight);
1319            sb.append(" vertical=" + vertical); sb.append(" bounds=" + bounds.toShortString());
1320            sb.append("\n");
1321            if (children != null) {
1322                sb.append(prefix); sb.append("First child=\n");
1323                sb.append(children[0].toString(prefix + "  "));
1324                sb.append(prefix); sb.append("Second child=\n");
1325                sb.append(children[1].toString(prefix + "  "));
1326            } else {
1327                sb.append(prefix); sb.append("Stack=\n");
1328                sb.append(stack.toString(prefix + "  "));
1329            }
1330            return sb.toString();
1331        }
1332
1333        @Override
1334        public String toString() {
1335            return toString("");
1336        }
1337    }
1338
1339    /**
1340     * Information you can retrieve about an ActivityStack in the system.
1341     * @hide
1342     */
1343    public static class StackInfo implements Parcelable {
1344        public int stackId;
1345        public Rect bounds;
1346        public int[] taskIds;
1347        public String[] taskNames;
1348
1349        @Override
1350        public int describeContents() {
1351            return 0;
1352        }
1353
1354        @Override
1355        public void writeToParcel(Parcel dest, int flags) {
1356            dest.writeInt(stackId);
1357            dest.writeInt(bounds.left);
1358            dest.writeInt(bounds.top);
1359            dest.writeInt(bounds.right);
1360            dest.writeInt(bounds.bottom);
1361            dest.writeIntArray(taskIds);
1362            dest.writeStringArray(taskNames);
1363        }
1364
1365        public void readFromParcel(Parcel source) {
1366            stackId = source.readInt();
1367            bounds = new Rect(
1368                    source.readInt(), source.readInt(), source.readInt(), source.readInt());
1369            taskIds = source.createIntArray();
1370            taskNames = source.createStringArray();
1371        }
1372
1373        public static final Creator<StackInfo> CREATOR = new Creator<StackInfo>() {
1374            @Override
1375            public StackInfo createFromParcel(Parcel source) {
1376                return new StackInfo(source);
1377            }
1378            @Override
1379            public StackInfo[] newArray(int size) {
1380                return new StackInfo[size];
1381            }
1382        };
1383
1384        public StackInfo() {
1385        }
1386
1387        private StackInfo(Parcel source) {
1388            readFromParcel(source);
1389        }
1390
1391        public String toString(String prefix) {
1392            StringBuilder sb = new StringBuilder(256);
1393            sb.append(prefix); sb.append("Stack id="); sb.append(stackId);
1394                    sb.append(" bounds="); sb.append(bounds.toShortString()); sb.append("\n");
1395            prefix = prefix + "  ";
1396            for (int i = 0; i < taskIds.length; ++i) {
1397                sb.append(prefix); sb.append("taskId="); sb.append(taskIds[i]);
1398                        sb.append(": "); sb.append(taskNames[i]); sb.append("\n");
1399            }
1400            return sb.toString();
1401        }
1402
1403        @Override
1404        public String toString() {
1405            return toString("");
1406        }
1407    }
1408
1409    /**
1410     * @hide
1411     */
1412    public boolean clearApplicationUserData(String packageName, IPackageDataObserver observer) {
1413        try {
1414            return ActivityManagerNative.getDefault().clearApplicationUserData(packageName,
1415                    observer, UserHandle.myUserId());
1416        } catch (RemoteException e) {
1417            return false;
1418        }
1419    }
1420
1421    /**
1422     * Information you can retrieve about any processes that are in an error condition.
1423     */
1424    public static class ProcessErrorStateInfo implements Parcelable {
1425        /**
1426         * Condition codes
1427         */
1428        public static final int NO_ERROR = 0;
1429        public static final int CRASHED = 1;
1430        public static final int NOT_RESPONDING = 2;
1431
1432        /**
1433         * The condition that the process is in.
1434         */
1435        public int condition;
1436
1437        /**
1438         * The process name in which the crash or error occurred.
1439         */
1440        public String processName;
1441
1442        /**
1443         * The pid of this process; 0 if none
1444         */
1445        public int pid;
1446
1447        /**
1448         * The kernel user-ID that has been assigned to this process;
1449         * currently this is not a unique ID (multiple applications can have
1450         * the same uid).
1451         */
1452        public int uid;
1453
1454        /**
1455         * The activity name associated with the error, if known.  May be null.
1456         */
1457        public String tag;
1458
1459        /**
1460         * A short message describing the error condition.
1461         */
1462        public String shortMsg;
1463
1464        /**
1465         * A long message describing the error condition.
1466         */
1467        public String longMsg;
1468
1469        /**
1470         * The stack trace where the error originated.  May be null.
1471         */
1472        public String stackTrace;
1473
1474        /**
1475         * to be deprecated: This value will always be null.
1476         */
1477        public byte[] crashData = null;
1478
1479        public ProcessErrorStateInfo() {
1480        }
1481
1482        @Override
1483        public int describeContents() {
1484            return 0;
1485        }
1486
1487        @Override
1488        public void writeToParcel(Parcel dest, int flags) {
1489            dest.writeInt(condition);
1490            dest.writeString(processName);
1491            dest.writeInt(pid);
1492            dest.writeInt(uid);
1493            dest.writeString(tag);
1494            dest.writeString(shortMsg);
1495            dest.writeString(longMsg);
1496            dest.writeString(stackTrace);
1497        }
1498
1499        public void readFromParcel(Parcel source) {
1500            condition = source.readInt();
1501            processName = source.readString();
1502            pid = source.readInt();
1503            uid = source.readInt();
1504            tag = source.readString();
1505            shortMsg = source.readString();
1506            longMsg = source.readString();
1507            stackTrace = source.readString();
1508        }
1509
1510        public static final Creator<ProcessErrorStateInfo> CREATOR =
1511                new Creator<ProcessErrorStateInfo>() {
1512            public ProcessErrorStateInfo createFromParcel(Parcel source) {
1513                return new ProcessErrorStateInfo(source);
1514            }
1515            public ProcessErrorStateInfo[] newArray(int size) {
1516                return new ProcessErrorStateInfo[size];
1517            }
1518        };
1519
1520        private ProcessErrorStateInfo(Parcel source) {
1521            readFromParcel(source);
1522        }
1523    }
1524
1525    /**
1526     * Returns a list of any processes that are currently in an error condition.  The result
1527     * will be null if all processes are running properly at this time.
1528     *
1529     * @return Returns a list of ProcessErrorStateInfo records, or null if there are no
1530     * current error conditions (it will not return an empty list).  This list ordering is not
1531     * specified.
1532     */
1533    public List<ProcessErrorStateInfo> getProcessesInErrorState() {
1534        try {
1535            return ActivityManagerNative.getDefault().getProcessesInErrorState();
1536        } catch (RemoteException e) {
1537            return null;
1538        }
1539    }
1540
1541    /**
1542     * Information you can retrieve about a running process.
1543     */
1544    public static class RunningAppProcessInfo implements Parcelable {
1545        /**
1546         * The name of the process that this object is associated with
1547         */
1548        public String processName;
1549
1550        /**
1551         * The pid of this process; 0 if none
1552         */
1553        public int pid;
1554
1555        /**
1556         * The user id of this process.
1557         */
1558        public int uid;
1559
1560        /**
1561         * All packages that have been loaded into the process.
1562         */
1563        public String pkgList[];
1564
1565        /**
1566         * Constant for {@link #flags}: this is an app that is unable to
1567         * correctly save its state when going to the background,
1568         * so it can not be killed while in the background.
1569         * @hide
1570         */
1571        public static final int FLAG_CANT_SAVE_STATE = 1<<0;
1572
1573        /**
1574         * Constant for {@link #flags}: this process is associated with a
1575         * persistent system app.
1576         * @hide
1577         */
1578        public static final int FLAG_PERSISTENT = 1<<1;
1579
1580        /**
1581         * Constant for {@link #flags}: this process is associated with a
1582         * persistent system app.
1583         * @hide
1584         */
1585        public static final int FLAG_HAS_ACTIVITIES = 1<<2;
1586
1587        /**
1588         * Flags of information.  May be any of
1589         * {@link #FLAG_CANT_SAVE_STATE}.
1590         * @hide
1591         */
1592        public int flags;
1593
1594        /**
1595         * Last memory trim level reported to the process: corresponds to
1596         * the values supplied to {@link android.content.ComponentCallbacks2#onTrimMemory(int)
1597         * ComponentCallbacks2.onTrimMemory(int)}.
1598         */
1599        public int lastTrimLevel;
1600
1601        /**
1602         * Constant for {@link #importance}: this is a persistent process.
1603         * Only used when reporting to process observers.
1604         * @hide
1605         */
1606        public static final int IMPORTANCE_PERSISTENT = 50;
1607
1608        /**
1609         * Constant for {@link #importance}: this process is running the
1610         * foreground UI.
1611         */
1612        public static final int IMPORTANCE_FOREGROUND = 100;
1613
1614        /**
1615         * Constant for {@link #importance}: this process is running something
1616         * that is actively visible to the user, though not in the immediate
1617         * foreground.
1618         */
1619        public static final int IMPORTANCE_VISIBLE = 200;
1620
1621        /**
1622         * Constant for {@link #importance}: this process is running something
1623         * that is considered to be actively perceptible to the user.  An
1624         * example would be an application performing background music playback.
1625         */
1626        public static final int IMPORTANCE_PERCEPTIBLE = 130;
1627
1628        /**
1629         * Constant for {@link #importance}: this process is running an
1630         * application that can not save its state, and thus can't be killed
1631         * while in the background.
1632         * @hide
1633         */
1634        public static final int IMPORTANCE_CANT_SAVE_STATE = 170;
1635
1636        /**
1637         * Constant for {@link #importance}: this process is contains services
1638         * that should remain running.
1639         */
1640        public static final int IMPORTANCE_SERVICE = 300;
1641
1642        /**
1643         * Constant for {@link #importance}: this process process contains
1644         * background code that is expendable.
1645         */
1646        public static final int IMPORTANCE_BACKGROUND = 400;
1647
1648        /**
1649         * Constant for {@link #importance}: this process is empty of any
1650         * actively running code.
1651         */
1652        public static final int IMPORTANCE_EMPTY = 500;
1653
1654        /**
1655         * The relative importance level that the system places on this
1656         * process.  May be one of {@link #IMPORTANCE_FOREGROUND},
1657         * {@link #IMPORTANCE_VISIBLE}, {@link #IMPORTANCE_SERVICE},
1658         * {@link #IMPORTANCE_BACKGROUND}, or {@link #IMPORTANCE_EMPTY}.  These
1659         * constants are numbered so that "more important" values are always
1660         * smaller than "less important" values.
1661         */
1662        public int importance;
1663
1664        /**
1665         * An additional ordering within a particular {@link #importance}
1666         * category, providing finer-grained information about the relative
1667         * utility of processes within a category.  This number means nothing
1668         * except that a smaller values are more recently used (and thus
1669         * more important).  Currently an LRU value is only maintained for
1670         * the {@link #IMPORTANCE_BACKGROUND} category, though others may
1671         * be maintained in the future.
1672         */
1673        public int lru;
1674
1675        /**
1676         * Constant for {@link #importanceReasonCode}: nothing special has
1677         * been specified for the reason for this level.
1678         */
1679        public static final int REASON_UNKNOWN = 0;
1680
1681        /**
1682         * Constant for {@link #importanceReasonCode}: one of the application's
1683         * content providers is being used by another process.  The pid of
1684         * the client process is in {@link #importanceReasonPid} and the
1685         * target provider in this process is in
1686         * {@link #importanceReasonComponent}.
1687         */
1688        public static final int REASON_PROVIDER_IN_USE = 1;
1689
1690        /**
1691         * Constant for {@link #importanceReasonCode}: one of the application's
1692         * content providers is being used by another process.  The pid of
1693         * the client process is in {@link #importanceReasonPid} and the
1694         * target provider in this process is in
1695         * {@link #importanceReasonComponent}.
1696         */
1697        public static final int REASON_SERVICE_IN_USE = 2;
1698
1699        /**
1700         * The reason for {@link #importance}, if any.
1701         */
1702        public int importanceReasonCode;
1703
1704        /**
1705         * For the specified values of {@link #importanceReasonCode}, this
1706         * is the process ID of the other process that is a client of this
1707         * process.  This will be 0 if no other process is using this one.
1708         */
1709        public int importanceReasonPid;
1710
1711        /**
1712         * For the specified values of {@link #importanceReasonCode}, this
1713         * is the name of the component that is being used in this process.
1714         */
1715        public ComponentName importanceReasonComponent;
1716
1717        /**
1718         * When {@link #importanceReasonPid} is non-0, this is the importance
1719         * of the other pid. @hide
1720         */
1721        public int importanceReasonImportance;
1722
1723        public RunningAppProcessInfo() {
1724            importance = IMPORTANCE_FOREGROUND;
1725            importanceReasonCode = REASON_UNKNOWN;
1726        }
1727
1728        public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) {
1729            processName = pProcessName;
1730            pid = pPid;
1731            pkgList = pArr;
1732        }
1733
1734        public int describeContents() {
1735            return 0;
1736        }
1737
1738        public void writeToParcel(Parcel dest, int flags) {
1739            dest.writeString(processName);
1740            dest.writeInt(pid);
1741            dest.writeInt(uid);
1742            dest.writeStringArray(pkgList);
1743            dest.writeInt(this.flags);
1744            dest.writeInt(lastTrimLevel);
1745            dest.writeInt(importance);
1746            dest.writeInt(lru);
1747            dest.writeInt(importanceReasonCode);
1748            dest.writeInt(importanceReasonPid);
1749            ComponentName.writeToParcel(importanceReasonComponent, dest);
1750            dest.writeInt(importanceReasonImportance);
1751        }
1752
1753        public void readFromParcel(Parcel source) {
1754            processName = source.readString();
1755            pid = source.readInt();
1756            uid = source.readInt();
1757            pkgList = source.readStringArray();
1758            flags = source.readInt();
1759            lastTrimLevel = source.readInt();
1760            importance = source.readInt();
1761            lru = source.readInt();
1762            importanceReasonCode = source.readInt();
1763            importanceReasonPid = source.readInt();
1764            importanceReasonComponent = ComponentName.readFromParcel(source);
1765            importanceReasonImportance = source.readInt();
1766        }
1767
1768        public static final Creator<RunningAppProcessInfo> CREATOR =
1769            new Creator<RunningAppProcessInfo>() {
1770            public RunningAppProcessInfo createFromParcel(Parcel source) {
1771                return new RunningAppProcessInfo(source);
1772            }
1773            public RunningAppProcessInfo[] newArray(int size) {
1774                return new RunningAppProcessInfo[size];
1775            }
1776        };
1777
1778        private RunningAppProcessInfo(Parcel source) {
1779            readFromParcel(source);
1780        }
1781    }
1782
1783    /**
1784     * Returns a list of application processes installed on external media
1785     * that are running on the device.
1786     *
1787     * <p><b>Note: this method is only intended for debugging or building
1788     * a user-facing process management UI.</b></p>
1789     *
1790     * @return Returns a list of ApplicationInfo records, or null if none
1791     * This list ordering is not specified.
1792     * @hide
1793     */
1794    public List<ApplicationInfo> getRunningExternalApplications() {
1795        try {
1796            return ActivityManagerNative.getDefault().getRunningExternalApplications();
1797        } catch (RemoteException e) {
1798            return null;
1799        }
1800    }
1801
1802    /**
1803     * Returns a list of application processes that are running on the device.
1804     *
1805     * <p><b>Note: this method is only intended for debugging or building
1806     * a user-facing process management UI.</b></p>
1807     *
1808     * @return Returns a list of RunningAppProcessInfo records, or null if there are no
1809     * running processes (it will not return an empty list).  This list ordering is not
1810     * specified.
1811     */
1812    public List<RunningAppProcessInfo> getRunningAppProcesses() {
1813        try {
1814            return ActivityManagerNative.getDefault().getRunningAppProcesses();
1815        } catch (RemoteException e) {
1816            return null;
1817        }
1818    }
1819
1820    /**
1821     * Return global memory state information for the calling process.  This
1822     * does not fill in all fields of the {@link RunningAppProcessInfo}.  The
1823     * only fields that will be filled in are
1824     * {@link RunningAppProcessInfo#pid},
1825     * {@link RunningAppProcessInfo#uid},
1826     * {@link RunningAppProcessInfo#lastTrimLevel},
1827     * {@link RunningAppProcessInfo#importance},
1828     * {@link RunningAppProcessInfo#lru}, and
1829     * {@link RunningAppProcessInfo#importanceReasonCode}.
1830     */
1831    static public void getMyMemoryState(RunningAppProcessInfo outState) {
1832        try {
1833            ActivityManagerNative.getDefault().getMyMemoryState(outState);
1834        } catch (RemoteException e) {
1835        }
1836    }
1837
1838    /**
1839     * Return information about the memory usage of one or more processes.
1840     *
1841     * <p><b>Note: this method is only intended for debugging or building
1842     * a user-facing process management UI.</b></p>
1843     *
1844     * @param pids The pids of the processes whose memory usage is to be
1845     * retrieved.
1846     * @return Returns an array of memory information, one for each
1847     * requested pid.
1848     */
1849    public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
1850        try {
1851            return ActivityManagerNative.getDefault().getProcessMemoryInfo(pids);
1852        } catch (RemoteException e) {
1853            return null;
1854        }
1855    }
1856
1857    /**
1858     * @deprecated This is now just a wrapper for
1859     * {@link #killBackgroundProcesses(String)}; the previous behavior here
1860     * is no longer available to applications because it allows them to
1861     * break other applications by removing their alarms, stopping their
1862     * services, etc.
1863     */
1864    @Deprecated
1865    public void restartPackage(String packageName) {
1866        killBackgroundProcesses(packageName);
1867    }
1868
1869    /**
1870     * Have the system immediately kill all background processes associated
1871     * with the given package.  This is the same as the kernel killing those
1872     * processes to reclaim memory; the system will take care of restarting
1873     * these processes in the future as needed.
1874     *
1875     * <p>You must hold the permission
1876     * {@link android.Manifest.permission#KILL_BACKGROUND_PROCESSES} to be able to
1877     * call this method.
1878     *
1879     * @param packageName The name of the package whose processes are to
1880     * be killed.
1881     */
1882    public void killBackgroundProcesses(String packageName) {
1883        try {
1884            ActivityManagerNative.getDefault().killBackgroundProcesses(packageName,
1885                    UserHandle.myUserId());
1886        } catch (RemoteException e) {
1887        }
1888    }
1889
1890    /**
1891     * Have the system perform a force stop of everything associated with
1892     * the given application package.  All processes that share its uid
1893     * will be killed, all services it has running stopped, all activities
1894     * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
1895     * broadcast will be sent, so that any of its registered alarms can
1896     * be stopped, notifications removed, etc.
1897     *
1898     * <p>You must hold the permission
1899     * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
1900     * call this method.
1901     *
1902     * @param packageName The name of the package to be stopped.
1903     *
1904     * @hide This is not available to third party applications due to
1905     * it allowing them to break other applications by stopping their
1906     * services, removing their alarms, etc.
1907     */
1908    public void forceStopPackage(String packageName) {
1909        try {
1910            ActivityManagerNative.getDefault().forceStopPackage(packageName,
1911                    UserHandle.myUserId());
1912        } catch (RemoteException e) {
1913        }
1914    }
1915
1916    /**
1917     * Get the device configuration attributes.
1918     */
1919    public ConfigurationInfo getDeviceConfigurationInfo() {
1920        try {
1921            return ActivityManagerNative.getDefault().getDeviceConfigurationInfo();
1922        } catch (RemoteException e) {
1923        }
1924        return null;
1925    }
1926
1927    /**
1928     * Get the preferred density of icons for the launcher. This is used when
1929     * custom drawables are created (e.g., for shortcuts).
1930     *
1931     * @return density in terms of DPI
1932     */
1933    public int getLauncherLargeIconDensity() {
1934        final Resources res = mContext.getResources();
1935        final int density = res.getDisplayMetrics().densityDpi;
1936        final int sw = res.getConfiguration().smallestScreenWidthDp;
1937
1938        if (sw < 600) {
1939            // Smaller than approx 7" tablets, use the regular icon size.
1940            return density;
1941        }
1942
1943        switch (density) {
1944            case DisplayMetrics.DENSITY_LOW:
1945                return DisplayMetrics.DENSITY_MEDIUM;
1946            case DisplayMetrics.DENSITY_MEDIUM:
1947                return DisplayMetrics.DENSITY_HIGH;
1948            case DisplayMetrics.DENSITY_TV:
1949                return DisplayMetrics.DENSITY_XHIGH;
1950            case DisplayMetrics.DENSITY_HIGH:
1951                return DisplayMetrics.DENSITY_XHIGH;
1952            case DisplayMetrics.DENSITY_XHIGH:
1953                return DisplayMetrics.DENSITY_XXHIGH;
1954            case DisplayMetrics.DENSITY_XXHIGH:
1955                return DisplayMetrics.DENSITY_XHIGH * 2;
1956            default:
1957                // The density is some abnormal value.  Return some other
1958                // abnormal value that is a reasonable scaling of it.
1959                return (int)((density*1.5f)+.5f);
1960        }
1961    }
1962
1963    /**
1964     * Get the preferred launcher icon size. This is used when custom drawables
1965     * are created (e.g., for shortcuts).
1966     *
1967     * @return dimensions of square icons in terms of pixels
1968     */
1969    public int getLauncherLargeIconSize() {
1970        final Resources res = mContext.getResources();
1971        final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size);
1972        final int sw = res.getConfiguration().smallestScreenWidthDp;
1973
1974        if (sw < 600) {
1975            // Smaller than approx 7" tablets, use the regular icon size.
1976            return size;
1977        }
1978
1979        final int density = res.getDisplayMetrics().densityDpi;
1980
1981        switch (density) {
1982            case DisplayMetrics.DENSITY_LOW:
1983                return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW;
1984            case DisplayMetrics.DENSITY_MEDIUM:
1985                return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM;
1986            case DisplayMetrics.DENSITY_TV:
1987                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
1988            case DisplayMetrics.DENSITY_HIGH:
1989                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
1990            case DisplayMetrics.DENSITY_XHIGH:
1991                return (size * DisplayMetrics.DENSITY_XXHIGH) / DisplayMetrics.DENSITY_XHIGH;
1992            case DisplayMetrics.DENSITY_XXHIGH:
1993                return (size * DisplayMetrics.DENSITY_XHIGH*2) / DisplayMetrics.DENSITY_XXHIGH;
1994            default:
1995                // The density is some abnormal value.  Return some other
1996                // abnormal value that is a reasonable scaling of it.
1997                return (int)((size*1.5f) + .5f);
1998        }
1999    }
2000
2001    /**
2002     * Returns "true" if the user interface is currently being messed with
2003     * by a monkey.
2004     */
2005    public static boolean isUserAMonkey() {
2006        try {
2007            return ActivityManagerNative.getDefault().isUserAMonkey();
2008        } catch (RemoteException e) {
2009        }
2010        return false;
2011    }
2012
2013    /**
2014     * Returns "true" if device is running in a test harness.
2015     */
2016    public static boolean isRunningInTestHarness() {
2017        return SystemProperties.getBoolean("ro.test_harness", false);
2018    }
2019
2020    /**
2021     * Returns the launch count of each installed package.
2022     *
2023     * @hide
2024     */
2025    public Map<String, Integer> getAllPackageLaunchCounts() {
2026        try {
2027            IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
2028                    ServiceManager.getService("usagestats"));
2029            if (usageStatsService == null) {
2030                return new HashMap<String, Integer>();
2031            }
2032
2033            PkgUsageStats[] allPkgUsageStats = usageStatsService.getAllPkgUsageStats();
2034            if (allPkgUsageStats == null) {
2035                return new HashMap<String, Integer>();
2036            }
2037
2038            Map<String, Integer> launchCounts = new HashMap<String, Integer>();
2039            for (PkgUsageStats pkgUsageStats : allPkgUsageStats) {
2040                launchCounts.put(pkgUsageStats.packageName, pkgUsageStats.launchCount);
2041            }
2042
2043            return launchCounts;
2044        } catch (RemoteException e) {
2045            Log.w(TAG, "Could not query launch counts", e);
2046            return new HashMap<String, Integer>();
2047        }
2048    }
2049
2050    /** @hide */
2051    public static int checkComponentPermission(String permission, int uid,
2052            int owningUid, boolean exported) {
2053        // Root, system server get to do everything.
2054        if (uid == 0 || uid == Process.SYSTEM_UID) {
2055            return PackageManager.PERMISSION_GRANTED;
2056        }
2057        // Isolated processes don't get any permissions.
2058        if (UserHandle.isIsolated(uid)) {
2059            return PackageManager.PERMISSION_DENIED;
2060        }
2061        // If there is a uid that owns whatever is being accessed, it has
2062        // blanket access to it regardless of the permissions it requires.
2063        if (owningUid >= 0 && UserHandle.isSameApp(uid, owningUid)) {
2064            return PackageManager.PERMISSION_GRANTED;
2065        }
2066        // If the target is not exported, then nobody else can get to it.
2067        if (!exported) {
2068            Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
2069            return PackageManager.PERMISSION_DENIED;
2070        }
2071        if (permission == null) {
2072            return PackageManager.PERMISSION_GRANTED;
2073        }
2074        try {
2075            return AppGlobals.getPackageManager()
2076                    .checkUidPermission(permission, uid);
2077        } catch (RemoteException e) {
2078            // Should never happen, but if it does... deny!
2079            Slog.e(TAG, "PackageManager is dead?!?", e);
2080        }
2081        return PackageManager.PERMISSION_DENIED;
2082    }
2083
2084    /** @hide */
2085    public static int checkUidPermission(String permission, int uid) {
2086        try {
2087            return AppGlobals.getPackageManager()
2088                    .checkUidPermission(permission, uid);
2089        } catch (RemoteException e) {
2090            // Should never happen, but if it does... deny!
2091            Slog.e(TAG, "PackageManager is dead?!?", e);
2092        }
2093        return PackageManager.PERMISSION_DENIED;
2094    }
2095
2096    /**
2097     * @hide
2098     * Helper for dealing with incoming user arguments to system service calls.
2099     * Takes care of checking permissions and converting USER_CURRENT to the
2100     * actual current user.
2101     *
2102     * @param callingPid The pid of the incoming call, as per Binder.getCallingPid().
2103     * @param callingUid The uid of the incoming call, as per Binder.getCallingUid().
2104     * @param userId The user id argument supplied by the caller -- this is the user
2105     * they want to run as.
2106     * @param allowAll If true, we will allow USER_ALL.  This means you must be prepared
2107     * to get a USER_ALL returned and deal with it correctly.  If false,
2108     * an exception will be thrown if USER_ALL is supplied.
2109     * @param requireFull If true, the caller must hold
2110     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} to be able to run as a
2111     * different user than their current process; otherwise they must hold
2112     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS}.
2113     * @param name Optional textual name of the incoming call; only for generating error messages.
2114     * @param callerPackage Optional package name of caller; only for error messages.
2115     *
2116     * @return Returns the user ID that the call should run as.  Will always be a concrete
2117     * user number, unless <var>allowAll</var> is true in which case it could also be
2118     * USER_ALL.
2119     */
2120    public static int handleIncomingUser(int callingPid, int callingUid, int userId,
2121            boolean allowAll, boolean requireFull, String name, String callerPackage) {
2122        if (UserHandle.getUserId(callingUid) == userId) {
2123            return userId;
2124        }
2125        try {
2126            return ActivityManagerNative.getDefault().handleIncomingUser(callingPid,
2127                    callingUid, userId, allowAll, requireFull, name, callerPackage);
2128        } catch (RemoteException e) {
2129            throw new SecurityException("Failed calling activity manager", e);
2130        }
2131    }
2132
2133    /** @hide */
2134    public static int getCurrentUser() {
2135        UserInfo ui;
2136        try {
2137            ui = ActivityManagerNative.getDefault().getCurrentUser();
2138            return ui != null ? ui.id : 0;
2139        } catch (RemoteException e) {
2140            return 0;
2141        }
2142    }
2143
2144    /**
2145     * Returns the usage statistics of each installed package.
2146     *
2147     * @hide
2148     */
2149    public PkgUsageStats[] getAllPackageUsageStats() {
2150        try {
2151            IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
2152                    ServiceManager.getService("usagestats"));
2153            if (usageStatsService != null) {
2154                return usageStatsService.getAllPkgUsageStats();
2155            }
2156        } catch (RemoteException e) {
2157            Log.w(TAG, "Could not query usage stats", e);
2158        }
2159        return new PkgUsageStats[0];
2160    }
2161
2162    /**
2163     * @param userid the user's id. Zero indicates the default user
2164     * @hide
2165     */
2166    public boolean switchUser(int userid) {
2167        try {
2168            return ActivityManagerNative.getDefault().switchUser(userid);
2169        } catch (RemoteException e) {
2170            return false;
2171        }
2172    }
2173
2174    /**
2175     * Return whether the given user is actively running.  This means that
2176     * the user is in the "started" state, not "stopped" -- it is currently
2177     * allowed to run code through scheduled alarms, receiving broadcasts,
2178     * etc.  A started user may be either the current foreground user or a
2179     * background user; the result here does not distinguish between the two.
2180     * @param userid the user's id. Zero indicates the default user.
2181     * @hide
2182     */
2183    public boolean isUserRunning(int userid) {
2184        try {
2185            return ActivityManagerNative.getDefault().isUserRunning(userid, false);
2186        } catch (RemoteException e) {
2187            return false;
2188        }
2189    }
2190
2191    /**
2192     * Perform a system dump of various state associated with the given application
2193     * package name.  This call blocks while the dump is being performed, so should
2194     * not be done on a UI thread.  The data will be written to the given file
2195     * descriptor as text.  An application must hold the
2196     * {@link android.Manifest.permission#DUMP} permission to make this call.
2197     * @param fd The file descriptor that the dump should be written to.
2198     * @param packageName The name of the package that is to be dumped.
2199     */
2200    public void dumpPackageState(FileDescriptor fd, String packageName) {
2201        dumpPackageStateStatic(fd, packageName);
2202    }
2203
2204    /**
2205     * @hide
2206     */
2207    public static void dumpPackageStateStatic(FileDescriptor fd, String packageName) {
2208        FileOutputStream fout = new FileOutputStream(fd);
2209        PrintWriter pw = new PrintWriter(fout);
2210        dumpService(pw, fd, Context.ACTIVITY_SERVICE, new String[] { "package", packageName});
2211        pw.println();
2212        dumpService(pw, fd, "package", new String[] { packageName});
2213        pw.println();
2214        dumpService(pw, fd, BatteryStats.SERVICE_NAME, new String[] { packageName});
2215        pw.flush();
2216    }
2217
2218    private static void dumpService(PrintWriter pw, FileDescriptor fd, String name, String[] args) {
2219        pw.print("DUMP OF SERVICE "); pw.print(name); pw.println(":");
2220        IBinder service = ServiceManager.checkService(name);
2221        if (service == null) {
2222            pw.println("  (Service not found)");
2223            return;
2224        }
2225        TransferPipe tp = null;
2226        try {
2227            pw.flush();
2228            tp = new TransferPipe();
2229            tp.setBufferPrefix("  ");
2230            service.dump(tp.getWriteFd().getFileDescriptor(), args);
2231            tp.go(fd);
2232        } catch (Throwable e) {
2233            if (tp != null) {
2234                tp.kill();
2235            }
2236            pw.println("Failure dumping service:");
2237            e.printStackTrace(pw);
2238        }
2239    }
2240}
2241