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.Manifest;
     20 import android.annotation.NonNull;
     21 import android.annotation.Nullable;
     22 import android.annotation.RequiresPermission;
     23 import android.annotation.SystemApi;
     24 import android.graphics.Canvas;
     25 import android.graphics.Matrix;
     26 import android.graphics.Point;
     27 import android.os.BatteryStats;
     28 import android.os.IBinder;
     29 import android.os.ParcelFileDescriptor;
     30 
     31 import android.util.Log;
     32 import com.android.internal.app.ProcessStats;
     33 import com.android.internal.os.TransferPipe;
     34 import com.android.internal.util.FastPrintWriter;
     35 
     36 import android.content.ComponentName;
     37 import android.content.Context;
     38 import android.content.Intent;
     39 import android.content.pm.ApplicationInfo;
     40 import android.content.pm.ConfigurationInfo;
     41 import android.content.pm.IPackageDataObserver;
     42 import android.content.pm.PackageManager;
     43 import android.content.pm.UserInfo;
     44 import android.content.res.Resources;
     45 import android.graphics.Bitmap;
     46 import android.graphics.Color;
     47 import android.graphics.Rect;
     48 import android.os.Bundle;
     49 import android.os.Debug;
     50 import android.os.Handler;
     51 import android.os.Parcel;
     52 import android.os.Parcelable;
     53 import android.os.Process;
     54 import android.os.RemoteException;
     55 import android.os.ServiceManager;
     56 import android.os.SystemProperties;
     57 import android.os.UserHandle;
     58 import android.text.TextUtils;
     59 import android.util.DisplayMetrics;
     60 import android.util.Size;
     61 import android.util.Slog;
     62 import org.xmlpull.v1.XmlSerializer;
     63 
     64 import java.io.FileDescriptor;
     65 import java.io.FileOutputStream;
     66 import java.io.IOException;
     67 import java.io.PrintWriter;
     68 import java.util.ArrayList;
     69 import java.util.List;
     70 
     71 /**
     72  * Interact with the overall activities running in the system.
     73  */
     74 public class ActivityManager {
     75     private static String TAG = "ActivityManager";
     76     private static boolean localLOGV = false;
     77 
     78     private static int gMaxRecentTasks = -1;
     79 
     80     private final Context mContext;
     81     private final Handler mHandler;
     82 
     83     /**
     84      * <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">{@code
     85      * &lt;meta-data>}</a> name for a 'home' Activity that declares a package that is to be
     86      * uninstalled in lieu of the declaring one.  The package named here must be
     87      * signed with the same certificate as the one declaring the {@code &lt;meta-data>}.
     88      */
     89     public static final String META_HOME_ALTERNATE = "android.app.home.alternate";
     90 
     91     /**
     92      * Result for IActivityManager.startActivity: trying to start a background user
     93      * activity that shouldn't be displayed for all users.
     94      * @hide
     95      */
     96     public static final int START_NOT_CURRENT_USER_ACTIVITY = -8;
     97 
     98     /**
     99      * Result for IActivityManager.startActivity: trying to start an activity under voice
    100      * control when that activity does not support the VOICE category.
    101      * @hide
    102      */
    103     public static final int START_NOT_VOICE_COMPATIBLE = -7;
    104 
    105     /**
    106      * Result for IActivityManager.startActivity: an error where the
    107      * start had to be canceled.
    108      * @hide
    109      */
    110     public static final int START_CANCELED = -6;
    111 
    112     /**
    113      * Result for IActivityManager.startActivity: an error where the
    114      * thing being started is not an activity.
    115      * @hide
    116      */
    117     public static final int START_NOT_ACTIVITY = -5;
    118 
    119     /**
    120      * Result for IActivityManager.startActivity: an error where the
    121      * caller does not have permission to start the activity.
    122      * @hide
    123      */
    124     public static final int START_PERMISSION_DENIED = -4;
    125 
    126     /**
    127      * Result for IActivityManager.startActivity: an error where the
    128      * caller has requested both to forward a result and to receive
    129      * a result.
    130      * @hide
    131      */
    132     public static final int START_FORWARD_AND_REQUEST_CONFLICT = -3;
    133 
    134     /**
    135      * Result for IActivityManager.startActivity: an error where the
    136      * requested class is not found.
    137      * @hide
    138      */
    139     public static final int START_CLASS_NOT_FOUND = -2;
    140 
    141     /**
    142      * Result for IActivityManager.startActivity: an error where the
    143      * given Intent could not be resolved to an activity.
    144      * @hide
    145      */
    146     public static final int START_INTENT_NOT_RESOLVED = -1;
    147 
    148     /**
    149      * Result for IActivityManaqer.startActivity: the activity was started
    150      * successfully as normal.
    151      * @hide
    152      */
    153     public static final int START_SUCCESS = 0;
    154 
    155     /**
    156      * Result for IActivityManaqer.startActivity: the caller asked that the Intent not
    157      * be executed if it is the recipient, and that is indeed the case.
    158      * @hide
    159      */
    160     public static final int START_RETURN_INTENT_TO_CALLER = 1;
    161 
    162     /**
    163      * Result for IActivityManaqer.startActivity: activity wasn't really started, but
    164      * a task was simply brought to the foreground.
    165      * @hide
    166      */
    167     public static final int START_TASK_TO_FRONT = 2;
    168 
    169     /**
    170      * Result for IActivityManaqer.startActivity: activity wasn't really started, but
    171      * the given Intent was given to the existing top activity.
    172      * @hide
    173      */
    174     public static final int START_DELIVERED_TO_TOP = 3;
    175 
    176     /**
    177      * Result for IActivityManaqer.startActivity: request was canceled because
    178      * app switches are temporarily canceled to ensure the user's last request
    179      * (such as pressing home) is performed.
    180      * @hide
    181      */
    182     public static final int START_SWITCHES_CANCELED = 4;
    183 
    184     /**
    185      * Result for IActivityManaqer.startActivity: a new activity was attempted to be started
    186      * while in Lock Task Mode.
    187      * @hide
    188      */
    189     public static final int START_RETURN_LOCK_TASK_MODE_VIOLATION = 5;
    190 
    191     /**
    192      * Flag for IActivityManaqer.startActivity: do special start mode where
    193      * a new activity is launched only if it is needed.
    194      * @hide
    195      */
    196     public static final int START_FLAG_ONLY_IF_NEEDED = 1<<0;
    197 
    198     /**
    199      * Flag for IActivityManaqer.startActivity: launch the app for
    200      * debugging.
    201      * @hide
    202      */
    203     public static final int START_FLAG_DEBUG = 1<<1;
    204 
    205     /**
    206      * Flag for IActivityManaqer.startActivity: launch the app for
    207      * OpenGL tracing.
    208      * @hide
    209      */
    210     public static final int START_FLAG_OPENGL_TRACES = 1<<2;
    211 
    212     /**
    213      * Result for IActivityManaqer.broadcastIntent: success!
    214      * @hide
    215      */
    216     public static final int BROADCAST_SUCCESS = 0;
    217 
    218     /**
    219      * Result for IActivityManaqer.broadcastIntent: attempt to broadcast
    220      * a sticky intent without appropriate permission.
    221      * @hide
    222      */
    223     public static final int BROADCAST_STICKY_CANT_HAVE_PERMISSION = -1;
    224 
    225     /**
    226      * Result for IActivityManager.broadcastIntent: trying to send a broadcast
    227      * to a stopped user. Fail.
    228      * @hide
    229      */
    230     public static final int BROADCAST_FAILED_USER_STOPPED = -2;
    231 
    232     /**
    233      * Type for IActivityManaqer.getIntentSender: this PendingIntent is
    234      * for a sendBroadcast operation.
    235      * @hide
    236      */
    237     public static final int INTENT_SENDER_BROADCAST = 1;
    238 
    239     /**
    240      * Type for IActivityManaqer.getIntentSender: this PendingIntent is
    241      * for a startActivity operation.
    242      * @hide
    243      */
    244     public static final int INTENT_SENDER_ACTIVITY = 2;
    245 
    246     /**
    247      * Type for IActivityManaqer.getIntentSender: this PendingIntent is
    248      * for an activity result operation.
    249      * @hide
    250      */
    251     public static final int INTENT_SENDER_ACTIVITY_RESULT = 3;
    252 
    253     /**
    254      * Type for IActivityManaqer.getIntentSender: this PendingIntent is
    255      * for a startService operation.
    256      * @hide
    257      */
    258     public static final int INTENT_SENDER_SERVICE = 4;
    259 
    260     /** @hide User operation call: success! */
    261     public static final int USER_OP_SUCCESS = 0;
    262 
    263     /** @hide User operation call: given user id is not known. */
    264     public static final int USER_OP_UNKNOWN_USER = -1;
    265 
    266     /** @hide User operation call: given user id is the current user, can't be stopped. */
    267     public static final int USER_OP_IS_CURRENT = -2;
    268 
    269     /** @hide Process does not exist. */
    270     public static final int PROCESS_STATE_NONEXISTENT = -1;
    271 
    272     /** @hide Process is a persistent system process. */
    273     public static final int PROCESS_STATE_PERSISTENT = 0;
    274 
    275     /** @hide Process is a persistent system process and is doing UI. */
    276     public static final int PROCESS_STATE_PERSISTENT_UI = 1;
    277 
    278     /** @hide Process is hosting the current top activities.  Note that this covers
    279      * all activities that are visible to the user. */
    280     public static final int PROCESS_STATE_TOP = 2;
    281 
    282     /** @hide Process is hosting a foreground service due to a system binding. */
    283     public static final int PROCESS_STATE_BOUND_FOREGROUND_SERVICE = 3;
    284 
    285     /** @hide Process is hosting a foreground service. */
    286     public static final int PROCESS_STATE_FOREGROUND_SERVICE = 4;
    287 
    288     /** @hide Same as {@link #PROCESS_STATE_TOP} but while device is sleeping. */
    289     public static final int PROCESS_STATE_TOP_SLEEPING = 5;
    290 
    291     /** @hide Process is important to the user, and something they are aware of. */
    292     public static final int PROCESS_STATE_IMPORTANT_FOREGROUND = 6;
    293 
    294     /** @hide Process is important to the user, but not something they are aware of. */
    295     public static final int PROCESS_STATE_IMPORTANT_BACKGROUND = 7;
    296 
    297     /** @hide Process is in the background running a backup/restore operation. */
    298     public static final int PROCESS_STATE_BACKUP = 8;
    299 
    300     /** @hide Process is in the background, but it can't restore its state so we want
    301      * to try to avoid killing it. */
    302     public static final int PROCESS_STATE_HEAVY_WEIGHT = 9;
    303 
    304     /** @hide Process is in the background running a service.  Unlike oom_adj, this level
    305      * is used for both the normal running in background state and the executing
    306      * operations state. */
    307     public static final int PROCESS_STATE_SERVICE = 10;
    308 
    309     /** @hide Process is in the background running a receiver.   Note that from the
    310      * perspective of oom_adj receivers run at a higher foreground level, but for our
    311      * prioritization here that is not necessary and putting them below services means
    312      * many fewer changes in some process states as they receive broadcasts. */
    313     public static final int PROCESS_STATE_RECEIVER = 11;
    314 
    315     /** @hide Process is in the background but hosts the home activity. */
    316     public static final int PROCESS_STATE_HOME = 12;
    317 
    318     /** @hide Process is in the background but hosts the last shown activity. */
    319     public static final int PROCESS_STATE_LAST_ACTIVITY = 13;
    320 
    321     /** @hide Process is being cached for later use and contains activities. */
    322     public static final int PROCESS_STATE_CACHED_ACTIVITY = 14;
    323 
    324     /** @hide Process is being cached for later use and is a client of another cached
    325      * process that contains activities. */
    326     public static final int PROCESS_STATE_CACHED_ACTIVITY_CLIENT = 15;
    327 
    328     /** @hide Process is being cached for later use and is empty. */
    329     public static final int PROCESS_STATE_CACHED_EMPTY = 16;
    330 
    331     /** @hide requestType for assist context: only basic information. */
    332     public static final int ASSIST_CONTEXT_BASIC = 0;
    333 
    334     /** @hide requestType for assist context: generate full AssistStructure. */
    335     public static final int ASSIST_CONTEXT_FULL = 1;
    336 
    337     /**
    338      * Lock task mode is not active.
    339      */
    340     public static final int LOCK_TASK_MODE_NONE = 0;
    341 
    342     /**
    343      * Full lock task mode is active.
    344      */
    345     public static final int LOCK_TASK_MODE_LOCKED = 1;
    346 
    347     /**
    348      * App pinning mode is active.
    349      */
    350     public static final int LOCK_TASK_MODE_PINNED = 2;
    351 
    352     Point mAppTaskThumbnailSize;
    353 
    354     /*package*/ ActivityManager(Context context, Handler handler) {
    355         mContext = context;
    356         mHandler = handler;
    357     }
    358 
    359     /**
    360      * Screen compatibility mode: the application most always run in
    361      * compatibility mode.
    362      * @hide
    363      */
    364     public static final int COMPAT_MODE_ALWAYS = -1;
    365 
    366     /**
    367      * Screen compatibility mode: the application can never run in
    368      * compatibility mode.
    369      * @hide
    370      */
    371     public static final int COMPAT_MODE_NEVER = -2;
    372 
    373     /**
    374      * Screen compatibility mode: unknown.
    375      * @hide
    376      */
    377     public static final int COMPAT_MODE_UNKNOWN = -3;
    378 
    379     /**
    380      * Screen compatibility mode: the application currently has compatibility
    381      * mode disabled.
    382      * @hide
    383      */
    384     public static final int COMPAT_MODE_DISABLED = 0;
    385 
    386     /**
    387      * Screen compatibility mode: the application currently has compatibility
    388      * mode enabled.
    389      * @hide
    390      */
    391     public static final int COMPAT_MODE_ENABLED = 1;
    392 
    393     /**
    394      * Screen compatibility mode: request to toggle the application's
    395      * compatibility mode.
    396      * @hide
    397      */
    398     public static final int COMPAT_MODE_TOGGLE = 2;
    399 
    400     /** @hide */
    401     public int getFrontActivityScreenCompatMode() {
    402         try {
    403             return ActivityManagerNative.getDefault().getFrontActivityScreenCompatMode();
    404         } catch (RemoteException e) {
    405             // System dead, we will be dead too soon!
    406             return 0;
    407         }
    408     }
    409 
    410     /** @hide */
    411     public void setFrontActivityScreenCompatMode(int mode) {
    412         try {
    413             ActivityManagerNative.getDefault().setFrontActivityScreenCompatMode(mode);
    414         } catch (RemoteException e) {
    415             // System dead, we will be dead too soon!
    416         }
    417     }
    418 
    419     /** @hide */
    420     public int getPackageScreenCompatMode(String packageName) {
    421         try {
    422             return ActivityManagerNative.getDefault().getPackageScreenCompatMode(packageName);
    423         } catch (RemoteException e) {
    424             // System dead, we will be dead too soon!
    425             return 0;
    426         }
    427     }
    428 
    429     /** @hide */
    430     public void setPackageScreenCompatMode(String packageName, int mode) {
    431         try {
    432             ActivityManagerNative.getDefault().setPackageScreenCompatMode(packageName, mode);
    433         } catch (RemoteException e) {
    434             // System dead, we will be dead too soon!
    435         }
    436     }
    437 
    438     /** @hide */
    439     public boolean getPackageAskScreenCompat(String packageName) {
    440         try {
    441             return ActivityManagerNative.getDefault().getPackageAskScreenCompat(packageName);
    442         } catch (RemoteException e) {
    443             // System dead, we will be dead too soon!
    444             return false;
    445         }
    446     }
    447 
    448     /** @hide */
    449     public void setPackageAskScreenCompat(String packageName, boolean ask) {
    450         try {
    451             ActivityManagerNative.getDefault().setPackageAskScreenCompat(packageName, ask);
    452         } catch (RemoteException e) {
    453             // System dead, we will be dead too soon!
    454         }
    455     }
    456 
    457     /**
    458      * Return the approximate per-application memory class of the current
    459      * device.  This gives you an idea of how hard a memory limit you should
    460      * impose on your application to let the overall system work best.  The
    461      * returned value is in megabytes; the baseline Android memory class is
    462      * 16 (which happens to be the Java heap limit of those devices); some
    463      * device with more memory may return 24 or even higher numbers.
    464      */
    465     public int getMemoryClass() {
    466         return staticGetMemoryClass();
    467     }
    468 
    469     /** @hide */
    470     static public int staticGetMemoryClass() {
    471         // Really brain dead right now -- just take this from the configured
    472         // vm heap size, and assume it is in megabytes and thus ends with "m".
    473         String vmHeapSize = SystemProperties.get("dalvik.vm.heapgrowthlimit", "");
    474         if (vmHeapSize != null && !"".equals(vmHeapSize)) {
    475             return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length()-1));
    476         }
    477         return staticGetLargeMemoryClass();
    478     }
    479 
    480     /**
    481      * Return the approximate per-application memory class of the current
    482      * device when an application is running with a large heap.  This is the
    483      * space available for memory-intensive applications; most applications
    484      * should not need this amount of memory, and should instead stay with the
    485      * {@link #getMemoryClass()} limit.  The returned value is in megabytes.
    486      * This may be the same size as {@link #getMemoryClass()} on memory
    487      * constrained devices, or it may be significantly larger on devices with
    488      * a large amount of available RAM.
    489      *
    490      * <p>The is the size of the application's Dalvik heap if it has
    491      * specified <code>android:largeHeap="true"</code> in its manifest.
    492      */
    493     public int getLargeMemoryClass() {
    494         return staticGetLargeMemoryClass();
    495     }
    496 
    497     /** @hide */
    498     static public int staticGetLargeMemoryClass() {
    499         // Really brain dead right now -- just take this from the configured
    500         // vm heap size, and assume it is in megabytes and thus ends with "m".
    501         String vmHeapSize = SystemProperties.get("dalvik.vm.heapsize", "16m");
    502         return Integer.parseInt(vmHeapSize.substring(0, vmHeapSize.length() - 1));
    503     }
    504 
    505     /**
    506      * Returns true if this is a low-RAM device.  Exactly whether a device is low-RAM
    507      * is ultimately up to the device configuration, but currently it generally means
    508      * something in the class of a 512MB device with about a 800x480 or less screen.
    509      * This is mostly intended to be used by apps to determine whether they should turn
    510      * off certain features that require more RAM.
    511      */
    512     public boolean isLowRamDevice() {
    513         return isLowRamDeviceStatic();
    514     }
    515 
    516     /** @hide */
    517     public static boolean isLowRamDeviceStatic() {
    518         return "true".equals(SystemProperties.get("ro.config.low_ram", "false"));
    519     }
    520 
    521     /**
    522      * Used by persistent processes to determine if they are running on a
    523      * higher-end device so should be okay using hardware drawing acceleration
    524      * (which tends to consume a lot more RAM).
    525      * @hide
    526      */
    527     static public boolean isHighEndGfx() {
    528         return !isLowRamDeviceStatic() &&
    529                 !Resources.getSystem().getBoolean(com.android.internal.R.bool.config_avoidGfxAccel);
    530     }
    531 
    532     /**
    533      * Return the maximum number of recents entries that we will maintain and show.
    534      * @hide
    535      */
    536     static public int getMaxRecentTasksStatic() {
    537         if (gMaxRecentTasks < 0) {
    538             return gMaxRecentTasks = isLowRamDeviceStatic() ? 50 : 100;
    539         }
    540         return gMaxRecentTasks;
    541     }
    542 
    543     /**
    544      * Return the default limit on the number of recents that an app can make.
    545      * @hide
    546      */
    547     static public int getDefaultAppRecentsLimitStatic() {
    548         return getMaxRecentTasksStatic() / 6;
    549     }
    550 
    551     /**
    552      * Return the maximum limit on the number of recents that an app can make.
    553      * @hide
    554      */
    555     static public int getMaxAppRecentsLimitStatic() {
    556         return getMaxRecentTasksStatic() / 2;
    557     }
    558 
    559     /**
    560      * Information you can set and retrieve about the current activity within the recent task list.
    561      */
    562     public static class TaskDescription implements Parcelable {
    563         /** @hide */
    564         public static final String ATTR_TASKDESCRIPTION_PREFIX = "task_description_";
    565         private static final String ATTR_TASKDESCRIPTIONLABEL =
    566                 ATTR_TASKDESCRIPTION_PREFIX + "label";
    567         private static final String ATTR_TASKDESCRIPTIONCOLOR =
    568                 ATTR_TASKDESCRIPTION_PREFIX + "color";
    569         private static final String ATTR_TASKDESCRIPTIONICONFILENAME =
    570                 ATTR_TASKDESCRIPTION_PREFIX + "icon_filename";
    571 
    572         private String mLabel;
    573         private Bitmap mIcon;
    574         private String mIconFilename;
    575         private int mColorPrimary;
    576 
    577         /**
    578          * Creates the TaskDescription to the specified values.
    579          *
    580          * @param label A label and description of the current state of this task.
    581          * @param icon An icon that represents the current state of this task.
    582          * @param colorPrimary A color to override the theme's primary color.  This color must be opaque.
    583          */
    584         public TaskDescription(String label, Bitmap icon, int colorPrimary) {
    585             if ((colorPrimary != 0) && (Color.alpha(colorPrimary) != 255)) {
    586                 throw new RuntimeException("A TaskDescription's primary color should be opaque");
    587             }
    588 
    589             mLabel = label;
    590             mIcon = icon;
    591             mColorPrimary = colorPrimary;
    592         }
    593 
    594         /** @hide */
    595         public TaskDescription(String label, int colorPrimary, String iconFilename) {
    596             this(label, null, colorPrimary);
    597             mIconFilename = iconFilename;
    598         }
    599 
    600         /**
    601          * Creates the TaskDescription to the specified values.
    602          *
    603          * @param label A label and description of the current state of this activity.
    604          * @param icon An icon that represents the current state of this activity.
    605          */
    606         public TaskDescription(String label, Bitmap icon) {
    607             this(label, icon, 0);
    608         }
    609 
    610         /**
    611          * Creates the TaskDescription to the specified values.
    612          *
    613          * @param label A label and description of the current state of this activity.
    614          */
    615         public TaskDescription(String label) {
    616             this(label, null, 0);
    617         }
    618 
    619         /**
    620          * Creates an empty TaskDescription.
    621          */
    622         public TaskDescription() {
    623             this(null, null, 0);
    624         }
    625 
    626         /**
    627          * Creates a copy of another TaskDescription.
    628          */
    629         public TaskDescription(TaskDescription td) {
    630             mLabel = td.mLabel;
    631             mIcon = td.mIcon;
    632             mColorPrimary = td.mColorPrimary;
    633             mIconFilename = td.mIconFilename;
    634         }
    635 
    636         private TaskDescription(Parcel source) {
    637             readFromParcel(source);
    638         }
    639 
    640         /**
    641          * Sets the label for this task description.
    642          * @hide
    643          */
    644         public void setLabel(String label) {
    645             mLabel = label;
    646         }
    647 
    648         /**
    649          * Sets the primary color for this task description.
    650          * @hide
    651          */
    652         public void setPrimaryColor(int primaryColor) {
    653             // Ensure that the given color is valid
    654             if ((primaryColor != 0) && (Color.alpha(primaryColor) != 255)) {
    655                 throw new RuntimeException("A TaskDescription's primary color should be opaque");
    656             }
    657             mColorPrimary = primaryColor;
    658         }
    659 
    660         /**
    661          * Sets the icon for this task description.
    662          * @hide
    663          */
    664         public void setIcon(Bitmap icon) {
    665             mIcon = icon;
    666         }
    667 
    668         /**
    669          * Moves the icon bitmap reference from an actual Bitmap to a file containing the
    670          * bitmap.
    671          * @hide
    672          */
    673         public void setIconFilename(String iconFilename) {
    674             mIconFilename = iconFilename;
    675             mIcon = null;
    676         }
    677 
    678         /**
    679          * @return The label and description of the current state of this task.
    680          */
    681         public String getLabel() {
    682             return mLabel;
    683         }
    684 
    685         /**
    686          * @return The icon that represents the current state of this task.
    687          */
    688         public Bitmap getIcon() {
    689             if (mIcon != null) {
    690                 return mIcon;
    691             }
    692             return loadTaskDescriptionIcon(mIconFilename);
    693         }
    694 
    695         /** @hide */
    696         public String getIconFilename() {
    697             return mIconFilename;
    698         }
    699 
    700         /** @hide */
    701         public Bitmap getInMemoryIcon() {
    702             return mIcon;
    703         }
    704 
    705         /** @hide */
    706         public static Bitmap loadTaskDescriptionIcon(String iconFilename) {
    707             if (iconFilename != null) {
    708                 try {
    709                     return ActivityManagerNative.getDefault().
    710                             getTaskDescriptionIcon(iconFilename);
    711                 } catch (RemoteException e) {
    712                 }
    713             }
    714             return null;
    715         }
    716 
    717         /**
    718          * @return The color override on the theme's primary color.
    719          */
    720         public int getPrimaryColor() {
    721             return mColorPrimary;
    722         }
    723 
    724         /** @hide */
    725         public void saveToXml(XmlSerializer out) throws IOException {
    726             if (mLabel != null) {
    727                 out.attribute(null, ATTR_TASKDESCRIPTIONLABEL, mLabel);
    728             }
    729             if (mColorPrimary != 0) {
    730                 out.attribute(null, ATTR_TASKDESCRIPTIONCOLOR, Integer.toHexString(mColorPrimary));
    731             }
    732             if (mIconFilename != null) {
    733                 out.attribute(null, ATTR_TASKDESCRIPTIONICONFILENAME, mIconFilename);
    734             }
    735         }
    736 
    737         /** @hide */
    738         public void restoreFromXml(String attrName, String attrValue) {
    739             if (ATTR_TASKDESCRIPTIONLABEL.equals(attrName)) {
    740                 setLabel(attrValue);
    741             } else if (ATTR_TASKDESCRIPTIONCOLOR.equals(attrName)) {
    742                 setPrimaryColor((int) Long.parseLong(attrValue, 16));
    743             } else if (ATTR_TASKDESCRIPTIONICONFILENAME.equals(attrName)) {
    744                 setIconFilename(attrValue);
    745             }
    746         }
    747 
    748         @Override
    749         public int describeContents() {
    750             return 0;
    751         }
    752 
    753         @Override
    754         public void writeToParcel(Parcel dest, int flags) {
    755             if (mLabel == null) {
    756                 dest.writeInt(0);
    757             } else {
    758                 dest.writeInt(1);
    759                 dest.writeString(mLabel);
    760             }
    761             if (mIcon == null) {
    762                 dest.writeInt(0);
    763             } else {
    764                 dest.writeInt(1);
    765                 mIcon.writeToParcel(dest, 0);
    766             }
    767             dest.writeInt(mColorPrimary);
    768             if (mIconFilename == null) {
    769                 dest.writeInt(0);
    770             } else {
    771                 dest.writeInt(1);
    772                 dest.writeString(mIconFilename);
    773             }
    774         }
    775 
    776         public void readFromParcel(Parcel source) {
    777             mLabel = source.readInt() > 0 ? source.readString() : null;
    778             mIcon = source.readInt() > 0 ? Bitmap.CREATOR.createFromParcel(source) : null;
    779             mColorPrimary = source.readInt();
    780             mIconFilename = source.readInt() > 0 ? source.readString() : null;
    781         }
    782 
    783         public static final Creator<TaskDescription> CREATOR
    784                 = new Creator<TaskDescription>() {
    785             public TaskDescription createFromParcel(Parcel source) {
    786                 return new TaskDescription(source);
    787             }
    788             public TaskDescription[] newArray(int size) {
    789                 return new TaskDescription[size];
    790             }
    791         };
    792 
    793         @Override
    794         public String toString() {
    795             return "TaskDescription Label: " + mLabel + " Icon: " + mIcon +
    796                     " colorPrimary: " + mColorPrimary;
    797         }
    798     }
    799 
    800     /**
    801      * Information you can retrieve about tasks that the user has most recently
    802      * started or visited.
    803      */
    804     public static class RecentTaskInfo implements Parcelable {
    805         /**
    806          * If this task is currently running, this is the identifier for it.
    807          * If it is not running, this will be -1.
    808          */
    809         public int id;
    810 
    811         /**
    812          * The true identifier of this task, valid even if it is not running.
    813          */
    814         public int persistentId;
    815 
    816         /**
    817          * The original Intent used to launch the task.  You can use this
    818          * Intent to re-launch the task (if it is no longer running) or bring
    819          * the current task to the front.
    820          */
    821         public Intent baseIntent;
    822 
    823         /**
    824          * If this task was started from an alias, this is the actual
    825          * activity component that was initially started; the component of
    826          * the baseIntent in this case is the name of the actual activity
    827          * implementation that the alias referred to.  Otherwise, this is null.
    828          */
    829         public ComponentName origActivity;
    830 
    831         /**
    832          * Description of the task's last state.
    833          */
    834         public CharSequence description;
    835 
    836         /**
    837          * The id of the ActivityStack this Task was on most recently.
    838          * @hide
    839          */
    840         public int stackId;
    841 
    842         /**
    843          * The id of the user the task was running as.
    844          * @hide
    845          */
    846         public int userId;
    847 
    848         /**
    849          * The first time this task was active.
    850          * @hide
    851          */
    852         public long firstActiveTime;
    853 
    854         /**
    855          * The last time this task was active.
    856          * @hide
    857          */
    858         public long lastActiveTime;
    859 
    860         /**
    861          * The recent activity values for the highest activity in the stack to have set the values.
    862          * {@link Activity#setTaskDescription(android.app.ActivityManager.TaskDescription)}.
    863          */
    864         public TaskDescription taskDescription;
    865 
    866         /**
    867          * Task affiliation for grouping with other tasks.
    868          */
    869         public int affiliatedTaskId;
    870 
    871         /**
    872          * Task affiliation color of the source task with the affiliated task id.
    873          *
    874          * @hide
    875          */
    876         public int affiliatedTaskColor;
    877 
    878         /**
    879          * The component launched as the first activity in the task.
    880          * This can be considered the "application" of this task.
    881          */
    882         public ComponentName baseActivity;
    883 
    884         /**
    885          * The activity component at the top of the history stack of the task.
    886          * This is what the user is currently doing.
    887          */
    888         public ComponentName topActivity;
    889 
    890         /**
    891          * Number of activities in this task.
    892          */
    893         public int numActivities;
    894 
    895         public RecentTaskInfo() {
    896         }
    897 
    898         @Override
    899         public int describeContents() {
    900             return 0;
    901         }
    902 
    903         @Override
    904         public void writeToParcel(Parcel dest, int flags) {
    905             dest.writeInt(id);
    906             dest.writeInt(persistentId);
    907             if (baseIntent != null) {
    908                 dest.writeInt(1);
    909                 baseIntent.writeToParcel(dest, 0);
    910             } else {
    911                 dest.writeInt(0);
    912             }
    913             ComponentName.writeToParcel(origActivity, dest);
    914             TextUtils.writeToParcel(description, dest,
    915                     Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
    916             if (taskDescription != null) {
    917                 dest.writeInt(1);
    918                 taskDescription.writeToParcel(dest, 0);
    919             } else {
    920                 dest.writeInt(0);
    921             }
    922             dest.writeInt(stackId);
    923             dest.writeInt(userId);
    924             dest.writeLong(firstActiveTime);
    925             dest.writeLong(lastActiveTime);
    926             dest.writeInt(affiliatedTaskId);
    927             dest.writeInt(affiliatedTaskColor);
    928             ComponentName.writeToParcel(baseActivity, dest);
    929             ComponentName.writeToParcel(topActivity, dest);
    930             dest.writeInt(numActivities);
    931         }
    932 
    933         public void readFromParcel(Parcel source) {
    934             id = source.readInt();
    935             persistentId = source.readInt();
    936             baseIntent = source.readInt() > 0 ? Intent.CREATOR.createFromParcel(source) : null;
    937             origActivity = ComponentName.readFromParcel(source);
    938             description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
    939             taskDescription = source.readInt() > 0 ?
    940                     TaskDescription.CREATOR.createFromParcel(source) : null;
    941             stackId = source.readInt();
    942             userId = source.readInt();
    943             firstActiveTime = source.readLong();
    944             lastActiveTime = source.readLong();
    945             affiliatedTaskId = source.readInt();
    946             affiliatedTaskColor = source.readInt();
    947             baseActivity = ComponentName.readFromParcel(source);
    948             topActivity = ComponentName.readFromParcel(source);
    949             numActivities = source.readInt();
    950         }
    951 
    952         public static final Creator<RecentTaskInfo> CREATOR
    953                 = new Creator<RecentTaskInfo>() {
    954             public RecentTaskInfo createFromParcel(Parcel source) {
    955                 return new RecentTaskInfo(source);
    956             }
    957             public RecentTaskInfo[] newArray(int size) {
    958                 return new RecentTaskInfo[size];
    959             }
    960         };
    961 
    962         private RecentTaskInfo(Parcel source) {
    963             readFromParcel(source);
    964         }
    965     }
    966 
    967     /**
    968      * Flag for use with {@link #getRecentTasks}: return all tasks, even those
    969      * that have set their
    970      * {@link android.content.Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag.
    971      */
    972     public static final int RECENT_WITH_EXCLUDED = 0x0001;
    973 
    974     /**
    975      * Provides a list that does not contain any
    976      * recent tasks that currently are not available to the user.
    977      */
    978     public static final int RECENT_IGNORE_UNAVAILABLE = 0x0002;
    979 
    980     /**
    981      * Provides a list that contains recent tasks for all
    982      * profiles of a user.
    983      * @hide
    984      */
    985     public static final int RECENT_INCLUDE_PROFILES = 0x0004;
    986 
    987     /**
    988      * Ignores all tasks that are on the home stack.
    989      * @hide
    990      */
    991     public static final int RECENT_IGNORE_HOME_STACK_TASKS = 0x0008;
    992 
    993     /**
    994      * <p></p>Return a list of the tasks that the user has recently launched, with
    995      * the most recent being first and older ones after in order.
    996      *
    997      * <p><b>Note: this method is only intended for debugging and presenting
    998      * task management user interfaces</b>.  This should never be used for
    999      * core logic in an application, such as deciding between different
   1000      * behaviors based on the information found here.  Such uses are
   1001      * <em>not</em> supported, and will likely break in the future.  For
   1002      * example, if multiple applications can be actively running at the
   1003      * same time, assumptions made about the meaning of the data here for
   1004      * purposes of control flow will be incorrect.</p>
   1005      *
   1006      * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method is
   1007      * no longer available to third party applications: the introduction of
   1008      * document-centric recents means
   1009      * it can leak personal information to the caller.  For backwards compatibility,
   1010      * it will still return a small subset of its data: at least the caller's
   1011      * own tasks (though see {@link #getAppTasks()} for the correct supported
   1012      * way to retrieve that information), and possibly some other tasks
   1013      * such as home that are known to not be sensitive.
   1014      *
   1015      * @param maxNum The maximum number of entries to return in the list.  The
   1016      * actual number returned may be smaller, depending on how many tasks the
   1017      * user has started and the maximum number the system can remember.
   1018      * @param flags Information about what to return.  May be any combination
   1019      * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
   1020      *
   1021      * @return Returns a list of RecentTaskInfo records describing each of
   1022      * the recent tasks.
   1023      */
   1024     @Deprecated
   1025     public List<RecentTaskInfo> getRecentTasks(int maxNum, int flags)
   1026             throws SecurityException {
   1027         try {
   1028             return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
   1029                     flags, UserHandle.myUserId());
   1030         } catch (RemoteException e) {
   1031             // System dead, we will be dead too soon!
   1032             return null;
   1033         }
   1034     }
   1035 
   1036     /**
   1037      * Same as {@link #getRecentTasks(int, int)} but returns the recent tasks for a
   1038      * specific user. It requires holding
   1039      * the {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
   1040      * @param maxNum The maximum number of entries to return in the list.  The
   1041      * actual number returned may be smaller, depending on how many tasks the
   1042      * user has started and the maximum number the system can remember.
   1043      * @param flags Information about what to return.  May be any combination
   1044      * of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
   1045      *
   1046      * @return Returns a list of RecentTaskInfo records describing each of
   1047      * the recent tasks.
   1048      *
   1049      * @hide
   1050      */
   1051     public List<RecentTaskInfo> getRecentTasksForUser(int maxNum, int flags, int userId)
   1052             throws SecurityException {
   1053         try {
   1054             return ActivityManagerNative.getDefault().getRecentTasks(maxNum,
   1055                     flags, userId);
   1056         } catch (RemoteException e) {
   1057             // System dead, we will be dead too soon!
   1058             return null;
   1059         }
   1060     }
   1061 
   1062     /**
   1063      * Information you can retrieve about a particular task that is currently
   1064      * "running" in the system.  Note that a running task does not mean the
   1065      * given task actually has a process it is actively running in; it simply
   1066      * means that the user has gone to it and never closed it, but currently
   1067      * the system may have killed its process and is only holding on to its
   1068      * last state in order to restart it when the user returns.
   1069      */
   1070     public static class RunningTaskInfo implements Parcelable {
   1071         /**
   1072          * A unique identifier for this task.
   1073          */
   1074         public int id;
   1075 
   1076         /**
   1077          * The component launched as the first activity in the task.  This can
   1078          * be considered the "application" of this task.
   1079          */
   1080         public ComponentName baseActivity;
   1081 
   1082         /**
   1083          * The activity component at the top of the history stack of the task.
   1084          * This is what the user is currently doing.
   1085          */
   1086         public ComponentName topActivity;
   1087 
   1088         /**
   1089          * Thumbnail representation of the task's current state.  Currently
   1090          * always null.
   1091          */
   1092         public Bitmap thumbnail;
   1093 
   1094         /**
   1095          * Description of the task's current state.
   1096          */
   1097         public CharSequence description;
   1098 
   1099         /**
   1100          * Number of activities in this task.
   1101          */
   1102         public int numActivities;
   1103 
   1104         /**
   1105          * Number of activities that are currently running (not stopped
   1106          * and persisted) in this task.
   1107          */
   1108         public int numRunning;
   1109 
   1110         /**
   1111          * Last time task was run. For sorting.
   1112          * @hide
   1113          */
   1114         public long lastActiveTime;
   1115 
   1116         public RunningTaskInfo() {
   1117         }
   1118 
   1119         public int describeContents() {
   1120             return 0;
   1121         }
   1122 
   1123         public void writeToParcel(Parcel dest, int flags) {
   1124             dest.writeInt(id);
   1125             ComponentName.writeToParcel(baseActivity, dest);
   1126             ComponentName.writeToParcel(topActivity, dest);
   1127             if (thumbnail != null) {
   1128                 dest.writeInt(1);
   1129                 thumbnail.writeToParcel(dest, 0);
   1130             } else {
   1131                 dest.writeInt(0);
   1132             }
   1133             TextUtils.writeToParcel(description, dest,
   1134                     Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
   1135             dest.writeInt(numActivities);
   1136             dest.writeInt(numRunning);
   1137         }
   1138 
   1139         public void readFromParcel(Parcel source) {
   1140             id = source.readInt();
   1141             baseActivity = ComponentName.readFromParcel(source);
   1142             topActivity = ComponentName.readFromParcel(source);
   1143             if (source.readInt() != 0) {
   1144                 thumbnail = Bitmap.CREATOR.createFromParcel(source);
   1145             } else {
   1146                 thumbnail = null;
   1147             }
   1148             description = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source);
   1149             numActivities = source.readInt();
   1150             numRunning = source.readInt();
   1151         }
   1152 
   1153         public static final Creator<RunningTaskInfo> CREATOR = new Creator<RunningTaskInfo>() {
   1154             public RunningTaskInfo createFromParcel(Parcel source) {
   1155                 return new RunningTaskInfo(source);
   1156             }
   1157             public RunningTaskInfo[] newArray(int size) {
   1158                 return new RunningTaskInfo[size];
   1159             }
   1160         };
   1161 
   1162         private RunningTaskInfo(Parcel source) {
   1163             readFromParcel(source);
   1164         }
   1165     }
   1166 
   1167     /**
   1168      * Get the list of tasks associated with the calling application.
   1169      *
   1170      * @return The list of tasks associated with the application making this call.
   1171      * @throws SecurityException
   1172      */
   1173     public List<ActivityManager.AppTask> getAppTasks() {
   1174         ArrayList<AppTask> tasks = new ArrayList<AppTask>();
   1175         List<IAppTask> appTasks;
   1176         try {
   1177             appTasks = ActivityManagerNative.getDefault().getAppTasks(mContext.getPackageName());
   1178         } catch (RemoteException e) {
   1179             // System dead, we will be dead too soon!
   1180             return null;
   1181         }
   1182         int numAppTasks = appTasks.size();
   1183         for (int i = 0; i < numAppTasks; i++) {
   1184             tasks.add(new AppTask(appTasks.get(i)));
   1185         }
   1186         return tasks;
   1187     }
   1188 
   1189     /**
   1190      * Return the current design dimensions for {@link AppTask} thumbnails, for use
   1191      * with {@link #addAppTask}.
   1192      */
   1193     public Size getAppTaskThumbnailSize() {
   1194         synchronized (this) {
   1195             ensureAppTaskThumbnailSizeLocked();
   1196             return new Size(mAppTaskThumbnailSize.x, mAppTaskThumbnailSize.y);
   1197         }
   1198     }
   1199 
   1200     private void ensureAppTaskThumbnailSizeLocked() {
   1201         if (mAppTaskThumbnailSize == null) {
   1202             try {
   1203                 mAppTaskThumbnailSize = ActivityManagerNative.getDefault().getAppTaskThumbnailSize();
   1204             } catch (RemoteException e) {
   1205                 throw new IllegalStateException("System dead?", e);
   1206             }
   1207         }
   1208     }
   1209 
   1210     /**
   1211      * Add a new {@link AppTask} for the calling application.  This will create a new
   1212      * recents entry that is added to the <b>end</b> of all existing recents.
   1213      *
   1214      * @param activity The activity that is adding the entry.   This is used to help determine
   1215      * the context that the new recents entry will be in.
   1216      * @param intent The Intent that describes the recents entry.  This is the same Intent that
   1217      * you would have used to launch the activity for it.  In generally you will want to set
   1218      * both {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT} and
   1219      * {@link Intent#FLAG_ACTIVITY_RETAIN_IN_RECENTS}; the latter is required since this recents
   1220      * entry will exist without an activity, so it doesn't make sense to not retain it when
   1221      * its activity disappears.  The given Intent here also must have an explicit ComponentName
   1222      * set on it.
   1223      * @param description Optional additional description information.
   1224      * @param thumbnail Thumbnail to use for the recents entry.  Should be the size given by
   1225      * {@link #getAppTaskThumbnailSize()}.  If the bitmap is not that exact size, it will be
   1226      * recreated in your process, probably in a way you don't like, before the recents entry
   1227      * is added.
   1228      *
   1229      * @return Returns the task id of the newly added app task, or -1 if the add failed.  The
   1230      * most likely cause of failure is that there is no more room for more tasks for your app.
   1231      */
   1232     public int addAppTask(@NonNull Activity activity, @NonNull Intent intent,
   1233             @Nullable TaskDescription description, @NonNull Bitmap thumbnail) {
   1234         Point size;
   1235         synchronized (this) {
   1236             ensureAppTaskThumbnailSizeLocked();
   1237             size = mAppTaskThumbnailSize;
   1238         }
   1239         final int tw = thumbnail.getWidth();
   1240         final int th = thumbnail.getHeight();
   1241         if (tw != size.x || th != size.y) {
   1242             Bitmap bm = Bitmap.createBitmap(size.x, size.y, thumbnail.getConfig());
   1243 
   1244             // Use ScaleType.CENTER_CROP, except we leave the top edge at the top.
   1245             float scale;
   1246             float dx = 0, dy = 0;
   1247             if (tw * size.x > size.y * th) {
   1248                 scale = (float) size.x / (float) th;
   1249                 dx = (size.y - tw * scale) * 0.5f;
   1250             } else {
   1251                 scale = (float) size.y / (float) tw;
   1252                 dy = (size.x - th * scale) * 0.5f;
   1253             }
   1254             Matrix matrix = new Matrix();
   1255             matrix.setScale(scale, scale);
   1256             matrix.postTranslate((int) (dx + 0.5f), 0);
   1257 
   1258             Canvas canvas = new Canvas(bm);
   1259             canvas.drawBitmap(thumbnail, matrix, null);
   1260             canvas.setBitmap(null);
   1261 
   1262             thumbnail = bm;
   1263         }
   1264         if (description == null) {
   1265             description = new TaskDescription();
   1266         }
   1267         try {
   1268             return ActivityManagerNative.getDefault().addAppTask(activity.getActivityToken(),
   1269                     intent, description, thumbnail);
   1270         } catch (RemoteException e) {
   1271             throw new IllegalStateException("System dead?", e);
   1272         }
   1273     }
   1274 
   1275     /**
   1276      * Return a list of the tasks that are currently running, with
   1277      * the most recent being first and older ones after in order.  Note that
   1278      * "running" does not mean any of the task's code is currently loaded or
   1279      * activity -- the task may have been frozen by the system, so that it
   1280      * can be restarted in its previous state when next brought to the
   1281      * foreground.
   1282      *
   1283      * <p><b>Note: this method is only intended for debugging and presenting
   1284      * task management user interfaces</b>.  This should never be used for
   1285      * core logic in an application, such as deciding between different
   1286      * behaviors based on the information found here.  Such uses are
   1287      * <em>not</em> supported, and will likely break in the future.  For
   1288      * example, if multiple applications can be actively running at the
   1289      * same time, assumptions made about the meaning of the data here for
   1290      * purposes of control flow will be incorrect.</p>
   1291      *
   1292      * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method
   1293      * is no longer available to third party
   1294      * applications: the introduction of document-centric recents means
   1295      * it can leak person information to the caller.  For backwards compatibility,
   1296      * it will still retu rn a small subset of its data: at least the caller's
   1297      * own tasks, and possibly some other tasks
   1298      * such as home that are known to not be sensitive.
   1299      *
   1300      * @param maxNum The maximum number of entries to return in the list.  The
   1301      * actual number returned may be smaller, depending on how many tasks the
   1302      * user has started.
   1303      *
   1304      * @return Returns a list of RunningTaskInfo records describing each of
   1305      * the running tasks.
   1306      */
   1307     @Deprecated
   1308     public List<RunningTaskInfo> getRunningTasks(int maxNum)
   1309             throws SecurityException {
   1310         try {
   1311             return ActivityManagerNative.getDefault().getTasks(maxNum, 0);
   1312         } catch (RemoteException e) {
   1313             // System dead, we will be dead too soon!
   1314             return null;
   1315         }
   1316     }
   1317 
   1318     /**
   1319      * Completely remove the given task.
   1320      *
   1321      * @param taskId Identifier of the task to be removed.
   1322      * @return Returns true if the given task was found and removed.
   1323      *
   1324      * @hide
   1325      */
   1326     public boolean removeTask(int taskId) throws SecurityException {
   1327         try {
   1328             return ActivityManagerNative.getDefault().removeTask(taskId);
   1329         } catch (RemoteException e) {
   1330             // System dead, we will be dead too soon!
   1331             return false;
   1332         }
   1333     }
   1334 
   1335     /** @hide */
   1336     public static class TaskThumbnail implements Parcelable {
   1337         public Bitmap mainThumbnail;
   1338         public ParcelFileDescriptor thumbnailFileDescriptor;
   1339 
   1340         public TaskThumbnail() {
   1341         }
   1342 
   1343         public int describeContents() {
   1344             if (thumbnailFileDescriptor != null) {
   1345                 return thumbnailFileDescriptor.describeContents();
   1346             }
   1347             return 0;
   1348         }
   1349 
   1350         public void writeToParcel(Parcel dest, int flags) {
   1351             if (mainThumbnail != null) {
   1352                 dest.writeInt(1);
   1353                 mainThumbnail.writeToParcel(dest, flags);
   1354             } else {
   1355                 dest.writeInt(0);
   1356             }
   1357             if (thumbnailFileDescriptor != null) {
   1358                 dest.writeInt(1);
   1359                 thumbnailFileDescriptor.writeToParcel(dest, flags);
   1360             } else {
   1361                 dest.writeInt(0);
   1362             }
   1363         }
   1364 
   1365         public void readFromParcel(Parcel source) {
   1366             if (source.readInt() != 0) {
   1367                 mainThumbnail = Bitmap.CREATOR.createFromParcel(source);
   1368             } else {
   1369                 mainThumbnail = null;
   1370             }
   1371             if (source.readInt() != 0) {
   1372                 thumbnailFileDescriptor = ParcelFileDescriptor.CREATOR.createFromParcel(source);
   1373             } else {
   1374                 thumbnailFileDescriptor = null;
   1375             }
   1376         }
   1377 
   1378         public static final Creator<TaskThumbnail> CREATOR = new Creator<TaskThumbnail>() {
   1379             public TaskThumbnail createFromParcel(Parcel source) {
   1380                 return new TaskThumbnail(source);
   1381             }
   1382             public TaskThumbnail[] newArray(int size) {
   1383                 return new TaskThumbnail[size];
   1384             }
   1385         };
   1386 
   1387         private TaskThumbnail(Parcel source) {
   1388             readFromParcel(source);
   1389         }
   1390     }
   1391 
   1392     /** @hide */
   1393     public TaskThumbnail getTaskThumbnail(int id) throws SecurityException {
   1394         try {
   1395             return ActivityManagerNative.getDefault().getTaskThumbnail(id);
   1396         } catch (RemoteException e) {
   1397             // System dead, we will be dead too soon!
   1398             return null;
   1399         }
   1400     }
   1401 
   1402     /** @hide */
   1403     public boolean isInHomeStack(int taskId) {
   1404         try {
   1405             return ActivityManagerNative.getDefault().isInHomeStack(taskId);
   1406         } catch (RemoteException e) {
   1407             // System dead, we will be dead too soon!
   1408             return false;
   1409         }
   1410     }
   1411 
   1412     /**
   1413      * Flag for {@link #moveTaskToFront(int, int)}: also move the "home"
   1414      * activity along with the task, so it is positioned immediately behind
   1415      * the task.
   1416      */
   1417     public static final int MOVE_TASK_WITH_HOME = 0x00000001;
   1418 
   1419     /**
   1420      * Flag for {@link #moveTaskToFront(int, int)}: don't count this as a
   1421      * user-instigated action, so the current activity will not receive a
   1422      * hint that the user is leaving.
   1423      */
   1424     public static final int MOVE_TASK_NO_USER_ACTION = 0x00000002;
   1425 
   1426     /**
   1427      * Equivalent to calling {@link #moveTaskToFront(int, int, Bundle)}
   1428      * with a null options argument.
   1429      *
   1430      * @param taskId The identifier of the task to be moved, as found in
   1431      * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
   1432      * @param flags Additional operational flags, 0 or more of
   1433      * {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}.
   1434      */
   1435     public void moveTaskToFront(int taskId, int flags) {
   1436         moveTaskToFront(taskId, flags, null);
   1437     }
   1438 
   1439     /**
   1440      * Ask that the task associated with a given task ID be moved to the
   1441      * front of the stack, so it is now visible to the user.  Requires that
   1442      * the caller hold permission {@link android.Manifest.permission#REORDER_TASKS}
   1443      * or a SecurityException will be thrown.
   1444      *
   1445      * @param taskId The identifier of the task to be moved, as found in
   1446      * {@link RunningTaskInfo} or {@link RecentTaskInfo}.
   1447      * @param flags Additional operational flags, 0 or more of
   1448      * {@link #MOVE_TASK_WITH_HOME}, {@link #MOVE_TASK_NO_USER_ACTION}.
   1449      * @param options Additional options for the operation, either null or
   1450      * as per {@link Context#startActivity(Intent, android.os.Bundle)
   1451      * Context.startActivity(Intent, Bundle)}.
   1452      */
   1453     public void moveTaskToFront(int taskId, int flags, Bundle options) {
   1454         try {
   1455             ActivityManagerNative.getDefault().moveTaskToFront(taskId, flags, options);
   1456         } catch (RemoteException e) {
   1457             // System dead, we will be dead too soon!
   1458         }
   1459     }
   1460 
   1461     /**
   1462      * Information you can retrieve about a particular Service that is
   1463      * currently running in the system.
   1464      */
   1465     public static class RunningServiceInfo implements Parcelable {
   1466         /**
   1467          * The service component.
   1468          */
   1469         public ComponentName service;
   1470 
   1471         /**
   1472          * If non-zero, this is the process the service is running in.
   1473          */
   1474         public int pid;
   1475 
   1476         /**
   1477          * The UID that owns this service.
   1478          */
   1479         public int uid;
   1480 
   1481         /**
   1482          * The name of the process this service runs in.
   1483          */
   1484         public String process;
   1485 
   1486         /**
   1487          * Set to true if the service has asked to run as a foreground process.
   1488          */
   1489         public boolean foreground;
   1490 
   1491         /**
   1492          * The time when the service was first made active, either by someone
   1493          * starting or binding to it.  This
   1494          * is in units of {@link android.os.SystemClock#elapsedRealtime()}.
   1495          */
   1496         public long activeSince;
   1497 
   1498         /**
   1499          * Set to true if this service has been explicitly started.
   1500          */
   1501         public boolean started;
   1502 
   1503         /**
   1504          * Number of clients connected to the service.
   1505          */
   1506         public int clientCount;
   1507 
   1508         /**
   1509          * Number of times the service's process has crashed while the service
   1510          * is running.
   1511          */
   1512         public int crashCount;
   1513 
   1514         /**
   1515          * The time when there was last activity in the service (either
   1516          * explicit requests to start it or clients binding to it).  This
   1517          * is in units of {@link android.os.SystemClock#uptimeMillis()}.
   1518          */
   1519         public long lastActivityTime;
   1520 
   1521         /**
   1522          * If non-zero, this service is not currently running, but scheduled to
   1523          * restart at the given time.
   1524          */
   1525         public long restarting;
   1526 
   1527         /**
   1528          * Bit for {@link #flags}: set if this service has been
   1529          * explicitly started.
   1530          */
   1531         public static final int FLAG_STARTED = 1<<0;
   1532 
   1533         /**
   1534          * Bit for {@link #flags}: set if the service has asked to
   1535          * run as a foreground process.
   1536          */
   1537         public static final int FLAG_FOREGROUND = 1<<1;
   1538 
   1539         /**
   1540          * Bit for {@link #flags): set if the service is running in a
   1541          * core system process.
   1542          */
   1543         public static final int FLAG_SYSTEM_PROCESS = 1<<2;
   1544 
   1545         /**
   1546          * Bit for {@link #flags): set if the service is running in a
   1547          * persistent process.
   1548          */
   1549         public static final int FLAG_PERSISTENT_PROCESS = 1<<3;
   1550 
   1551         /**
   1552          * Running flags.
   1553          */
   1554         public int flags;
   1555 
   1556         /**
   1557          * For special services that are bound to by system code, this is
   1558          * the package that holds the binding.
   1559          */
   1560         public String clientPackage;
   1561 
   1562         /**
   1563          * For special services that are bound to by system code, this is
   1564          * a string resource providing a user-visible label for who the
   1565          * client is.
   1566          */
   1567         public int clientLabel;
   1568 
   1569         public RunningServiceInfo() {
   1570         }
   1571 
   1572         public int describeContents() {
   1573             return 0;
   1574         }
   1575 
   1576         public void writeToParcel(Parcel dest, int flags) {
   1577             ComponentName.writeToParcel(service, dest);
   1578             dest.writeInt(pid);
   1579             dest.writeInt(uid);
   1580             dest.writeString(process);
   1581             dest.writeInt(foreground ? 1 : 0);
   1582             dest.writeLong(activeSince);
   1583             dest.writeInt(started ? 1 : 0);
   1584             dest.writeInt(clientCount);
   1585             dest.writeInt(crashCount);
   1586             dest.writeLong(lastActivityTime);
   1587             dest.writeLong(restarting);
   1588             dest.writeInt(this.flags);
   1589             dest.writeString(clientPackage);
   1590             dest.writeInt(clientLabel);
   1591         }
   1592 
   1593         public void readFromParcel(Parcel source) {
   1594             service = ComponentName.readFromParcel(source);
   1595             pid = source.readInt();
   1596             uid = source.readInt();
   1597             process = source.readString();
   1598             foreground = source.readInt() != 0;
   1599             activeSince = source.readLong();
   1600             started = source.readInt() != 0;
   1601             clientCount = source.readInt();
   1602             crashCount = source.readInt();
   1603             lastActivityTime = source.readLong();
   1604             restarting = source.readLong();
   1605             flags = source.readInt();
   1606             clientPackage = source.readString();
   1607             clientLabel = source.readInt();
   1608         }
   1609 
   1610         public static final Creator<RunningServiceInfo> CREATOR = new Creator<RunningServiceInfo>() {
   1611             public RunningServiceInfo createFromParcel(Parcel source) {
   1612                 return new RunningServiceInfo(source);
   1613             }
   1614             public RunningServiceInfo[] newArray(int size) {
   1615                 return new RunningServiceInfo[size];
   1616             }
   1617         };
   1618 
   1619         private RunningServiceInfo(Parcel source) {
   1620             readFromParcel(source);
   1621         }
   1622     }
   1623 
   1624     /**
   1625      * Return a list of the services that are currently running.
   1626      *
   1627      * <p><b>Note: this method is only intended for debugging or implementing
   1628      * service management type user interfaces.</b></p>
   1629      *
   1630      * @param maxNum The maximum number of entries to return in the list.  The
   1631      * actual number returned may be smaller, depending on how many services
   1632      * are running.
   1633      *
   1634      * @return Returns a list of RunningServiceInfo records describing each of
   1635      * the running tasks.
   1636      */
   1637     public List<RunningServiceInfo> getRunningServices(int maxNum)
   1638             throws SecurityException {
   1639         try {
   1640             return ActivityManagerNative.getDefault()
   1641                     .getServices(maxNum, 0);
   1642         } catch (RemoteException e) {
   1643             // System dead, we will be dead too soon!
   1644             return null;
   1645         }
   1646     }
   1647 
   1648     /**
   1649      * Returns a PendingIntent you can start to show a control panel for the
   1650      * given running service.  If the service does not have a control panel,
   1651      * null is returned.
   1652      */
   1653     public PendingIntent getRunningServiceControlPanel(ComponentName service)
   1654             throws SecurityException {
   1655         try {
   1656             return ActivityManagerNative.getDefault()
   1657                     .getRunningServiceControlPanel(service);
   1658         } catch (RemoteException e) {
   1659             // System dead, we will be dead too soon!
   1660             return null;
   1661         }
   1662     }
   1663 
   1664     /**
   1665      * Information you can retrieve about the available memory through
   1666      * {@link ActivityManager#getMemoryInfo}.
   1667      */
   1668     public static class MemoryInfo implements Parcelable {
   1669         /**
   1670          * The available memory on the system.  This number should not
   1671          * be considered absolute: due to the nature of the kernel, a significant
   1672          * portion of this memory is actually in use and needed for the overall
   1673          * system to run well.
   1674          */
   1675         public long availMem;
   1676 
   1677         /**
   1678          * The total memory accessible by the kernel.  This is basically the
   1679          * RAM size of the device, not including below-kernel fixed allocations
   1680          * like DMA buffers, RAM for the baseband CPU, etc.
   1681          */
   1682         public long totalMem;
   1683 
   1684         /**
   1685          * The threshold of {@link #availMem} at which we consider memory to be
   1686          * low and start killing background services and other non-extraneous
   1687          * processes.
   1688          */
   1689         public long threshold;
   1690 
   1691         /**
   1692          * Set to true if the system considers itself to currently be in a low
   1693          * memory situation.
   1694          */
   1695         public boolean lowMemory;
   1696 
   1697         /** @hide */
   1698         public long hiddenAppThreshold;
   1699         /** @hide */
   1700         public long secondaryServerThreshold;
   1701         /** @hide */
   1702         public long visibleAppThreshold;
   1703         /** @hide */
   1704         public long foregroundAppThreshold;
   1705 
   1706         public MemoryInfo() {
   1707         }
   1708 
   1709         public int describeContents() {
   1710             return 0;
   1711         }
   1712 
   1713         public void writeToParcel(Parcel dest, int flags) {
   1714             dest.writeLong(availMem);
   1715             dest.writeLong(totalMem);
   1716             dest.writeLong(threshold);
   1717             dest.writeInt(lowMemory ? 1 : 0);
   1718             dest.writeLong(hiddenAppThreshold);
   1719             dest.writeLong(secondaryServerThreshold);
   1720             dest.writeLong(visibleAppThreshold);
   1721             dest.writeLong(foregroundAppThreshold);
   1722         }
   1723 
   1724         public void readFromParcel(Parcel source) {
   1725             availMem = source.readLong();
   1726             totalMem = source.readLong();
   1727             threshold = source.readLong();
   1728             lowMemory = source.readInt() != 0;
   1729             hiddenAppThreshold = source.readLong();
   1730             secondaryServerThreshold = source.readLong();
   1731             visibleAppThreshold = source.readLong();
   1732             foregroundAppThreshold = source.readLong();
   1733         }
   1734 
   1735         public static final Creator<MemoryInfo> CREATOR
   1736                 = new Creator<MemoryInfo>() {
   1737             public MemoryInfo createFromParcel(Parcel source) {
   1738                 return new MemoryInfo(source);
   1739             }
   1740             public MemoryInfo[] newArray(int size) {
   1741                 return new MemoryInfo[size];
   1742             }
   1743         };
   1744 
   1745         private MemoryInfo(Parcel source) {
   1746             readFromParcel(source);
   1747         }
   1748     }
   1749 
   1750     /**
   1751      * Return general information about the memory state of the system.  This
   1752      * can be used to help decide how to manage your own memory, though note
   1753      * that polling is not recommended and
   1754      * {@link android.content.ComponentCallbacks2#onTrimMemory(int)
   1755      * ComponentCallbacks2.onTrimMemory(int)} is the preferred way to do this.
   1756      * Also see {@link #getMyMemoryState} for how to retrieve the current trim
   1757      * level of your process as needed, which gives a better hint for how to
   1758      * manage its memory.
   1759      */
   1760     public void getMemoryInfo(MemoryInfo outInfo) {
   1761         try {
   1762             ActivityManagerNative.getDefault().getMemoryInfo(outInfo);
   1763         } catch (RemoteException e) {
   1764         }
   1765     }
   1766 
   1767     /**
   1768      * Information you can retrieve about an ActivityStack in the system.
   1769      * @hide
   1770      */
   1771     public static class StackInfo implements Parcelable {
   1772         public int stackId;
   1773         public Rect bounds = new Rect();
   1774         public int[] taskIds;
   1775         public String[] taskNames;
   1776         public int displayId;
   1777 
   1778         @Override
   1779         public int describeContents() {
   1780             return 0;
   1781         }
   1782 
   1783         @Override
   1784         public void writeToParcel(Parcel dest, int flags) {
   1785             dest.writeInt(stackId);
   1786             dest.writeInt(bounds.left);
   1787             dest.writeInt(bounds.top);
   1788             dest.writeInt(bounds.right);
   1789             dest.writeInt(bounds.bottom);
   1790             dest.writeIntArray(taskIds);
   1791             dest.writeStringArray(taskNames);
   1792             dest.writeInt(displayId);
   1793         }
   1794 
   1795         public void readFromParcel(Parcel source) {
   1796             stackId = source.readInt();
   1797             bounds = new Rect(
   1798                     source.readInt(), source.readInt(), source.readInt(), source.readInt());
   1799             taskIds = source.createIntArray();
   1800             taskNames = source.createStringArray();
   1801             displayId = source.readInt();
   1802         }
   1803 
   1804         public static final Creator<StackInfo> CREATOR = new Creator<StackInfo>() {
   1805             @Override
   1806             public StackInfo createFromParcel(Parcel source) {
   1807                 return new StackInfo(source);
   1808             }
   1809             @Override
   1810             public StackInfo[] newArray(int size) {
   1811                 return new StackInfo[size];
   1812             }
   1813         };
   1814 
   1815         public StackInfo() {
   1816         }
   1817 
   1818         private StackInfo(Parcel source) {
   1819             readFromParcel(source);
   1820         }
   1821 
   1822         public String toString(String prefix) {
   1823             StringBuilder sb = new StringBuilder(256);
   1824             sb.append(prefix); sb.append("Stack id="); sb.append(stackId);
   1825                     sb.append(" bounds="); sb.append(bounds.toShortString());
   1826                     sb.append(" displayId="); sb.append(displayId);
   1827                     sb.append("\n");
   1828             prefix = prefix + "  ";
   1829             for (int i = 0; i < taskIds.length; ++i) {
   1830                 sb.append(prefix); sb.append("taskId="); sb.append(taskIds[i]);
   1831                         sb.append(": "); sb.append(taskNames[i]); sb.append("\n");
   1832             }
   1833             return sb.toString();
   1834         }
   1835 
   1836         @Override
   1837         public String toString() {
   1838             return toString("");
   1839         }
   1840     }
   1841 
   1842     /**
   1843      * @hide
   1844      */
   1845     public boolean clearApplicationUserData(String packageName, IPackageDataObserver observer) {
   1846         try {
   1847             return ActivityManagerNative.getDefault().clearApplicationUserData(packageName,
   1848                     observer, UserHandle.myUserId());
   1849         } catch (RemoteException e) {
   1850             return false;
   1851         }
   1852     }
   1853 
   1854     /**
   1855      * Permits an application to erase its own data from disk.  This is equivalent to
   1856      * the user choosing to clear the app's data from within the device settings UI.  It
   1857      * erases all dynamic data associated with the app -- its private data and data in its
   1858      * private area on external storage -- but does not remove the installed application
   1859      * itself, nor any OBB files.
   1860      *
   1861      * @return {@code true} if the application successfully requested that the application's
   1862      *     data be erased; {@code false} otherwise.
   1863      */
   1864     public boolean clearApplicationUserData() {
   1865         return clearApplicationUserData(mContext.getPackageName(), null);
   1866     }
   1867 
   1868     /**
   1869      * Information you can retrieve about any processes that are in an error condition.
   1870      */
   1871     public static class ProcessErrorStateInfo implements Parcelable {
   1872         /**
   1873          * Condition codes
   1874          */
   1875         public static final int NO_ERROR = 0;
   1876         public static final int CRASHED = 1;
   1877         public static final int NOT_RESPONDING = 2;
   1878 
   1879         /**
   1880          * The condition that the process is in.
   1881          */
   1882         public int condition;
   1883 
   1884         /**
   1885          * The process name in which the crash or error occurred.
   1886          */
   1887         public String processName;
   1888 
   1889         /**
   1890          * The pid of this process; 0 if none
   1891          */
   1892         public int pid;
   1893 
   1894         /**
   1895          * The kernel user-ID that has been assigned to this process;
   1896          * currently this is not a unique ID (multiple applications can have
   1897          * the same uid).
   1898          */
   1899         public int uid;
   1900 
   1901         /**
   1902          * The activity name associated with the error, if known.  May be null.
   1903          */
   1904         public String tag;
   1905 
   1906         /**
   1907          * A short message describing the error condition.
   1908          */
   1909         public String shortMsg;
   1910 
   1911         /**
   1912          * A long message describing the error condition.
   1913          */
   1914         public String longMsg;
   1915 
   1916         /**
   1917          * The stack trace where the error originated.  May be null.
   1918          */
   1919         public String stackTrace;
   1920 
   1921         /**
   1922          * to be deprecated: This value will always be null.
   1923          */
   1924         public byte[] crashData = null;
   1925 
   1926         public ProcessErrorStateInfo() {
   1927         }
   1928 
   1929         @Override
   1930         public int describeContents() {
   1931             return 0;
   1932         }
   1933 
   1934         @Override
   1935         public void writeToParcel(Parcel dest, int flags) {
   1936             dest.writeInt(condition);
   1937             dest.writeString(processName);
   1938             dest.writeInt(pid);
   1939             dest.writeInt(uid);
   1940             dest.writeString(tag);
   1941             dest.writeString(shortMsg);
   1942             dest.writeString(longMsg);
   1943             dest.writeString(stackTrace);
   1944         }
   1945 
   1946         public void readFromParcel(Parcel source) {
   1947             condition = source.readInt();
   1948             processName = source.readString();
   1949             pid = source.readInt();
   1950             uid = source.readInt();
   1951             tag = source.readString();
   1952             shortMsg = source.readString();
   1953             longMsg = source.readString();
   1954             stackTrace = source.readString();
   1955         }
   1956 
   1957         public static final Creator<ProcessErrorStateInfo> CREATOR =
   1958                 new Creator<ProcessErrorStateInfo>() {
   1959             public ProcessErrorStateInfo createFromParcel(Parcel source) {
   1960                 return new ProcessErrorStateInfo(source);
   1961             }
   1962             public ProcessErrorStateInfo[] newArray(int size) {
   1963                 return new ProcessErrorStateInfo[size];
   1964             }
   1965         };
   1966 
   1967         private ProcessErrorStateInfo(Parcel source) {
   1968             readFromParcel(source);
   1969         }
   1970     }
   1971 
   1972     /**
   1973      * Returns a list of any processes that are currently in an error condition.  The result
   1974      * will be null if all processes are running properly at this time.
   1975      *
   1976      * @return Returns a list of ProcessErrorStateInfo records, or null if there are no
   1977      * current error conditions (it will not return an empty list).  This list ordering is not
   1978      * specified.
   1979      */
   1980     public List<ProcessErrorStateInfo> getProcessesInErrorState() {
   1981         try {
   1982             return ActivityManagerNative.getDefault().getProcessesInErrorState();
   1983         } catch (RemoteException e) {
   1984             return null;
   1985         }
   1986     }
   1987 
   1988     /**
   1989      * Information you can retrieve about a running process.
   1990      */
   1991     public static class RunningAppProcessInfo implements Parcelable {
   1992         /**
   1993          * The name of the process that this object is associated with
   1994          */
   1995         public String processName;
   1996 
   1997         /**
   1998          * The pid of this process; 0 if none
   1999          */
   2000         public int pid;
   2001 
   2002         /**
   2003          * The user id of this process.
   2004          */
   2005         public int uid;
   2006 
   2007         /**
   2008          * All packages that have been loaded into the process.
   2009          */
   2010         public String pkgList[];
   2011 
   2012         /**
   2013          * Constant for {@link #flags}: this is an app that is unable to
   2014          * correctly save its state when going to the background,
   2015          * so it can not be killed while in the background.
   2016          * @hide
   2017          */
   2018         public static final int FLAG_CANT_SAVE_STATE = 1<<0;
   2019 
   2020         /**
   2021          * Constant for {@link #flags}: this process is associated with a
   2022          * persistent system app.
   2023          * @hide
   2024          */
   2025         public static final int FLAG_PERSISTENT = 1<<1;
   2026 
   2027         /**
   2028          * Constant for {@link #flags}: this process is associated with a
   2029          * persistent system app.
   2030          * @hide
   2031          */
   2032         public static final int FLAG_HAS_ACTIVITIES = 1<<2;
   2033 
   2034         /**
   2035          * Flags of information.  May be any of
   2036          * {@link #FLAG_CANT_SAVE_STATE}.
   2037          * @hide
   2038          */
   2039         public int flags;
   2040 
   2041         /**
   2042          * Last memory trim level reported to the process: corresponds to
   2043          * the values supplied to {@link android.content.ComponentCallbacks2#onTrimMemory(int)
   2044          * ComponentCallbacks2.onTrimMemory(int)}.
   2045          */
   2046         public int lastTrimLevel;
   2047 
   2048         /**
   2049          * Constant for {@link #importance}: This process is running the
   2050          * foreground UI; that is, it is the thing currently at the top of the screen
   2051          * that the user is interacting with.
   2052          */
   2053         public static final int IMPORTANCE_FOREGROUND = 100;
   2054 
   2055         /**
   2056          * Constant for {@link #importance}: This process is running a foreground
   2057          * service, for example to perform music playback even while the user is
   2058          * not immediately in the app.  This generally indicates that the process
   2059          * is doing something the user actively cares about.
   2060          */
   2061         public static final int IMPORTANCE_FOREGROUND_SERVICE = 125;
   2062 
   2063         /**
   2064          * Constant for {@link #importance}: This process is running the foreground
   2065          * UI, but the device is asleep so it is not visible to the user.  This means
   2066          * the user is not really aware of the process, because they can not see or
   2067          * interact with it, but it is quite important because it what they expect to
   2068          * return to once unlocking the device.
   2069          */
   2070         public static final int IMPORTANCE_TOP_SLEEPING = 150;
   2071 
   2072         /**
   2073          * Constant for {@link #importance}: This process is running something
   2074          * that is actively visible to the user, though not in the immediate
   2075          * foreground.  This may be running a window that is behind the current
   2076          * foreground (so paused and with its state saved, not interacting with
   2077          * the user, but visible to them to some degree); it may also be running
   2078          * other services under the system's control that it inconsiders important.
   2079          */
   2080         public static final int IMPORTANCE_VISIBLE = 200;
   2081 
   2082         /**
   2083          * Constant for {@link #importance}: This process is not something the user
   2084          * is directly aware of, but is otherwise perceptable to them to some degree.
   2085          */
   2086         public static final int IMPORTANCE_PERCEPTIBLE = 130;
   2087 
   2088         /**
   2089          * Constant for {@link #importance}: This process is running an
   2090          * application that can not save its state, and thus can't be killed
   2091          * while in the background.
   2092          * @hide
   2093          */
   2094         public static final int IMPORTANCE_CANT_SAVE_STATE = 170;
   2095 
   2096         /**
   2097          * Constant for {@link #importance}: This process is contains services
   2098          * that should remain running.  These are background services apps have
   2099          * started, not something the user is aware of, so they may be killed by
   2100          * the system relatively freely (though it is generally desired that they
   2101          * stay running as long as they want to).
   2102          */
   2103         public static final int IMPORTANCE_SERVICE = 300;
   2104 
   2105         /**
   2106          * Constant for {@link #importance}: This process process contains
   2107          * background code that is expendable.
   2108          */
   2109         public static final int IMPORTANCE_BACKGROUND = 400;
   2110 
   2111         /**
   2112          * Constant for {@link #importance}: This process is empty of any
   2113          * actively running code.
   2114          */
   2115         public static final int IMPORTANCE_EMPTY = 500;
   2116 
   2117         /**
   2118          * Constant for {@link #importance}: This process does not exist.
   2119          */
   2120         public static final int IMPORTANCE_GONE = 1000;
   2121 
   2122         /** @hide */
   2123         public static int procStateToImportance(int procState) {
   2124             if (procState == PROCESS_STATE_NONEXISTENT) {
   2125                 return IMPORTANCE_GONE;
   2126             } else if (procState >= PROCESS_STATE_HOME) {
   2127                 return IMPORTANCE_BACKGROUND;
   2128             } else if (procState >= PROCESS_STATE_SERVICE) {
   2129                 return IMPORTANCE_SERVICE;
   2130             } else if (procState > PROCESS_STATE_HEAVY_WEIGHT) {
   2131                 return IMPORTANCE_CANT_SAVE_STATE;
   2132             } else if (procState >= PROCESS_STATE_IMPORTANT_BACKGROUND) {
   2133                 return IMPORTANCE_PERCEPTIBLE;
   2134             } else if (procState >= PROCESS_STATE_IMPORTANT_FOREGROUND) {
   2135                 return IMPORTANCE_VISIBLE;
   2136             } else if (procState >= PROCESS_STATE_TOP_SLEEPING) {
   2137                 return IMPORTANCE_TOP_SLEEPING;
   2138             } else if (procState >= PROCESS_STATE_FOREGROUND_SERVICE) {
   2139                 return IMPORTANCE_FOREGROUND_SERVICE;
   2140             } else {
   2141                 return IMPORTANCE_FOREGROUND;
   2142             }
   2143         }
   2144 
   2145         /**
   2146          * The relative importance level that the system places on this
   2147          * process.  May be one of {@link #IMPORTANCE_FOREGROUND},
   2148          * {@link #IMPORTANCE_VISIBLE}, {@link #IMPORTANCE_SERVICE},
   2149          * {@link #IMPORTANCE_BACKGROUND}, or {@link #IMPORTANCE_EMPTY}.  These
   2150          * constants are numbered so that "more important" values are always
   2151          * smaller than "less important" values.
   2152          */
   2153         public int importance;
   2154 
   2155         /**
   2156          * An additional ordering within a particular {@link #importance}
   2157          * category, providing finer-grained information about the relative
   2158          * utility of processes within a category.  This number means nothing
   2159          * except that a smaller values are more recently used (and thus
   2160          * more important).  Currently an LRU value is only maintained for
   2161          * the {@link #IMPORTANCE_BACKGROUND} category, though others may
   2162          * be maintained in the future.
   2163          */
   2164         public int lru;
   2165 
   2166         /**
   2167          * Constant for {@link #importanceReasonCode}: nothing special has
   2168          * been specified for the reason for this level.
   2169          */
   2170         public static final int REASON_UNKNOWN = 0;
   2171 
   2172         /**
   2173          * Constant for {@link #importanceReasonCode}: one of the application's
   2174          * content providers is being used by another process.  The pid of
   2175          * the client process is in {@link #importanceReasonPid} and the
   2176          * target provider in this process is in
   2177          * {@link #importanceReasonComponent}.
   2178          */
   2179         public static final int REASON_PROVIDER_IN_USE = 1;
   2180 
   2181         /**
   2182          * Constant for {@link #importanceReasonCode}: one of the application's
   2183          * content providers is being used by another process.  The pid of
   2184          * the client process is in {@link #importanceReasonPid} and the
   2185          * target provider in this process is in
   2186          * {@link #importanceReasonComponent}.
   2187          */
   2188         public static final int REASON_SERVICE_IN_USE = 2;
   2189 
   2190         /**
   2191          * The reason for {@link #importance}, if any.
   2192          */
   2193         public int importanceReasonCode;
   2194 
   2195         /**
   2196          * For the specified values of {@link #importanceReasonCode}, this
   2197          * is the process ID of the other process that is a client of this
   2198          * process.  This will be 0 if no other process is using this one.
   2199          */
   2200         public int importanceReasonPid;
   2201 
   2202         /**
   2203          * For the specified values of {@link #importanceReasonCode}, this
   2204          * is the name of the component that is being used in this process.
   2205          */
   2206         public ComponentName importanceReasonComponent;
   2207 
   2208         /**
   2209          * When {@link #importanceReasonPid} is non-0, this is the importance
   2210          * of the other pid. @hide
   2211          */
   2212         public int importanceReasonImportance;
   2213 
   2214         /**
   2215          * Current process state, as per PROCESS_STATE_* constants.
   2216          * @hide
   2217          */
   2218         public int processState;
   2219 
   2220         public RunningAppProcessInfo() {
   2221             importance = IMPORTANCE_FOREGROUND;
   2222             importanceReasonCode = REASON_UNKNOWN;
   2223             processState = PROCESS_STATE_IMPORTANT_FOREGROUND;
   2224         }
   2225 
   2226         public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) {
   2227             processName = pProcessName;
   2228             pid = pPid;
   2229             pkgList = pArr;
   2230         }
   2231 
   2232         public int describeContents() {
   2233             return 0;
   2234         }
   2235 
   2236         public void writeToParcel(Parcel dest, int flags) {
   2237             dest.writeString(processName);
   2238             dest.writeInt(pid);
   2239             dest.writeInt(uid);
   2240             dest.writeStringArray(pkgList);
   2241             dest.writeInt(this.flags);
   2242             dest.writeInt(lastTrimLevel);
   2243             dest.writeInt(importance);
   2244             dest.writeInt(lru);
   2245             dest.writeInt(importanceReasonCode);
   2246             dest.writeInt(importanceReasonPid);
   2247             ComponentName.writeToParcel(importanceReasonComponent, dest);
   2248             dest.writeInt(importanceReasonImportance);
   2249             dest.writeInt(processState);
   2250         }
   2251 
   2252         public void readFromParcel(Parcel source) {
   2253             processName = source.readString();
   2254             pid = source.readInt();
   2255             uid = source.readInt();
   2256             pkgList = source.readStringArray();
   2257             flags = source.readInt();
   2258             lastTrimLevel = source.readInt();
   2259             importance = source.readInt();
   2260             lru = source.readInt();
   2261             importanceReasonCode = source.readInt();
   2262             importanceReasonPid = source.readInt();
   2263             importanceReasonComponent = ComponentName.readFromParcel(source);
   2264             importanceReasonImportance = source.readInt();
   2265             processState = source.readInt();
   2266         }
   2267 
   2268         public static final Creator<RunningAppProcessInfo> CREATOR =
   2269             new Creator<RunningAppProcessInfo>() {
   2270             public RunningAppProcessInfo createFromParcel(Parcel source) {
   2271                 return new RunningAppProcessInfo(source);
   2272             }
   2273             public RunningAppProcessInfo[] newArray(int size) {
   2274                 return new RunningAppProcessInfo[size];
   2275             }
   2276         };
   2277 
   2278         private RunningAppProcessInfo(Parcel source) {
   2279             readFromParcel(source);
   2280         }
   2281     }
   2282 
   2283     /**
   2284      * Returns a list of application processes installed on external media
   2285      * that are running on the device.
   2286      *
   2287      * <p><b>Note: this method is only intended for debugging or building
   2288      * a user-facing process management UI.</b></p>
   2289      *
   2290      * @return Returns a list of ApplicationInfo records, or null if none
   2291      * This list ordering is not specified.
   2292      * @hide
   2293      */
   2294     public List<ApplicationInfo> getRunningExternalApplications() {
   2295         try {
   2296             return ActivityManagerNative.getDefault().getRunningExternalApplications();
   2297         } catch (RemoteException e) {
   2298             return null;
   2299         }
   2300     }
   2301 
   2302     /**
   2303      * Sets the memory trim mode for a process and schedules a memory trim operation.
   2304      *
   2305      * <p><b>Note: this method is only intended for testing framework.</b></p>
   2306      *
   2307      * @return Returns true if successful.
   2308      * @hide
   2309      */
   2310     public boolean setProcessMemoryTrimLevel(String process, int userId, int level) {
   2311         try {
   2312             return ActivityManagerNative.getDefault().setProcessMemoryTrimLevel(process, userId,
   2313                     level);
   2314         } catch (RemoteException e) {
   2315             return false;
   2316         }
   2317     }
   2318 
   2319     /**
   2320      * Returns a list of application processes that are running on the device.
   2321      *
   2322      * <p><b>Note: this method is only intended for debugging or building
   2323      * a user-facing process management UI.</b></p>
   2324      *
   2325      * @return Returns a list of RunningAppProcessInfo records, or null if there are no
   2326      * running processes (it will not return an empty list).  This list ordering is not
   2327      * specified.
   2328      */
   2329     public List<RunningAppProcessInfo> getRunningAppProcesses() {
   2330         try {
   2331             return ActivityManagerNative.getDefault().getRunningAppProcesses();
   2332         } catch (RemoteException e) {
   2333             return null;
   2334         }
   2335     }
   2336 
   2337     /**
   2338      * Return the importance of a given package name, based on the processes that are
   2339      * currently running.  The return value is one of the importance constants defined
   2340      * in {@link RunningAppProcessInfo}, giving you the highest importance of all the
   2341      * processes that this package has code running inside of.  If there are no processes
   2342      * running its code, {@link RunningAppProcessInfo#IMPORTANCE_GONE} is returned.
   2343      * @hide
   2344      */
   2345     @SystemApi
   2346     public int getPackageImportance(String packageName) {
   2347         try {
   2348             int procState = ActivityManagerNative.getDefault().getPackageProcessState(packageName,
   2349                     mContext.getOpPackageName());
   2350             return RunningAppProcessInfo.procStateToImportance(procState);
   2351         } catch (RemoteException e) {
   2352             return RunningAppProcessInfo.IMPORTANCE_GONE;
   2353         }
   2354     }
   2355 
   2356     /**
   2357      * Return global memory state information for the calling process.  This
   2358      * does not fill in all fields of the {@link RunningAppProcessInfo}.  The
   2359      * only fields that will be filled in are
   2360      * {@link RunningAppProcessInfo#pid},
   2361      * {@link RunningAppProcessInfo#uid},
   2362      * {@link RunningAppProcessInfo#lastTrimLevel},
   2363      * {@link RunningAppProcessInfo#importance},
   2364      * {@link RunningAppProcessInfo#lru}, and
   2365      * {@link RunningAppProcessInfo#importanceReasonCode}.
   2366      */
   2367     static public void getMyMemoryState(RunningAppProcessInfo outState) {
   2368         try {
   2369             ActivityManagerNative.getDefault().getMyMemoryState(outState);
   2370         } catch (RemoteException e) {
   2371         }
   2372     }
   2373 
   2374     /**
   2375      * Return information about the memory usage of one or more processes.
   2376      *
   2377      * <p><b>Note: this method is only intended for debugging or building
   2378      * a user-facing process management UI.</b></p>
   2379      *
   2380      * @param pids The pids of the processes whose memory usage is to be
   2381      * retrieved.
   2382      * @return Returns an array of memory information, one for each
   2383      * requested pid.
   2384      */
   2385     public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
   2386         try {
   2387             return ActivityManagerNative.getDefault().getProcessMemoryInfo(pids);
   2388         } catch (RemoteException e) {
   2389             return null;
   2390         }
   2391     }
   2392 
   2393     /**
   2394      * @deprecated This is now just a wrapper for
   2395      * {@link #killBackgroundProcesses(String)}; the previous behavior here
   2396      * is no longer available to applications because it allows them to
   2397      * break other applications by removing their alarms, stopping their
   2398      * services, etc.
   2399      */
   2400     @Deprecated
   2401     public void restartPackage(String packageName) {
   2402         killBackgroundProcesses(packageName);
   2403     }
   2404 
   2405     /**
   2406      * Have the system immediately kill all background processes associated
   2407      * with the given package.  This is the same as the kernel killing those
   2408      * processes to reclaim memory; the system will take care of restarting
   2409      * these processes in the future as needed.
   2410      *
   2411      * <p>You must hold the permission
   2412      * {@link android.Manifest.permission#KILL_BACKGROUND_PROCESSES} to be able to
   2413      * call this method.
   2414      *
   2415      * @param packageName The name of the package whose processes are to
   2416      * be killed.
   2417      */
   2418     public void killBackgroundProcesses(String packageName) {
   2419         try {
   2420             ActivityManagerNative.getDefault().killBackgroundProcesses(packageName,
   2421                     UserHandle.myUserId());
   2422         } catch (RemoteException e) {
   2423         }
   2424     }
   2425 
   2426     /**
   2427      * Kills the specified UID.
   2428      * @param uid The UID to kill.
   2429      * @param reason The reason for the kill.
   2430      *
   2431      * @hide
   2432      */
   2433     @RequiresPermission(Manifest.permission.KILL_UID)
   2434     public void killUid(int uid, String reason) {
   2435         try {
   2436             ActivityManagerNative.getDefault().killUid(UserHandle.getAppId(uid),
   2437                     UserHandle.getUserId(uid), reason);
   2438         } catch (RemoteException e) {
   2439             Log.e(TAG, "Couldn't kill uid:" + uid, e);
   2440         }
   2441     }
   2442 
   2443     /**
   2444      * Have the system perform a force stop of everything associated with
   2445      * the given application package.  All processes that share its uid
   2446      * will be killed, all services it has running stopped, all activities
   2447      * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
   2448      * broadcast will be sent, so that any of its registered alarms can
   2449      * be stopped, notifications removed, etc.
   2450      *
   2451      * <p>You must hold the permission
   2452      * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
   2453      * call this method.
   2454      *
   2455      * @param packageName The name of the package to be stopped.
   2456      * @param userId The user for which the running package is to be stopped.
   2457      *
   2458      * @hide This is not available to third party applications due to
   2459      * it allowing them to break other applications by stopping their
   2460      * services, removing their alarms, etc.
   2461      */
   2462     public void forceStopPackageAsUser(String packageName, int userId) {
   2463         try {
   2464             ActivityManagerNative.getDefault().forceStopPackage(packageName, userId);
   2465         } catch (RemoteException e) {
   2466         }
   2467     }
   2468 
   2469     /**
   2470      * @see #forceStopPackageAsUser(String, int)
   2471      * @hide
   2472      */
   2473     public void forceStopPackage(String packageName) {
   2474         forceStopPackageAsUser(packageName, UserHandle.myUserId());
   2475     }
   2476 
   2477     /**
   2478      * Get the device configuration attributes.
   2479      */
   2480     public ConfigurationInfo getDeviceConfigurationInfo() {
   2481         try {
   2482             return ActivityManagerNative.getDefault().getDeviceConfigurationInfo();
   2483         } catch (RemoteException e) {
   2484         }
   2485         return null;
   2486     }
   2487 
   2488     /**
   2489      * Get the preferred density of icons for the launcher. This is used when
   2490      * custom drawables are created (e.g., for shortcuts).
   2491      *
   2492      * @return density in terms of DPI
   2493      */
   2494     public int getLauncherLargeIconDensity() {
   2495         final Resources res = mContext.getResources();
   2496         final int density = res.getDisplayMetrics().densityDpi;
   2497         final int sw = res.getConfiguration().smallestScreenWidthDp;
   2498 
   2499         if (sw < 600) {
   2500             // Smaller than approx 7" tablets, use the regular icon size.
   2501             return density;
   2502         }
   2503 
   2504         switch (density) {
   2505             case DisplayMetrics.DENSITY_LOW:
   2506                 return DisplayMetrics.DENSITY_MEDIUM;
   2507             case DisplayMetrics.DENSITY_MEDIUM:
   2508                 return DisplayMetrics.DENSITY_HIGH;
   2509             case DisplayMetrics.DENSITY_TV:
   2510                 return DisplayMetrics.DENSITY_XHIGH;
   2511             case DisplayMetrics.DENSITY_HIGH:
   2512                 return DisplayMetrics.DENSITY_XHIGH;
   2513             case DisplayMetrics.DENSITY_XHIGH:
   2514                 return DisplayMetrics.DENSITY_XXHIGH;
   2515             case DisplayMetrics.DENSITY_XXHIGH:
   2516                 return DisplayMetrics.DENSITY_XHIGH * 2;
   2517             default:
   2518                 // The density is some abnormal value.  Return some other
   2519                 // abnormal value that is a reasonable scaling of it.
   2520                 return (int)((density*1.5f)+.5f);
   2521         }
   2522     }
   2523 
   2524     /**
   2525      * Get the preferred launcher icon size. This is used when custom drawables
   2526      * are created (e.g., for shortcuts).
   2527      *
   2528      * @return dimensions of square icons in terms of pixels
   2529      */
   2530     public int getLauncherLargeIconSize() {
   2531         return getLauncherLargeIconSizeInner(mContext);
   2532     }
   2533 
   2534     static int getLauncherLargeIconSizeInner(Context context) {
   2535         final Resources res = context.getResources();
   2536         final int size = res.getDimensionPixelSize(android.R.dimen.app_icon_size);
   2537         final int sw = res.getConfiguration().smallestScreenWidthDp;
   2538 
   2539         if (sw < 600) {
   2540             // Smaller than approx 7" tablets, use the regular icon size.
   2541             return size;
   2542         }
   2543 
   2544         final int density = res.getDisplayMetrics().densityDpi;
   2545 
   2546         switch (density) {
   2547             case DisplayMetrics.DENSITY_LOW:
   2548                 return (size * DisplayMetrics.DENSITY_MEDIUM) / DisplayMetrics.DENSITY_LOW;
   2549             case DisplayMetrics.DENSITY_MEDIUM:
   2550                 return (size * DisplayMetrics.DENSITY_HIGH) / DisplayMetrics.DENSITY_MEDIUM;
   2551             case DisplayMetrics.DENSITY_TV:
   2552                 return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
   2553             case DisplayMetrics.DENSITY_HIGH:
   2554                 return (size * DisplayMetrics.DENSITY_XHIGH) / DisplayMetrics.DENSITY_HIGH;
   2555             case DisplayMetrics.DENSITY_XHIGH:
   2556                 return (size * DisplayMetrics.DENSITY_XXHIGH) / DisplayMetrics.DENSITY_XHIGH;
   2557             case DisplayMetrics.DENSITY_XXHIGH:
   2558                 return (size * DisplayMetrics.DENSITY_XHIGH*2) / DisplayMetrics.DENSITY_XXHIGH;
   2559             default:
   2560                 // The density is some abnormal value.  Return some other
   2561                 // abnormal value that is a reasonable scaling of it.
   2562                 return (int)((size*1.5f) + .5f);
   2563         }
   2564     }
   2565 
   2566     /**
   2567      * Returns "true" if the user interface is currently being messed with
   2568      * by a monkey.
   2569      */
   2570     public static boolean isUserAMonkey() {
   2571         try {
   2572             return ActivityManagerNative.getDefault().isUserAMonkey();
   2573         } catch (RemoteException e) {
   2574         }
   2575         return false;
   2576     }
   2577 
   2578     /**
   2579      * Returns "true" if device is running in a test harness.
   2580      */
   2581     public static boolean isRunningInTestHarness() {
   2582         return SystemProperties.getBoolean("ro.test_harness", false);
   2583     }
   2584 
   2585     /**
   2586      * Returns the launch count of each installed package.
   2587      *
   2588      * @hide
   2589      */
   2590     /*public Map<String, Integer> getAllPackageLaunchCounts() {
   2591         try {
   2592             IUsageStats usageStatsService = IUsageStats.Stub.asInterface(
   2593                     ServiceManager.getService("usagestats"));
   2594             if (usageStatsService == null) {
   2595                 return new HashMap<String, Integer>();
   2596             }
   2597 
   2598             UsageStats.PackageStats[] allPkgUsageStats = usageStatsService.getAllPkgUsageStats(
   2599                     ActivityThread.currentPackageName());
   2600             if (allPkgUsageStats == null) {
   2601                 return new HashMap<String, Integer>();
   2602             }
   2603 
   2604             Map<String, Integer> launchCounts = new HashMap<String, Integer>();
   2605             for (UsageStats.PackageStats pkgUsageStats : allPkgUsageStats) {
   2606                 launchCounts.put(pkgUsageStats.getPackageName(), pkgUsageStats.getLaunchCount());
   2607             }
   2608 
   2609             return launchCounts;
   2610         } catch (RemoteException e) {
   2611             Log.w(TAG, "Could not query launch counts", e);
   2612             return new HashMap<String, Integer>();
   2613         }
   2614     }*/
   2615 
   2616     /** @hide */
   2617     public static int checkComponentPermission(String permission, int uid,
   2618             int owningUid, boolean exported) {
   2619         // Root, system server get to do everything.
   2620         final int appId = UserHandle.getAppId(uid);
   2621         if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) {
   2622             return PackageManager.PERMISSION_GRANTED;
   2623         }
   2624         // Isolated processes don't get any permissions.
   2625         if (UserHandle.isIsolated(uid)) {
   2626             return PackageManager.PERMISSION_DENIED;
   2627         }
   2628         // If there is a uid that owns whatever is being accessed, it has
   2629         // blanket access to it regardless of the permissions it requires.
   2630         if (owningUid >= 0 && UserHandle.isSameApp(uid, owningUid)) {
   2631             return PackageManager.PERMISSION_GRANTED;
   2632         }
   2633         // If the target is not exported, then nobody else can get to it.
   2634         if (!exported) {
   2635             /*
   2636             RuntimeException here = new RuntimeException("here");
   2637             here.fillInStackTrace();
   2638             Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid,
   2639                     here);
   2640             */
   2641             return PackageManager.PERMISSION_DENIED;
   2642         }
   2643         if (permission == null) {
   2644             return PackageManager.PERMISSION_GRANTED;
   2645         }
   2646         try {
   2647             return AppGlobals.getPackageManager()
   2648                     .checkUidPermission(permission, uid);
   2649         } catch (RemoteException e) {
   2650             // Should never happen, but if it does... deny!
   2651             Slog.e(TAG, "PackageManager is dead?!?", e);
   2652         }
   2653         return PackageManager.PERMISSION_DENIED;
   2654     }
   2655 
   2656     /** @hide */
   2657     public static int checkUidPermission(String permission, int uid) {
   2658         try {
   2659             return AppGlobals.getPackageManager()
   2660                     .checkUidPermission(permission, uid);
   2661         } catch (RemoteException e) {
   2662             // Should never happen, but if it does... deny!
   2663             Slog.e(TAG, "PackageManager is dead?!?", e);
   2664         }
   2665         return PackageManager.PERMISSION_DENIED;
   2666     }
   2667 
   2668     /**
   2669      * @hide
   2670      * Helper for dealing with incoming user arguments to system service calls.
   2671      * Takes care of checking permissions and converting USER_CURRENT to the
   2672      * actual current user.
   2673      *
   2674      * @param callingPid The pid of the incoming call, as per Binder.getCallingPid().
   2675      * @param callingUid The uid of the incoming call, as per Binder.getCallingUid().
   2676      * @param userId The user id argument supplied by the caller -- this is the user
   2677      * they want to run as.
   2678      * @param allowAll If true, we will allow USER_ALL.  This means you must be prepared
   2679      * to get a USER_ALL returned and deal with it correctly.  If false,
   2680      * an exception will be thrown if USER_ALL is supplied.
   2681      * @param requireFull If true, the caller must hold
   2682      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} to be able to run as a
   2683      * different user than their current process; otherwise they must hold
   2684      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS}.
   2685      * @param name Optional textual name of the incoming call; only for generating error messages.
   2686      * @param callerPackage Optional package name of caller; only for error messages.
   2687      *
   2688      * @return Returns the user ID that the call should run as.  Will always be a concrete
   2689      * user number, unless <var>allowAll</var> is true in which case it could also be
   2690      * USER_ALL.
   2691      */
   2692     public static int handleIncomingUser(int callingPid, int callingUid, int userId,
   2693             boolean allowAll, boolean requireFull, String name, String callerPackage) {
   2694         if (UserHandle.getUserId(callingUid) == userId) {
   2695             return userId;
   2696         }
   2697         try {
   2698             return ActivityManagerNative.getDefault().handleIncomingUser(callingPid,
   2699                     callingUid, userId, allowAll, requireFull, name, callerPackage);
   2700         } catch (RemoteException e) {
   2701             throw new SecurityException("Failed calling activity manager", e);
   2702         }
   2703     }
   2704 
   2705     /**
   2706      * Gets the userId of the current foreground user. Requires system permissions.
   2707      * @hide
   2708      */
   2709     @SystemApi
   2710     public static int getCurrentUser() {
   2711         UserInfo ui;
   2712         try {
   2713             ui = ActivityManagerNative.getDefault().getCurrentUser();
   2714             return ui != null ? ui.id : 0;
   2715         } catch (RemoteException e) {
   2716             return 0;
   2717         }
   2718     }
   2719 
   2720     /**
   2721      * @param userid the user's id. Zero indicates the default user.
   2722      * @hide
   2723      */
   2724     public boolean switchUser(int userid) {
   2725         try {
   2726             return ActivityManagerNative.getDefault().switchUser(userid);
   2727         } catch (RemoteException e) {
   2728             return false;
   2729         }
   2730     }
   2731 
   2732     /**
   2733      * Return whether the given user is actively running.  This means that
   2734      * the user is in the "started" state, not "stopped" -- it is currently
   2735      * allowed to run code through scheduled alarms, receiving broadcasts,
   2736      * etc.  A started user may be either the current foreground user or a
   2737      * background user; the result here does not distinguish between the two.
   2738      * @param userid the user's id. Zero indicates the default user.
   2739      * @hide
   2740      */
   2741     public boolean isUserRunning(int userid) {
   2742         try {
   2743             return ActivityManagerNative.getDefault().isUserRunning(userid, false);
   2744         } catch (RemoteException e) {
   2745             return false;
   2746         }
   2747     }
   2748 
   2749     /**
   2750      * Perform a system dump of various state associated with the given application
   2751      * package name.  This call blocks while the dump is being performed, so should
   2752      * not be done on a UI thread.  The data will be written to the given file
   2753      * descriptor as text.  An application must hold the
   2754      * {@link android.Manifest.permission#DUMP} permission to make this call.
   2755      * @param fd The file descriptor that the dump should be written to.  The file
   2756      * descriptor is <em>not</em> closed by this function; the caller continues to
   2757      * own it.
   2758      * @param packageName The name of the package that is to be dumped.
   2759      */
   2760     public void dumpPackageState(FileDescriptor fd, String packageName) {
   2761         dumpPackageStateStatic(fd, packageName);
   2762     }
   2763 
   2764     /**
   2765      * @hide
   2766      */
   2767     public static void dumpPackageStateStatic(FileDescriptor fd, String packageName) {
   2768         FileOutputStream fout = new FileOutputStream(fd);
   2769         PrintWriter pw = new FastPrintWriter(fout);
   2770         dumpService(pw, fd, "package", new String[] { packageName });
   2771         pw.println();
   2772         dumpService(pw, fd, Context.ACTIVITY_SERVICE, new String[] {
   2773                 "-a", "package", packageName });
   2774         pw.println();
   2775         dumpService(pw, fd, "meminfo", new String[] { "--local", "--package", packageName });
   2776         pw.println();
   2777         dumpService(pw, fd, ProcessStats.SERVICE_NAME, new String[] { packageName });
   2778         pw.println();
   2779         dumpService(pw, fd, "usagestats", new String[] { "--packages", packageName });
   2780         pw.println();
   2781         dumpService(pw, fd, BatteryStats.SERVICE_NAME, new String[] { packageName });
   2782         pw.flush();
   2783     }
   2784 
   2785     private static void dumpService(PrintWriter pw, FileDescriptor fd, String name, String[] args) {
   2786         pw.print("DUMP OF SERVICE "); pw.print(name); pw.println(":");
   2787         IBinder service = ServiceManager.checkService(name);
   2788         if (service == null) {
   2789             pw.println("  (Service not found)");
   2790             return;
   2791         }
   2792         TransferPipe tp = null;
   2793         try {
   2794             pw.flush();
   2795             tp = new TransferPipe();
   2796             tp.setBufferPrefix("  ");
   2797             service.dumpAsync(tp.getWriteFd().getFileDescriptor(), args);
   2798             tp.go(fd, 10000);
   2799         } catch (Throwable e) {
   2800             if (tp != null) {
   2801                 tp.kill();
   2802             }
   2803             pw.println("Failure dumping service:");
   2804             e.printStackTrace(pw);
   2805         }
   2806     }
   2807 
   2808     /**
   2809      * Request that the system start watching for the calling process to exceed a pss
   2810      * size as given here.  Once called, the system will look for any occasions where it
   2811      * sees the associated process with a larger pss size and, when this happens, automatically
   2812      * pull a heap dump from it and allow the user to share the data.  Note that this request
   2813      * continues running even if the process is killed and restarted.  To remove the watch,
   2814      * use {@link #clearWatchHeapLimit()}.
   2815      *
   2816      * <p>This API only work if the calling process has been marked as
   2817      * {@link ApplicationInfo#FLAG_DEBUGGABLE} or this is running on a debuggable
   2818      * (userdebug or eng) build.</p>
   2819      *
   2820      * <p>Callers can optionally implement {@link #ACTION_REPORT_HEAP_LIMIT} to directly
   2821      * handle heap limit reports themselves.</p>
   2822      *
   2823      * @param pssSize The size in bytes to set the limit at.
   2824      */
   2825     public void setWatchHeapLimit(long pssSize) {
   2826         try {
   2827             ActivityManagerNative.getDefault().setDumpHeapDebugLimit(null, 0, pssSize,
   2828                     mContext.getPackageName());
   2829         } catch (RemoteException e) {
   2830         }
   2831     }
   2832 
   2833     /**
   2834      * Action an app can implement to handle reports from {@link #setWatchHeapLimit(long)}.
   2835      * If your package has an activity handling this action, it will be launched with the
   2836      * heap data provided to it the same way as {@link Intent#ACTION_SEND}.  Note that to
   2837      * match the activty must support this action and a MIME type of "*&#47;*".
   2838      */
   2839     public static final String ACTION_REPORT_HEAP_LIMIT = "android.app.action.REPORT_HEAP_LIMIT";
   2840 
   2841     /**
   2842      * Clear a heap watch limit previously set by {@link #setWatchHeapLimit(long)}.
   2843      */
   2844     public void clearWatchHeapLimit() {
   2845         try {
   2846             ActivityManagerNative.getDefault().setDumpHeapDebugLimit(null, 0, 0, null);
   2847         } catch (RemoteException e) {
   2848         }
   2849     }
   2850 
   2851     /**
   2852      * @hide
   2853      */
   2854     public void startLockTaskMode(int taskId) {
   2855         try {
   2856             ActivityManagerNative.getDefault().startLockTaskMode(taskId);
   2857         } catch (RemoteException e) {
   2858         }
   2859     }
   2860 
   2861     /**
   2862      * @hide
   2863      */
   2864     public void stopLockTaskMode() {
   2865         try {
   2866             ActivityManagerNative.getDefault().stopLockTaskMode();
   2867         } catch (RemoteException e) {
   2868         }
   2869     }
   2870 
   2871     /**
   2872      * Return whether currently in lock task mode.  When in this mode
   2873      * no new tasks can be created or switched to.
   2874      *
   2875      * @see Activity#startLockTask()
   2876      *
   2877      * @deprecated Use {@link #getLockTaskModeState} instead.
   2878      */
   2879     public boolean isInLockTaskMode() {
   2880         return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
   2881     }
   2882 
   2883     /**
   2884      * Return the current state of task locking. The three possible outcomes
   2885      * are {@link #LOCK_TASK_MODE_NONE}, {@link #LOCK_TASK_MODE_LOCKED}
   2886      * and {@link #LOCK_TASK_MODE_PINNED}.
   2887      *
   2888      * @see Activity#startLockTask()
   2889      */
   2890     public int getLockTaskModeState() {
   2891         try {
   2892             return ActivityManagerNative.getDefault().getLockTaskModeState();
   2893         } catch (RemoteException e) {
   2894             return ActivityManager.LOCK_TASK_MODE_NONE;
   2895         }
   2896     }
   2897 
   2898     /**
   2899      * The AppTask allows you to manage your own application's tasks.
   2900      * See {@link android.app.ActivityManager#getAppTasks()}
   2901      */
   2902     public static class AppTask {
   2903         private IAppTask mAppTaskImpl;
   2904 
   2905         /** @hide */
   2906         public AppTask(IAppTask task) {
   2907             mAppTaskImpl = task;
   2908         }
   2909 
   2910         /**
   2911          * Finishes all activities in this task and removes it from the recent tasks list.
   2912          */
   2913         public void finishAndRemoveTask() {
   2914             try {
   2915                 mAppTaskImpl.finishAndRemoveTask();
   2916             } catch (RemoteException e) {
   2917                 Slog.e(TAG, "Invalid AppTask", e);
   2918             }
   2919         }
   2920 
   2921         /**
   2922          * Get the RecentTaskInfo associated with this task.
   2923          *
   2924          * @return The RecentTaskInfo for this task, or null if the task no longer exists.
   2925          */
   2926         public RecentTaskInfo getTaskInfo() {
   2927             try {
   2928                 return mAppTaskImpl.getTaskInfo();
   2929             } catch (RemoteException e) {
   2930                 Slog.e(TAG, "Invalid AppTask", e);
   2931                 return null;
   2932             }
   2933         }
   2934 
   2935         /**
   2936          * Bring this task to the foreground.  If it contains activities, they will be
   2937          * brought to the foreground with it and their instances re-created if needed.
   2938          * If it doesn't contain activities, the root activity of the task will be
   2939          * re-launched.
   2940          */
   2941         public void moveToFront() {
   2942             try {
   2943                 mAppTaskImpl.moveToFront();
   2944             } catch (RemoteException e) {
   2945                 Slog.e(TAG, "Invalid AppTask", e);
   2946             }
   2947         }
   2948 
   2949         /**
   2950          * Start an activity in this task.  Brings the task to the foreground.  If this task
   2951          * is not currently active (that is, its id < 0), then a new activity for the given
   2952          * Intent will be launched as the root of the task and the task brought to the
   2953          * foreground.  Otherwise, if this task is currently active and the Intent does not specify
   2954          * an activity to launch in a new task, then a new activity for the given Intent will
   2955          * be launched on top of the task and the task brought to the foreground.  If this
   2956          * task is currently active and the Intent specifies {@link Intent#FLAG_ACTIVITY_NEW_TASK}
   2957          * or would otherwise be launched in to a new task, then the activity not launched but
   2958          * this task be brought to the foreground and a new intent delivered to the top
   2959          * activity if appropriate.
   2960          *
   2961          * <p>In other words, you generally want to use an Intent here that does not specify
   2962          * {@link Intent#FLAG_ACTIVITY_NEW_TASK} or {@link Intent#FLAG_ACTIVITY_NEW_DOCUMENT},
   2963          * and let the system do the right thing.</p>
   2964          *
   2965          * @param intent The Intent describing the new activity to be launched on the task.
   2966          * @param options Optional launch options.
   2967          *
   2968          * @see Activity#startActivity(android.content.Intent, android.os.Bundle)
   2969          */
   2970         public void startActivity(Context context, Intent intent, Bundle options) {
   2971             ActivityThread thread = ActivityThread.currentActivityThread();
   2972             thread.getInstrumentation().execStartActivityFromAppTask(context,
   2973                     thread.getApplicationThread(), mAppTaskImpl, intent, options);
   2974         }
   2975 
   2976         /**
   2977          * Modify the {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} flag in the root
   2978          * Intent of this AppTask.
   2979          *
   2980          * @param exclude If true, {@link Intent#FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS} will
   2981          * be set; otherwise, it will be cleared.
   2982          */
   2983         public void setExcludeFromRecents(boolean exclude) {
   2984             try {
   2985                 mAppTaskImpl.setExcludeFromRecents(exclude);
   2986             } catch (RemoteException e) {
   2987                 Slog.e(TAG, "Invalid AppTask", e);
   2988             }
   2989         }
   2990     }
   2991 }
   2992