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