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