ActivityManager.java revision 27ff913d56de8400083a13fc572e2812b32c890c
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 com.android.internal.app.IUsageStats;
20import com.android.internal.os.PkgUsageStats;
21import com.android.internal.util.MemInfoReader;
22
23import android.content.ComponentName;
24import android.content.Context;
25import android.content.Intent;
26import android.content.pm.ApplicationInfo;
27import android.content.pm.ConfigurationInfo;
28import android.content.pm.IPackageDataObserver;
29import android.content.res.Configuration;
30import android.content.res.Resources;
31import android.graphics.Bitmap;
32import android.graphics.Point;
33import android.os.Binder;
34import android.os.Debug;
35import android.os.Handler;
36import android.os.Parcel;
37import android.os.Parcelable;
38import android.os.RemoteException;
39import android.os.ServiceManager;
40import android.os.SystemProperties;
41import android.text.TextUtils;
42import android.util.DisplayMetrics;
43import android.util.Log;
44import android.util.Slog;
45import android.view.Display;
46
47import java.util.ArrayList;
48import java.util.HashMap;
49import java.util.List;
50import java.util.Map;
51
52/**
53 * Interact with the overall activities running in the system.
54 */
55public class ActivityManager {
56    private static String TAG = "ActivityManager";
57    private static boolean localLOGV = false;
58
59    private final Context mContext;
60    private final Handler mHandler;
61
62    /*package*/ ActivityManager(Context context, Handler handler) {
63        mContext = context;
64        mHandler = handler;
65    }
66
67    /**
68     * Screen compatibility mode: the application most always run in
69     * compatibility mode.
70     * @hide
71     */
72    public static final int COMPAT_MODE_ALWAYS = -1;
73
74    /**
75     * Screen compatibility mode: the application can never run in
76     * compatibility mode.
77     * @hide
78     */
79    public static final int COMPAT_MODE_NEVER = -2;
80
81    /**
82     * Screen compatibility mode: unknown.
83     * @hide
84     */
85    public static final int COMPAT_MODE_UNKNOWN = -3;
86
87    /**
88     * Screen compatibility mode: the application currently has compatibility
89     * mode disabled.
90     * @hide
91     */
92    public static final int COMPAT_MODE_DISABLED = 0;
93
94    /**
95     * Screen compatibility mode: the application currently has compatibility
96     * mode enabled.
97     * @hide
98     */
99    public static final int COMPAT_MODE_ENABLED = 1;
100
101    /**
102     * Screen compatibility mode: request to toggle the application's
103     * compatibility mode.
104     * @hide
105     */
106    public static final int COMPAT_MODE_TOGGLE = 2;
107
108    /** @hide */
109    public int getFrontActivityScreenCompatMode() {
110        try {
111            return ActivityManagerNative.getDefault().getFrontActivityScreenCompatMode();
112        } catch (RemoteException e) {
113            // System dead, we will be dead too soon!
114            return 0;
115        }
116    }
117
118    /** @hide */
119    public void setFrontActivityScreenCompatMode(int mode) {
120        try {
121            ActivityManagerNative.getDefault().setFrontActivityScreenCompatMode(mode);
122        } catch (RemoteException e) {
123            // System dead, we will be dead too soon!
124        }
125    }
126
127    /** @hide */
128    public int getPackageScreenCompatMode(String packageName) {
129        try {
130            return ActivityManagerNative.getDefault().getPackageScreenCompatMode(packageName);
131        } catch (RemoteException e) {
132            // System dead, we will be dead too soon!
133            return 0;
134        }
135    }
136
137    /** @hide */
138    public void setPackageScreenCompatMode(String packageName, int mode) {
139        try {
140            ActivityManagerNative.getDefault().setPackageScreenCompatMode(packageName, mode);
141        } catch (RemoteException e) {
142            // System dead, we will be dead too soon!
143        }
144    }
145
146    /** @hide */
147    public boolean getPackageAskScreenCompat(String packageName) {
148        try {
149            return ActivityManagerNative.getDefault().getPackageAskScreenCompat(packageName);
150        } catch (RemoteException e) {
151            // System dead, we will be dead too soon!
152            return false;
153        }
154    }
155
156    /** @hide */
157    public void setPackageAskScreenCompat(String packageName, boolean ask) {
158        try {
159            ActivityManagerNative.getDefault().setPackageAskScreenCompat(packageName, ask);
160        } catch (RemoteException e) {
161            // System dead, we will be dead too soon!
162        }
163    }
164
165    /**
166     * Return the approximate per-application memory class of the current
167     * device.  This gives you an idea of how hard a memory limit you should
168     * impose on your application to let the overall system work best.  The
169     * returned value is in megabytes; the baseline Android memory class is
170     * 16 (which happens to be the Java heap limit of those devices); some
171     * device with more memory may return 24 or even higher numbers.
172     */
173    public int getMemoryClass() {
174        return staticGetMemoryClass();
175    }
176
177    /** @hide */
178    static public int staticGetMemoryClass() {
179        // Really brain dead right now -- just take this from the configured
180        // vm heap size, and assume it is in megabytes and thus ends with "m".
181        String vmHeapSize = SystemProperties.get("dalvik.vm.heapgrowthlimit", "");
182        if (vmHeapSize != null && !"".equals(vmHeapSize)) {
183            return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1));
184        }
185        return staticGetLargeMemoryClass();
186    }
187
188    /**
189     * Return the approximate per-application memory class of the current
190     * device when an application is running with a large heap.  This is the
191     * space available for memory-intensive applications; most applications
192     * should not need this amount of memory, and should instead stay with the
193     * {@link #getMemoryClass()} limit.  The returned value is in megabytes.
194     * This may be the same size as {@link #getMemoryClass()} on memory
195     * constrained devices, or it may be significantly larger on devices with
196     * a large amount of available RAM.
197     *
198     * <p>The is the size of the application's Dalvik heap if it has
199     * specified <code>android:largeHeap="true"</code> in its manifest.
200     */
201    public int getLargeMemoryClass() {
202        return staticGetLargeMemoryClass();
203    }
204
205    /** @hide */
206    static public int staticGetLargeMemoryClass() {
207        // Really brain dead right now -- just take this from the configured
208        // vm heap size, and assume it is in megabytes and thus ends with "m".
209        String vmHeapSize = SystemProperties.get("dalvik.vm.heapsize", "16m");
210        return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1));
211    }
212
213    /**
214     * Used by persistent processes to determine if they are running on a
215     * higher-end device so should be okay using hardware drawing acceleration
216     * (which tends to consume a lot more RAM).
217     * @hide
218     */
219    static public boolean isHighEndGfx(Display display) {
220        MemInfoReader reader = new MemInfoReader();
221        reader.readMemInfo();
222        if (reader.getTotalSize() >= (512*1024*1024)) {
223            // If the device has at least 512MB RAM available to the kernel,
224            // we can afford the overhead of graphics acceleration.
225            return true;
226        }
227        Point p = new Point();
228        display.getRealSize(p);
229        int pixels = p.x * p.y;
230        if (pixels >= (1024*600)) {
231            // If this is a sufficiently large screen, then there are enough
232            // pixels on it that we'd really like to use hw drawing.
233            return true;
234        }
235        return false;
236    }
237
238    /**
239     * Use to decide whether the running device can be considered a "large
240     * RAM" device.  Exactly what memory limit large RAM is will vary, but
241     * it essentially means there is plenty of RAM to have lots of background
242     * processes running under decent loads.
243     * @hide
244     */
245    static public boolean isLargeRAM() {
246        MemInfoReader reader = new MemInfoReader();
247        reader.readMemInfo();
248        if (reader.getTotalSize() >= (640*1024*1024)) {
249            // Currently 640MB RAM available to the kernel is the point at
250            // which we have plenty of RAM to spare.
251            return true;
252        }
253        return false;
254    }
255
256    /**
257     * Information you can retrieve about tasks that the user has most recently
258     * started or visited.
259     */
260    public static class RecentTaskInfo implements Parcelable {
261        /**
262         * If this task is currently running, this is the identifier for it.
263         * If it is not running, this will be -1.
264         */
265        public int id;
266
267        /**
268         * The true identifier of this task, valid even if it is not running.
269         */
270        public int persistentId;
271
272        /**
273         * The original Intent used to launch the task.  You can use this
274         * Intent to re-launch the task (if it is no longer running) or bring
275         * the current task to the front.
276         */
277        public Intent baseIntent;
278
279        /**
280         * If this task was started from an alias, this is the actual
281         * activity component that was initially started; the component of
282         * the baseIntent in this case is the name of the actual activity
283         * implementation that the alias referred to.  Otherwise, this is null.
284         */
285        public ComponentName origActivity;
286
287        /**
288         * Description of the task's last state.
289         */
290        public CharSequence description;
291
292        public RecentTaskInfo() {
293        }
294
295        public int describeContents() {
296            return 0;
297        }
298
299        public void writeToParcel(Parcel dest, int flags) {
300            dest.writeInt(id);
301            dest.writeInt(persistentId);
302            if (baseIntent != null) {
303                dest.writeInt(1);
304                baseIntent.writeToParcel(dest, 0);
305            } else {
306                dest.writeInt(0);
307            }
308            ComponentName.writeToParcel(origActivity, dest);
309            TextUtils.writeToParcel(description, dest,
310                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
311        }
312
313        public void readFromParcel(Parcel source) {
314            id = source.readInt();
315            persistentId = source.readInt();
316            if (source.readInt() != 0) {
317                baseIntent = Intent.CREATOR.createFromParcel(source);
318            } else {
319                baseIntent = null;
320            }
321            origActivity = ComponentName.readFromParcel(source);
322            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
323        }
324
325        public static final Creator<RecentTaskInfo> CREATOR
326                = new Creator<RecentTaskInfo>() {
327            public RecentTaskInfo createFromParcel(Parcel source) {
328                return new RecentTaskInfo(source);
329            }
330            public RecentTaskInfo[] newArray(int size) {
331                return new RecentTaskInfo[size];
332            }
333        };
334
335        private RecentTaskInfo(Parcel source) {
336            readFromParcel(source);
337        }
338    }
339
340    /**
341     * Flag for use with {@link #getRecentTasks}: return all tasks, even those
342     * that have set their
343     * {@link android.content.Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag.
344     */
345    public static final int RECENT_WITH_EXCLUDED = 0x0001;
346
347    /**
348     * Provides a list that does not contain any
349     * recent tasks that currently are not available to the user.
350     */
351    public static final int RECENT_IGNORE_UNAVAILABLE = 0x0002;
352
353    /**
354     * Return a list of the tasks that the user has recently launched, with
355     * the most recent being first and older ones after in order.
356     *
357     * @param maxNum The maximum number of entries to return in the list.  The
358     * actual number returned may be smaller, depending on how many tasks the
359     * user has started and the maximum number the system can remember.
360     * @param flags Information about what to return.  May be any combination
361     * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
362     *
363     * @return Returns a list of RecentTaskInfo records describing each of
364     * the recent tasks.
365     *
366     * @throws SecurityException Throws SecurityException if the caller does
367     * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
368     */
369    public List<RecentTaskInfo> getRecentTasks(int maxNum, int flags)
370            throws SecurityException {
371        try {
372            return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
373                    flags);
374        } catch (RemoteException e) {
375            // System dead, we will be dead too soon!
376            return null;
377        }
378    }
379
380    /**
381     * Information you can retrieve about a particular task that is currently
382     * "running" in the system.  Note that a running task does not mean the
383     * given task actually has a process it is actively running in; it simply
384     * means that the user has gone to it and never closed it, but currently
385     * the system may have killed its process and is only holding on to its
386     * last state in order to restart it when the user returns.
387     */
388    public static class RunningTaskInfo implements Parcelable {
389        /**
390         * A unique identifier for this task.
391         */
392        public int id;
393
394        /**
395         * The component launched as the first activity in the task.  This can
396         * be considered the "application" of this task.
397         */
398        public ComponentName baseActivity;
399
400        /**
401         * The activity component at the top of the history stack of the task.
402         * This is what the user is currently doing.
403         */
404        public ComponentName topActivity;
405
406        /**
407         * Thumbnail representation of the task's current state.  Currently
408         * always null.
409         */
410        public Bitmap thumbnail;
411
412        /**
413         * Description of the task's current state.
414         */
415        public CharSequence description;
416
417        /**
418         * Number of activities in this task.
419         */
420        public int numActivities;
421
422        /**
423         * Number of activities that are currently running (not stopped
424         * and persisted) in this task.
425         */
426        public int numRunning;
427
428        public RunningTaskInfo() {
429        }
430
431        public int describeContents() {
432            return 0;
433        }
434
435        public void writeToParcel(Parcel dest, int flags) {
436            dest.writeInt(id);
437            ComponentName.writeToParcel(baseActivity, dest);
438            ComponentName.writeToParcel(topActivity, dest);
439            if (thumbnail != null) {
440                dest.writeInt(1);
441                thumbnail.writeToParcel(dest, 0);
442            } else {
443                dest.writeInt(0);
444            }
445            TextUtils.writeToParcel(description, dest,
446                    Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
447            dest.writeInt(numActivities);
448            dest.writeInt(numRunning);
449        }
450
451        public void readFromParcel(Parcel source) {
452            id = source.readInt();
453            baseActivity = ComponentName.readFromParcel(source);
454            topActivity = ComponentName.readFromParcel(source);
455            if (source.readInt() != 0) {
456                thumbnail = Bitmap.CREATOR.createFromParcel(source);
457            } else {
458                thumbnail = null;
459            }
460            description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
461            numActivities = source.readInt();
462            numRunning = source.readInt();
463        }
464
465        public static final Creator<RunningTaskInfo> CREATOR = new Creator<RunningTaskInfo>() {
466            public RunningTaskInfo createFromParcel(Parcel source) {
467                return new RunningTaskInfo(source);
468            }
469            public RunningTaskInfo[] newArray(int size) {
470                return new RunningTaskInfo[size];
471            }
472        };
473
474        private RunningTaskInfo(Parcel source) {
475            readFromParcel(source);
476        }
477    }
478
479    /**
480     * Return a list of the tasks that are currently running, with
481     * the most recent being first and older ones after in order.  Note that
482     * "running" does not mean any of the task's code is currently loaded or
483     * activity -- the task may have been frozen by the system, so that it
484     * can be restarted in its previous state when next brought to the
485     * foreground.
486     *
487     * @param maxNum The maximum number of entries to return in the list.  The
488     * actual number returned may be smaller, depending on how many tasks the
489     * user has started.
490     *
491     * @param flags Optional flags
492     * @param receiver Optional receiver for delayed thumbnails
493     *
494     * @return Returns a list of RunningTaskInfo records describing each of
495     * the running tasks.
496     *
497     * Some thumbnails may not be available at the time of this call. The optional
498     * receiver may be used to receive those thumbnails.
499     *
500     * @throws SecurityException Throws SecurityException if the caller does
501     * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
502     *
503     * @hide
504     */
505    public List<RunningTaskInfo> getRunningTasks(int maxNum, int flags, IThumbnailReceiver receiver)
506            throws SecurityException {
507        try {
508            return ActivityManagerNative.getDefault().getTasks(maxNum, flags, receiver);
509        } catch (RemoteException e) {
510            // System dead, we will be dead too soon!
511            return null;
512        }
513    }
514
515    /**
516     * Return a list of the tasks that are currently running, with
517     * the most recent being first and older ones after in order.  Note that
518     * "running" does not mean any of the task's code is currently loaded or
519     * activity -- the task may have been frozen by the system, so that it
520     * can be restarted in its previous state when next brought to the
521     * foreground.
522     *
523     * @param maxNum The maximum number of entries to return in the list.  The
524     * actual number returned may be smaller, depending on how many tasks the
525     * user has started.
526     *
527     * @return Returns a list of RunningTaskInfo records describing each of
528     * the running tasks.
529     *
530     * @throws SecurityException Throws SecurityException if the caller does
531     * not hold the {@link android.Manifest.permission#GET_TASKS} permission.
532     */
533    public List<RunningTaskInfo> getRunningTasks(int maxNum)
534            throws SecurityException {
535        return getRunningTasks(maxNum, 0, null);
536    }
537
538    /**
539     * Remove some end of a task's activity stack that is not part of
540     * the main application.  The selected activities will be finished, so
541     * they are no longer part of the main task.
542     *
543     * @param taskId The identifier of the task.
544     * @param subTaskIndex The number of the sub-task; this corresponds
545     * to the index of the thumbnail returned by {@link #getTaskThumbnails(int)}.
546     * @return Returns true if the sub-task was found and was removed.
547     *
548     * @hide
549     */
550    public boolean removeSubTask(int taskId, int subTaskIndex)
551            throws SecurityException {
552        try {
553            return ActivityManagerNative.getDefault().removeSubTask(taskId, subTaskIndex);
554        } catch (RemoteException e) {
555            // System dead, we will be dead too soon!
556            return false;
557        }
558    }
559
560    /**
561     * If set, the process of the root activity of the task will be killed
562     * as part of removing the task.
563     * @hide
564     */
565    public static final int REMOVE_TASK_KILL_PROCESS = 0x0001;
566
567    /**
568     * Completely remove the given task.
569     *
570     * @param taskId Identifier of the task to be removed.
571     * @param flags Additional operational flags.  May be 0 or
572     * {@link #REMOVE_TASK_KILL_PROCESS}.
573     * @return Returns true if the given task was found and removed.
574     *
575     * @hide
576     */
577    public boolean removeTask(int taskId, int flags)
578            throws SecurityException {
579        try {
580            return ActivityManagerNative.getDefault().removeTask(taskId, flags);
581        } catch (RemoteException e) {
582            // System dead, we will be dead too soon!
583            return false;
584        }
585    }
586
587    /** @hide */
588    public static class TaskThumbnails implements Parcelable {
589        public Bitmap mainThumbnail;
590
591        public int numSubThumbbails;
592
593        /** @hide */
594        public IThumbnailRetriever retriever;
595
596        public TaskThumbnails() {
597        }
598
599        public Bitmap getSubThumbnail(int index) {
600            try {
601                return retriever.getThumbnail(index);
602            } catch (RemoteException e) {
603                return null;
604            }
605        }
606
607        public int describeContents() {
608            return 0;
609        }
610
611        public void writeToParcel(Parcel dest, int flags) {
612            if (mainThumbnail != null) {
613                dest.writeInt(1);
614                mainThumbnail.writeToParcel(dest, 0);
615            } else {
616                dest.writeInt(0);
617            }
618            dest.writeInt(numSubThumbbails);
619            dest.writeStrongInterface(retriever);
620        }
621
622        public void readFromParcel(Parcel source) {
623            if (source.readInt() != 0) {
624                mainThumbnail = Bitmap.CREATOR.createFromParcel(source);
625            } else {
626                mainThumbnail = null;
627            }
628            numSubThumbbails = source.readInt();
629            retriever = IThumbnailRetriever.Stub.asInterface(source.readStrongBinder());
630        }
631
632        public static final Creator<TaskThumbnails> CREATOR = new Creator<TaskThumbnails>() {
633            public TaskThumbnails createFromParcel(Parcel source) {
634                return new TaskThumbnails(source);
635            }
636            public TaskThumbnails[] newArray(int size) {
637                return new TaskThumbnails[size];
638            }
639        };
640
641        private TaskThumbnails(Parcel source) {
642            readFromParcel(source);
643        }
644    }
645
646    /** @hide */
647    public TaskThumbnails getTaskThumbnails(int id) throws SecurityException {
648        try {
649            return ActivityManagerNative.getDefault().getTaskThumbnails(id);
650        } catch (RemoteException e) {
651            // System dead, we will be dead too soon!
652            return null;
653        }
654    }
655
656    /**
657     * Flag for {@link #moveTaskToFront(int, int)}: also move the "home"
658     * activity along with the task, so it is positioned immediately behind
659     * the task.
660     */
661    public static final int MOVE_TASK_WITH_HOME = 0x00000001;
662
663    /**
664     * Flag for {@link #moveTaskToFront(int, int)}: don't count this as a
665     * user-instigated action, so the current activity will not receive a
666     * hint that the user is leaving.
667     */
668    public static final int MOVE_TASK_NO_USER_ACTION = 0x00000002;
669
670    /**
671     * Ask that the task associated with a given task ID be moved to the
672     * front of the stack, so it is now visible to the user.  Requires that
673     * the caller hold permission {@link android.Manifest.permission#REORDER_TASKS}
674     * or a SecurityException will be thrown.
675     *
676     * @param taskId The identifier of the task to be moved, as found in
677     * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
678     * @param flags Additional operational flags, 0 or more of
679     * {@link #MOVE_TASK_WITH_HOME}.
680     */
681    public void moveTaskToFront(int taskId, int flags) {
682        try {
683            ActivityManagerNative.getDefault().moveTaskToFront(taskId, flags);
684        } catch (RemoteException e) {
685            // System dead, we will be dead too soon!
686        }
687    }
688
689    /**
690     * Information you can retrieve about a particular Service that is
691     * currently running in the system.
692     */
693    public static class RunningServiceInfo implements Parcelable {
694        /**
695         * The service component.
696         */
697        public ComponentName service;
698
699        /**
700         * If non-zero, this is the process the service is running in.
701         */
702        public int pid;
703
704        /**
705         * The UID that owns this service.
706         */
707        public int uid;
708
709        /**
710         * The name of the process this service runs in.
711         */
712        public String process;
713
714        /**
715         * Set to true if the service has asked to run as a foreground process.
716         */
717        public boolean foreground;
718
719        /**
720         * The time when the service was first made active, either by someone
721         * starting or binding to it.  This
722         * is in units of {@link android.os.SystemClock#elapsedRealtime()}.
723         */
724        public long activeSince;
725
726        /**
727         * Set to true if this service has been explicitly started.
728         */
729        public boolean started;
730
731        /**
732         * Number of clients connected to the service.
733         */
734        public int clientCount;
735
736        /**
737         * Number of times the service's process has crashed while the service
738         * is running.
739         */
740        public int crashCount;
741
742        /**
743         * The time when there was last activity in the service (either
744         * explicit requests to start it or clients binding to it).  This
745         * is in units of {@link android.os.SystemClock#uptimeMillis()}.
746         */
747        public long lastActivityTime;
748
749        /**
750         * If non-zero, this service is not currently running, but scheduled to
751         * restart at the given time.
752         */
753        public long restarting;
754
755        /**
756         * Bit for {@link #flags}: set if this service has been
757         * explicitly started.
758         */
759        public static final int FLAG_STARTED = 1<<0;
760
761        /**
762         * Bit for {@link #flags}: set if the service has asked to
763         * run as a foreground process.
764         */
765        public static final int FLAG_FOREGROUND = 1<<1;
766
767        /**
768         * Bit for {@link #flags): set if the service is running in a
769         * core system process.
770         */
771        public static final int FLAG_SYSTEM_PROCESS = 1<<2;
772
773        /**
774         * Bit for {@link #flags): set if the service is running in a
775         * persistent process.
776         */
777        public static final int FLAG_PERSISTENT_PROCESS = 1<<3;
778
779        /**
780         * Running flags.
781         */
782        public int flags;
783
784        /**
785         * For special services that are bound to by system code, this is
786         * the package that holds the binding.
787         */
788        public String clientPackage;
789
790        /**
791         * For special services that are bound to by system code, this is
792         * a string resource providing a user-visible label for who the
793         * client is.
794         */
795        public int clientLabel;
796
797        public RunningServiceInfo() {
798        }
799
800        public int describeContents() {
801            return 0;
802        }
803
804        public void writeToParcel(Parcel dest, int flags) {
805            ComponentName.writeToParcel(service, dest);
806            dest.writeInt(pid);
807            dest.writeInt(uid);
808            dest.writeString(process);
809            dest.writeInt(foreground ? 1 : 0);
810            dest.writeLong(activeSince);
811            dest.writeInt(started ? 1 : 0);
812            dest.writeInt(clientCount);
813            dest.writeInt(crashCount);
814            dest.writeLong(lastActivityTime);
815            dest.writeLong(restarting);
816            dest.writeInt(this.flags);
817            dest.writeString(clientPackage);
818            dest.writeInt(clientLabel);
819        }
820
821        public void readFromParcel(Parcel source) {
822            service = ComponentName.readFromParcel(source);
823            pid = source.readInt();
824            uid = source.readInt();
825            process = source.readString();
826            foreground = source.readInt() != 0;
827            activeSince = source.readLong();
828            started = source.readInt() != 0;
829            clientCount = source.readInt();
830            crashCount = source.readInt();
831            lastActivityTime = source.readLong();
832            restarting = source.readLong();
833            flags = source.readInt();
834            clientPackage = source.readString();
835            clientLabel = source.readInt();
836        }
837
838        public static final Creator<RunningServiceInfo> CREATOR = new Creator<RunningServiceInfo>() {
839            public RunningServiceInfo createFromParcel(Parcel source) {
840                return new RunningServiceInfo(source);
841            }
842            public RunningServiceInfo[] newArray(int size) {
843                return new RunningServiceInfo[size];
844            }
845        };
846
847        private RunningServiceInfo(Parcel source) {
848            readFromParcel(source);
849        }
850    }
851
852    /**
853     * Return a list of the services that are currently running.
854     *
855     * @param maxNum The maximum number of entries to return in the list.  The
856     * actual number returned may be smaller, depending on how many services
857     * are running.
858     *
859     * @return Returns a list of RunningServiceInfo records describing each of
860     * the running tasks.
861     */
862    public List<RunningServiceInfo> getRunningServices(int maxNum)
863            throws SecurityException {
864        try {
865            return ActivityManagerNative.getDefault()
866                    .getServices(maxNum, 0);
867        } catch (RemoteException e) {
868            // System dead, we will be dead too soon!
869            return null;
870        }
871    }
872
873    /**
874     * Returns a PendingIntent you can start to show a control panel for the
875     * given running service.  If the service does not have a control panel,
876     * null is returned.
877     */
878    public PendingIntent getRunningServiceControlPanel(ComponentName service)
879            throws SecurityException {
880        try {
881            return ActivityManagerNative.getDefault()
882                    .getRunningServiceControlPanel(service);
883        } catch (RemoteException e) {
884            // System dead, we will be dead too soon!
885            return null;
886        }
887    }
888
889    /**
890     * Information you can retrieve about the available memory through
891     * {@link ActivityManager#getMemoryInfo}.
892     */
893    public static class MemoryInfo implements Parcelable {
894        /**
895         * The total available memory on the system.  This number should not
896         * be considered absolute: due to the nature of the kernel, a significant
897         * portion of this memory is actually in use and needed for the overall
898         * system to run well.
899         */
900        public long availMem;
901
902        /**
903         * The threshold of {@link #availMem} at which we consider memory to be
904         * low and start killing background services and other non-extraneous
905         * processes.
906         */
907        public long threshold;
908
909        /**
910         * Set to true if the system considers itself to currently be in a low
911         * memory situation.
912         */
913        public boolean lowMemory;
914
915        /** @hide */
916        public long hiddenAppThreshold;
917        /** @hide */
918        public long secondaryServerThreshold;
919        /** @hide */
920        public long visibleAppThreshold;
921        /** @hide */
922        public long foregroundAppThreshold;
923
924        public MemoryInfo() {
925        }
926
927        public int describeContents() {
928            return 0;
929        }
930
931        public void writeToParcel(Parcel dest, int flags) {
932            dest.writeLong(availMem);
933            dest.writeLong(threshold);
934            dest.writeInt(lowMemory ? 1 : 0);
935            dest.writeLong(hiddenAppThreshold);
936            dest.writeLong(secondaryServerThreshold);
937            dest.writeLong(visibleAppThreshold);
938            dest.writeLong(foregroundAppThreshold);
939        }
940
941        public void readFromParcel(Parcel source) {
942            availMem = source.readLong();
943            threshold = source.readLong();
944            lowMemory = source.readInt() != 0;
945            hiddenAppThreshold = source.readLong();
946            secondaryServerThreshold = source.readLong();
947            visibleAppThreshold = source.readLong();
948            foregroundAppThreshold = source.readLong();
949        }
950
951        public static final Creator<MemoryInfo> CREATOR
952                = new Creator<MemoryInfo>() {
953            public MemoryInfo createFromParcel(Parcel source) {
954                return new MemoryInfo(source);
955            }
956            public MemoryInfo[] newArray(int size) {
957                return new MemoryInfo[size];
958            }
959        };
960
961        private MemoryInfo(Parcel source) {
962            readFromParcel(source);
963        }
964    }
965
966    public void getMemoryInfo(MemoryInfo outInfo) {
967        try {
968            ActivityManagerNative.getDefault().getMemoryInfo(outInfo);
969        } catch (RemoteException e) {
970        }
971    }
972
973    /**
974     * @hide
975     */
976    public boolean clearApplicationUserData(String packageName, IPackageDataObserver observer) {
977        try {
978            return ActivityManagerNative.getDefault().clearApplicationUserData(packageName,
979                    observer, Binder.getOrigCallingUser());
980        } catch (RemoteException e) {
981            return false;
982        }
983    }
984
985    /**
986     * Information you can retrieve about any processes that are in an error condition.
987     */
988    public static class ProcessErrorStateInfo implements Parcelable {
989        /**
990         * Condition codes
991         */
992        public static final int NO_ERROR = 0;
993        public static final int CRASHED = 1;
994        public static final int NOT_RESPONDING = 2;
995
996        /**
997         * The condition that the process is in.
998         */
999        public int condition;
1000
1001        /**
1002         * The process name in which the crash or error occurred.
1003         */
1004        public String processName;
1005
1006        /**
1007         * The pid of this process; 0 if none
1008         */
1009        public int pid;
1010
1011        /**
1012         * The kernel user-ID that has been assigned to this process;
1013         * currently this is not a unique ID (multiple applications can have
1014         * the same uid).
1015         */
1016        public int uid;
1017
1018        /**
1019         * The activity name associated with the error, if known.  May be null.
1020         */
1021        public String tag;
1022
1023        /**
1024         * A short message describing the error condition.
1025         */
1026        public String shortMsg;
1027
1028        /**
1029         * A long message describing the error condition.
1030         */
1031        public String longMsg;
1032
1033        /**
1034         * The stack trace where the error originated.  May be null.
1035         */
1036        public String stackTrace;
1037
1038        /**
1039         * to be deprecated: This value will always be null.
1040         */
1041        public byte[] crashData = null;
1042
1043        public ProcessErrorStateInfo() {
1044        }
1045
1046        public int describeContents() {
1047            return 0;
1048        }
1049
1050        public void writeToParcel(Parcel dest, int flags) {
1051            dest.writeInt(condition);
1052            dest.writeString(processName);
1053            dest.writeInt(pid);
1054            dest.writeInt(uid);
1055            dest.writeString(tag);
1056            dest.writeString(shortMsg);
1057            dest.writeString(longMsg);
1058            dest.writeString(stackTrace);
1059        }
1060
1061        public void readFromParcel(Parcel source) {
1062            condition = source.readInt();
1063            processName = source.readString();
1064            pid = source.readInt();
1065            uid = source.readInt();
1066            tag = source.readString();
1067            shortMsg = source.readString();
1068            longMsg = source.readString();
1069            stackTrace = source.readString();
1070        }
1071
1072        public static final Creator<ProcessErrorStateInfo> CREATOR =
1073                new Creator<ProcessErrorStateInfo>() {
1074            public ProcessErrorStateInfo createFromParcel(Parcel source) {
1075                return new ProcessErrorStateInfo(source);
1076            }
1077            public ProcessErrorStateInfo[] newArray(int size) {
1078                return new ProcessErrorStateInfo[size];
1079            }
1080        };
1081
1082        private ProcessErrorStateInfo(Parcel source) {
1083            readFromParcel(source);
1084        }
1085    }
1086
1087    /**
1088     * Returns a list of any processes that are currently in an error condition.  The result
1089     * will be null if all processes are running properly at this time.
1090     *
1091     * @return Returns a list of ProcessErrorStateInfo records, or null if there are no
1092     * current error conditions (it will not return an empty list).  This list ordering is not
1093     * specified.
1094     */
1095    public List<ProcessErrorStateInfo> getProcessesInErrorState() {
1096        try {
1097            return ActivityManagerNative.getDefault().getProcessesInErrorState();
1098        } catch (RemoteException e) {
1099            return null;
1100        }
1101    }
1102
1103    /**
1104     * Information you can retrieve about a running process.
1105     */
1106    public static class RunningAppProcessInfo implements Parcelable {
1107        /**
1108         * The name of the process that this object is associated with
1109         */
1110        public String processName;
1111
1112        /**
1113         * The pid of this process; 0 if none
1114         */
1115        public int pid;
1116
1117        /**
1118         * The user id of this process.
1119         */
1120        public int uid;
1121
1122        /**
1123         * All packages that have been loaded into the process.
1124         */
1125        public String pkgList[];
1126
1127        /**
1128         * Constant for {@link #flags}: this is an app that is unable to
1129         * correctly save its state when going to the background,
1130         * so it can not be killed while in the background.
1131         * @hide
1132         */
1133        public static final int FLAG_CANT_SAVE_STATE = 1<<0;
1134
1135        /**
1136         * Constant for {@link #flags}: this process is associated with a
1137         * persistent system app.
1138         * @hide
1139         */
1140        public static final int FLAG_PERSISTENT = 1<<1;
1141
1142        /**
1143         * Flags of information.  May be any of
1144         * {@link #FLAG_CANT_SAVE_STATE}.
1145         * @hide
1146         */
1147        public int flags;
1148
1149        /**
1150         * Last memory trim level reported to the process: corresponds to
1151         * the values supplied to {@link android.content.ComponentCallbacks2#onTrimMemory(int)
1152         * ComponentCallbacks2.onTrimMemory(int)}.
1153         */
1154        public int lastTrimLevel;
1155
1156        /**
1157         * Constant for {@link #importance}: this process is running the
1158         * foreground UI.
1159         */
1160        public static final int IMPORTANCE_FOREGROUND = 100;
1161
1162        /**
1163         * Constant for {@link #importance}: this process is running something
1164         * that is actively visible to the user, though not in the immediate
1165         * foreground.
1166         */
1167        public static final int IMPORTANCE_VISIBLE = 200;
1168
1169        /**
1170         * Constant for {@link #importance}: this process is running something
1171         * that is considered to be actively perceptible to the user.  An
1172         * example would be an application performing background music playback.
1173         */
1174        public static final int IMPORTANCE_PERCEPTIBLE = 130;
1175
1176        /**
1177         * Constant for {@link #importance}: this process is running an
1178         * application that can not save its state, and thus can't be killed
1179         * while in the background.
1180         * @hide
1181         */
1182        public static final int IMPORTANCE_CANT_SAVE_STATE = 170;
1183
1184        /**
1185         * Constant for {@link #importance}: this process is contains services
1186         * that should remain running.
1187         */
1188        public static final int IMPORTANCE_SERVICE = 300;
1189
1190        /**
1191         * Constant for {@link #importance}: this process process contains
1192         * background code that is expendable.
1193         */
1194        public static final int IMPORTANCE_BACKGROUND = 400;
1195
1196        /**
1197         * Constant for {@link #importance}: this process is empty of any
1198         * actively running code.
1199         */
1200        public static final int IMPORTANCE_EMPTY = 500;
1201
1202        /**
1203         * The relative importance level that the system places on this
1204         * process.  May be one of {@link #IMPORTANCE_FOREGROUND},
1205         * {@link #IMPORTANCE_VISIBLE}, {@link #IMPORTANCE_SERVICE},
1206         * {@link #IMPORTANCE_BACKGROUND}, or {@link #IMPORTANCE_EMPTY}.  These
1207         * constants are numbered so that "more important" values are always
1208         * smaller than "less important" values.
1209         */
1210        public int importance;
1211
1212        /**
1213         * An additional ordering within a particular {@link #importance}
1214         * category, providing finer-grained information about the relative
1215         * utility of processes within a category.  This number means nothing
1216         * except that a smaller values are more recently used (and thus
1217         * more important).  Currently an LRU value is only maintained for
1218         * the {@link #IMPORTANCE_BACKGROUND} category, though others may
1219         * be maintained in the future.
1220         */
1221        public int lru;
1222
1223        /**
1224         * Constant for {@link #importanceReasonCode}: nothing special has
1225         * been specified for the reason for this level.
1226         */
1227        public static final int REASON_UNKNOWN = 0;
1228
1229        /**
1230         * Constant for {@link #importanceReasonCode}: one of the application's
1231         * content providers is being used by another process.  The pid of
1232         * the client process is in {@link #importanceReasonPid} and the
1233         * target provider in this process is in
1234         * {@link #importanceReasonComponent}.
1235         */
1236        public static final int REASON_PROVIDER_IN_USE = 1;
1237
1238        /**
1239         * Constant for {@link #importanceReasonCode}: one of the application's
1240         * content providers is being used by another process.  The pid of
1241         * the client process is in {@link #importanceReasonPid} and the
1242         * target provider in this process is in
1243         * {@link #importanceReasonComponent}.
1244         */
1245        public static final int REASON_SERVICE_IN_USE = 2;
1246
1247        /**
1248         * The reason for {@link #importance}, if any.
1249         */
1250        public int importanceReasonCode;
1251
1252        /**
1253         * For the specified values of {@link #importanceReasonCode}, this
1254         * is the process ID of the other process that is a client of this
1255         * process.  This will be 0 if no other process is using this one.
1256         */
1257        public int importanceReasonPid;
1258
1259        /**
1260         * For the specified values of {@link #importanceReasonCode}, this
1261         * is the name of the component that is being used in this process.
1262         */
1263        public ComponentName importanceReasonComponent;
1264
1265        /**
1266         * When {@link importanceReasonPid} is non-0, this is the importance
1267         * of the other pid. @hide
1268         */
1269        public int importanceReasonImportance;
1270
1271        public RunningAppProcessInfo() {
1272            importance = IMPORTANCE_FOREGROUND;
1273            importanceReasonCode = REASON_UNKNOWN;
1274        }
1275
1276        public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) {
1277            processName = pProcessName;
1278            pid = pPid;
1279            pkgList = pArr;
1280        }
1281
1282        public int describeContents() {
1283            return 0;
1284        }
1285
1286        public void writeToParcel(Parcel dest, int flags) {
1287            dest.writeString(processName);
1288            dest.writeInt(pid);
1289            dest.writeInt(uid);
1290            dest.writeStringArray(pkgList);
1291            dest.writeInt(this.flags);
1292            dest.writeInt(lastTrimLevel);
1293            dest.writeInt(importance);
1294            dest.writeInt(lru);
1295            dest.writeInt(importanceReasonCode);
1296            dest.writeInt(importanceReasonPid);
1297            ComponentName.writeToParcel(importanceReasonComponent, dest);
1298            dest.writeInt(importanceReasonImportance);
1299        }
1300
1301        public void readFromParcel(Parcel source) {
1302            processName = source.readString();
1303            pid = source.readInt();
1304            uid = source.readInt();
1305            pkgList = source.readStringArray();
1306            flags = source.readInt();
1307            lastTrimLevel = source.readInt();
1308            importance = source.readInt();
1309            lru = source.readInt();
1310            importanceReasonCode = source.readInt();
1311            importanceReasonPid = source.readInt();
1312            importanceReasonComponent = ComponentName.readFromParcel(source);
1313            importanceReasonImportance = source.readInt();
1314        }
1315
1316        public static final Creator<RunningAppProcessInfo> CREATOR =
1317            new Creator<RunningAppProcessInfo>() {
1318            public RunningAppProcessInfo createFromParcel(Parcel source) {
1319                return new RunningAppProcessInfo(source);
1320            }
1321            public RunningAppProcessInfo[] newArray(int size) {
1322                return new RunningAppProcessInfo[size];
1323            }
1324        };
1325
1326        private RunningAppProcessInfo(Parcel source) {
1327            readFromParcel(source);
1328        }
1329    }
1330
1331    /**
1332     * Returns a list of application processes installed on external media
1333     * that are running on the device.
1334     *
1335     * @return Returns a list of ApplicationInfo records, or null if none
1336     * This list ordering is not specified.
1337     * @hide
1338     */
1339    public List<ApplicationInfo> getRunningExternalApplications() {
1340        try {
1341            return ActivityManagerNative.getDefault().getRunningExternalApplications();
1342        } catch (RemoteException e) {
1343            return null;
1344        }
1345    }
1346
1347    /**
1348     * Returns a list of application processes that are running on the device.
1349     *
1350     * @return Returns a list of RunningAppProcessInfo records, or null if there are no
1351     * running processes (it will not return an empty list).  This list ordering is not
1352     * specified.
1353     */
1354    public List<RunningAppProcessInfo> getRunningAppProcesses() {
1355        try {
1356            return ActivityManagerNative.getDefault().getRunningAppProcesses();
1357        } catch (RemoteException e) {
1358            return null;
1359        }
1360    }
1361
1362    /**
1363     * Return global memory state information for the calling process.  This
1364     * does not fill in all fields of the {@link RunningAppProcessInfo}.  The
1365     * only fields that will be filled in are
1366     * {@link RunningAppProcessInfo#pid},
1367     * {@link RunningAppProcessInfo#uid},
1368     * {@link RunningAppProcessInfo#lastTrimLevel},
1369     * {@link RunningAppProcessInfo#importance},
1370     * {@link RunningAppProcessInfo#lru}, and
1371     * {@link RunningAppProcessInfo#importanceReasonCode}.
1372     */
1373    static public void getMyMemoryState(RunningAppProcessInfo outState) {
1374        try {
1375            ActivityManagerNative.getDefault().getMyMemoryState(outState);
1376        } catch (RemoteException e) {
1377        }
1378    }
1379
1380    /**
1381     * Return information about the memory usage of one or more processes.
1382     *
1383     * @param pids The pids of the processes whose memory usage is to be
1384     * retrieved.
1385     * @return Returns an array of memory information, one for each
1386     * requested pid.
1387     */
1388    public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
1389        try {
1390            return ActivityManagerNative.getDefault().getProcessMemoryInfo(pids);
1391        } catch (RemoteException e) {
1392            return null;
1393        }
1394    }
1395
1396    /**
1397     * @deprecated This is now just a wrapper for
1398     * {@link #killBackgroundProcesses(String)}; the previous behavior here
1399     * is no longer available to applications because it allows them to
1400     * break other applications by removing their alarms, stopping their
1401     * services, etc.
1402     */
1403    @Deprecated
1404    public void restartPackage(String packageName) {
1405        killBackgroundProcesses(packageName);
1406    }
1407
1408    /**
1409     * Have the system immediately kill all background processes associated
1410     * with the given package.  This is the same as the kernel killing those
1411     * processes to reclaim memory; the system will take care of restarting
1412     * these processes in the future as needed.
1413     *
1414     * <p>You must hold the permission
1415     * {@link android.Manifest.permission#KILL_BACKGROUND_PROCESSES} to be able to
1416     * call this method.
1417     *
1418     * @param packageName The name of the package whose processes are to
1419     * be killed.
1420     */
1421    public void killBackgroundProcesses(String packageName) {
1422        try {
1423            ActivityManagerNative.getDefault().killBackgroundProcesses(packageName);
1424        } catch (RemoteException e) {
1425        }
1426    }
1427
1428    /**
1429     * Have the system perform a force stop of everything associated with
1430     * the given application package.  All processes that share its uid
1431     * will be killed, all services it has running stopped, all activities
1432     * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
1433     * broadcast will be sent, so that any of its registered alarms can
1434     * be stopped, notifications removed, etc.
1435     *
1436     * <p>You must hold the permission
1437     * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
1438     * call this method.
1439     *
1440     * @param packageName The name of the package to be stopped.
1441     *
1442     * @hide This is not available to third party applications due to
1443     * it allowing them to break other applications by stopping their
1444     * services, removing their alarms, etc.
1445     */
1446    public void forceStopPackage(String packageName) {
1447        try {
1448            ActivityManagerNative.getDefault().forceStopPackage(packageName);
1449        } catch (RemoteException e) {
1450        }
1451    }
1452
1453    /**
1454     * Get the device configuration attributes.
1455     */
1456    public ConfigurationInfo getDeviceConfigurationInfo() {
1457        try {
1458            return ActivityManagerNative.getDefault().getDeviceConfigurationInfo();
1459        } catch (RemoteException e) {
1460        }
1461        return null;
1462    }
1463
1464    /**
1465     * Get the preferred density of icons for the launcher. This is used when
1466     * custom drawables are created (e.g., for shortcuts).
1467     *
1468     * @return density in terms of DPI
1469     */
1470    public int getLauncherLargeIconDensity() {
1471        final Resources res = mContext.getResources();
1472        final int density = res.getDisplayMetrics().densityDpi;
1473        final int sw = res.getConfiguration().smallestScreenWidthDp;
1474
1475        if (sw < 600) {
1476            // Smaller than approx 7" tablets, use the regular icon size.
1477            return density;
1478        }
1479
1480        switch (density) {
1481            case DisplayMetrics.DENSITY_LOW:
1482                return DisplayMetrics.DENSITY_MEDIUM;
1483            case DisplayMetrics.DENSITY_MEDIUM:
1484                return DisplayMetrics.DENSITY_HIGH;
1485            case DisplayMetrics.DENSITY_HIGH:
1486                return DisplayMetrics.DENSITY_XHIGH;
1487            case DisplayMetrics.DENSITY_XHIGH:
1488                return DisplayMetrics.DENSITY_XXHIGH;
1489            case DisplayMetrics.DENSITY_XXHIGH:
1490                return DisplayMetrics.DENSITY_XHIGH * 2;
1491            default:
1492                // The density is some abnormal value.  Return some other
1493                // abnormal value that is a reasonable scaling of it.
1494                return (int)(density*1.5f);
1495        }
1496    }
1497
1498    /**
1499     * Get the preferred launcher icon size. This is used when custom drawables
1500     * are created (e.g., for shortcuts).
1501     *
1502     * @return dimensions of square icons in terms of pixels
1503     */
1504    public int getLauncherLargeIconSize() {
1505        final Resources res = mContext.getResources();
1506        final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size);
1507        final int sw = res.getConfiguration().smallestScreenWidthDp;
1508
1509        if (sw < 600) {
1510            // Smaller than approx 7" tablets, use the regular icon size.
1511            return size;
1512        }
1513
1514        final int density = res.getDisplayMetrics().densityDpi;
1515
1516        switch (density) {
1517            case DisplayMetrics.DENSITY_LOW:
1518                return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW;
1519            case DisplayMetrics.DENSITY_MEDIUM:
1520                return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM;
1521            case DisplayMetrics.DENSITY_HIGH:
1522                return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
1523            case DisplayMetrics.DENSITY_XHIGH:
1524                return (size * DisplayMetrics.DENSITY_XXHIGH) / DisplayMetrics.DENSITY_XHIGH;
1525            case DisplayMetrics.DENSITY_XXHIGH:
1526                return (size * DisplayMetrics.DENSITY_XHIGH*2) / DisplayMetrics.DENSITY_XXHIGH;
1527            default:
1528                // The density is some abnormal value.  Return some other
1529                // abnormal value that is a reasonable scaling of it.
1530                return (int)(size*1.5f);
1531        }
1532    }
1533
1534    /**
1535     * Returns "true" if the user interface is currently being messed with
1536     * by a monkey.
1537     */
1538    public static boolean isUserAMonkey() {
1539        try {
1540            return ActivityManagerNative.getDefault().isUserAMonkey();
1541        } catch (RemoteException e) {
1542        }
1543        return false;
1544    }
1545
1546    /**
1547     * Returns "true" if device is running in a test harness.
1548     */
1549    public static boolean isRunningInTestHarness() {
1550        return SystemProperties.getBoolean("ro.test_harness", false);
1551    }
1552
1553    /**
1554     * Returns the launch count of each installed package.
1555     *
1556     * @hide
1557     */
1558    public Map<String, Integer> getAllPackageLaunchCounts() {
1559        try {
1560            IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
1561                    ServiceManager.getService("usagestats"));
1562            if (usageStatsService == null) {
1563                return new HashMap<String, Integer>();
1564            }
1565
1566            PkgUsageStats[] allPkgUsageStats = usageStatsService.getAllPkgUsageStats();
1567            if (allPkgUsageStats == null) {
1568                return new HashMap<String, Integer>();
1569            }
1570
1571            Map<String, Integer> launchCounts = new HashMap<String, Integer>();
1572            for (PkgUsageStats pkgUsageStats : allPkgUsageStats) {
1573                launchCounts.put(pkgUsageStats.packageName, pkgUsageStats.launchCount);
1574            }
1575
1576            return launchCounts;
1577        } catch (RemoteException e) {
1578            Log.w(TAG, "Could not query launch counts", e);
1579            return new HashMap<String, Integer>();
1580        }
1581    }
1582
1583    /**
1584     * Returns the usage statistics of each installed package.
1585     *
1586     * @hide
1587     */
1588    public PkgUsageStats[] getAllPackageUsageStats() {
1589        try {
1590            IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
1591                    ServiceManager.getService("usagestats"));
1592            if (usageStatsService != null) {
1593                return usageStatsService.getAllPkgUsageStats();
1594            }
1595        } catch (RemoteException e) {
1596            Log.w(TAG, "Could not query usage stats", e);
1597        }
1598        return new PkgUsageStats[0];
1599    }
1600
1601    /**
1602     * @param userid the user's id. Zero indicates the default user
1603     * @hide
1604     */
1605    public boolean switchUser(int userid) {
1606        try {
1607            return ActivityManagerNative.getDefault().switchUser(userid);
1608        } catch (RemoteException e) {
1609            return false;
1610        }
1611    }
1612
1613}
1614