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