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