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