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