Home | History | Annotate | Download | only in am
      1 /*
      2  * Copyright (C) 2006-2008 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 com.android.server.am;
     18 
     19 import static android.Manifest.permission.INTERACT_ACROSS_USERS;
     20 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
     21 import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
     22 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
     23 import static com.android.internal.util.XmlUtils.readBooleanAttribute;
     24 import static com.android.internal.util.XmlUtils.readIntAttribute;
     25 import static com.android.internal.util.XmlUtils.readLongAttribute;
     26 import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
     27 import static com.android.internal.util.XmlUtils.writeIntAttribute;
     28 import static com.android.internal.util.XmlUtils.writeLongAttribute;
     29 import static com.android.server.Watchdog.NATIVE_STACKS_OF_INTEREST;
     30 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
     31 import static org.xmlpull.v1.XmlPullParser.START_TAG;
     32 import static com.android.server.am.ActivityStackSupervisor.HOME_STACK_ID;
     33 import static com.android.server.am.TaskRecord.INVALID_TASK_ID;
     34 
     35 import android.Manifest;
     36 import android.app.AppOpsManager;
     37 import android.app.ApplicationThreadNative;
     38 import android.app.IActivityContainer;
     39 import android.app.IActivityContainerCallback;
     40 import android.app.IAppTask;
     41 import android.app.ITaskStackListener;
     42 import android.app.ProfilerInfo;
     43 import android.app.admin.DevicePolicyManager;
     44 import android.app.usage.UsageEvents;
     45 import android.app.usage.UsageStatsManagerInternal;
     46 import android.appwidget.AppWidgetManager;
     47 import android.content.res.Resources;
     48 import android.graphics.Bitmap;
     49 import android.graphics.Point;
     50 import android.graphics.Rect;
     51 import android.os.BatteryStats;
     52 import android.os.PersistableBundle;
     53 import android.os.storage.IMountService;
     54 import android.os.storage.StorageManager;
     55 import android.service.voice.IVoiceInteractionSession;
     56 import android.util.ArrayMap;
     57 import android.util.ArraySet;
     58 import android.util.SparseIntArray;
     59 
     60 import android.view.Display;
     61 import com.android.internal.R;
     62 import com.android.internal.annotations.GuardedBy;
     63 import com.android.internal.app.IAppOpsService;
     64 import com.android.internal.app.IVoiceInteractor;
     65 import com.android.internal.app.ProcessMap;
     66 import com.android.internal.app.ProcessStats;
     67 import com.android.internal.os.BackgroundThread;
     68 import com.android.internal.os.BatteryStatsImpl;
     69 import com.android.internal.os.ProcessCpuTracker;
     70 import com.android.internal.os.TransferPipe;
     71 import com.android.internal.os.Zygote;
     72 import com.android.internal.util.FastPrintWriter;
     73 import com.android.internal.util.FastXmlSerializer;
     74 import com.android.internal.util.MemInfoReader;
     75 import com.android.internal.util.Preconditions;
     76 import com.android.server.AppOpsService;
     77 import com.android.server.AttributeCache;
     78 import com.android.server.IntentResolver;
     79 import com.android.server.LocalServices;
     80 import com.android.server.ServiceThread;
     81 import com.android.server.SystemService;
     82 import com.android.server.SystemServiceManager;
     83 import com.android.server.Watchdog;
     84 import com.android.server.am.ActivityStack.ActivityState;
     85 import com.android.server.firewall.IntentFirewall;
     86 import com.android.server.pm.Installer;
     87 import com.android.server.pm.UserManagerService;
     88 import com.android.server.statusbar.StatusBarManagerInternal;
     89 import com.android.server.wm.AppTransition;
     90 import com.android.server.wm.WindowManagerService;
     91 import com.google.android.collect.Lists;
     92 import com.google.android.collect.Maps;
     93 
     94 import libcore.io.IoUtils;
     95 
     96 import org.xmlpull.v1.XmlPullParser;
     97 import org.xmlpull.v1.XmlPullParserException;
     98 import org.xmlpull.v1.XmlSerializer;
     99 
    100 import android.app.Activity;
    101 import android.app.ActivityManager;
    102 import android.app.ActivityManager.RunningTaskInfo;
    103 import android.app.ActivityManager.StackInfo;
    104 import android.app.ActivityManagerInternal;
    105 import android.app.ActivityManagerNative;
    106 import android.app.ActivityOptions;
    107 import android.app.ActivityThread;
    108 import android.app.AlertDialog;
    109 import android.app.AppGlobals;
    110 import android.app.ApplicationErrorReport;
    111 import android.app.Dialog;
    112 import android.app.IActivityController;
    113 import android.app.IApplicationThread;
    114 import android.app.IInstrumentationWatcher;
    115 import android.app.INotificationManager;
    116 import android.app.IProcessObserver;
    117 import android.app.IServiceConnection;
    118 import android.app.IStopUserCallback;
    119 import android.app.IUiAutomationConnection;
    120 import android.app.IUserSwitchObserver;
    121 import android.app.Instrumentation;
    122 import android.app.Notification;
    123 import android.app.NotificationManager;
    124 import android.app.PendingIntent;
    125 import android.app.backup.IBackupManager;
    126 import android.content.ActivityNotFoundException;
    127 import android.content.BroadcastReceiver;
    128 import android.content.ClipData;
    129 import android.content.ComponentCallbacks2;
    130 import android.content.ComponentName;
    131 import android.content.ContentProvider;
    132 import android.content.ContentResolver;
    133 import android.content.Context;
    134 import android.content.DialogInterface;
    135 import android.content.IContentProvider;
    136 import android.content.IIntentReceiver;
    137 import android.content.IIntentSender;
    138 import android.content.Intent;
    139 import android.content.IntentFilter;
    140 import android.content.IntentSender;
    141 import android.content.pm.ActivityInfo;
    142 import android.content.pm.ApplicationInfo;
    143 import android.content.pm.ConfigurationInfo;
    144 import android.content.pm.IPackageDataObserver;
    145 import android.content.pm.IPackageManager;
    146 import android.content.pm.InstrumentationInfo;
    147 import android.content.pm.PackageInfo;
    148 import android.content.pm.PackageManager;
    149 import android.content.pm.ParceledListSlice;
    150 import android.content.pm.UserInfo;
    151 import android.content.pm.PackageManager.NameNotFoundException;
    152 import android.content.pm.PathPermission;
    153 import android.content.pm.ProviderInfo;
    154 import android.content.pm.ResolveInfo;
    155 import android.content.pm.ServiceInfo;
    156 import android.content.res.CompatibilityInfo;
    157 import android.content.res.Configuration;
    158 import android.net.Proxy;
    159 import android.net.ProxyInfo;
    160 import android.net.Uri;
    161 import android.os.Binder;
    162 import android.os.Build;
    163 import android.os.Bundle;
    164 import android.os.Debug;
    165 import android.os.DropBoxManager;
    166 import android.os.Environment;
    167 import android.os.FactoryTest;
    168 import android.os.FileObserver;
    169 import android.os.FileUtils;
    170 import android.os.Handler;
    171 import android.os.IBinder;
    172 import android.os.IPermissionController;
    173 import android.os.IRemoteCallback;
    174 import android.os.IUserManager;
    175 import android.os.Looper;
    176 import android.os.Message;
    177 import android.os.Parcel;
    178 import android.os.ParcelFileDescriptor;
    179 import android.os.PowerManagerInternal;
    180 import android.os.Process;
    181 import android.os.RemoteCallbackList;
    182 import android.os.RemoteException;
    183 import android.os.SELinux;
    184 import android.os.ServiceManager;
    185 import android.os.StrictMode;
    186 import android.os.SystemClock;
    187 import android.os.SystemProperties;
    188 import android.os.UpdateLock;
    189 import android.os.UserHandle;
    190 import android.os.UserManager;
    191 import android.provider.Settings;
    192 import android.text.format.DateUtils;
    193 import android.text.format.Time;
    194 import android.util.AtomicFile;
    195 import android.util.EventLog;
    196 import android.util.Log;
    197 import android.util.Pair;
    198 import android.util.PrintWriterPrinter;
    199 import android.util.Slog;
    200 import android.util.SparseArray;
    201 import android.util.TimeUtils;
    202 import android.util.Xml;
    203 import android.view.Gravity;
    204 import android.view.LayoutInflater;
    205 import android.view.View;
    206 import android.view.WindowManager;
    207 
    208 import dalvik.system.VMRuntime;
    209 
    210 import java.io.BufferedInputStream;
    211 import java.io.BufferedOutputStream;
    212 import java.io.DataInputStream;
    213 import java.io.DataOutputStream;
    214 import java.io.File;
    215 import java.io.FileDescriptor;
    216 import java.io.FileInputStream;
    217 import java.io.FileNotFoundException;
    218 import java.io.FileOutputStream;
    219 import java.io.IOException;
    220 import java.io.InputStreamReader;
    221 import java.io.PrintWriter;
    222 import java.io.StringWriter;
    223 import java.lang.ref.WeakReference;
    224 import java.util.ArrayList;
    225 import java.util.Arrays;
    226 import java.util.Collections;
    227 import java.util.Comparator;
    228 import java.util.HashMap;
    229 import java.util.HashSet;
    230 import java.util.Iterator;
    231 import java.util.List;
    232 import java.util.Locale;
    233 import java.util.Map;
    234 import java.util.Set;
    235 import java.util.concurrent.atomic.AtomicBoolean;
    236 import java.util.concurrent.atomic.AtomicLong;
    237 
    238 public final class ActivityManagerService extends ActivityManagerNative
    239         implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
    240 
    241     private static final String USER_DATA_DIR = "/data/user/";
    242     // File that stores last updated system version and called preboot receivers
    243     static final String CALLED_PRE_BOOTS_FILENAME = "called_pre_boots.dat";
    244 
    245     static final String TAG = "ActivityManager";
    246     static final String TAG_MU = "ActivityManagerServiceMU";
    247     static final boolean DEBUG = false;
    248     static final boolean localLOGV = DEBUG;
    249     static final boolean DEBUG_BACKUP = localLOGV || false;
    250     static final boolean DEBUG_BROADCAST = localLOGV || false;
    251     static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
    252     static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
    253     static final boolean DEBUG_CLEANUP = localLOGV || false;
    254     static final boolean DEBUG_CONFIGURATION = localLOGV || false;
    255     static final boolean DEBUG_FOCUS = false;
    256     static final boolean DEBUG_IMMERSIVE = localLOGV || false;
    257     static final boolean DEBUG_MU = localLOGV || false;
    258     static final boolean DEBUG_OOM_ADJ = localLOGV || false;
    259     static final boolean DEBUG_LRU = localLOGV || false;
    260     static final boolean DEBUG_PAUSE = localLOGV || false;
    261     static final boolean DEBUG_POWER = localLOGV || false;
    262     static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
    263     static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
    264     static final boolean DEBUG_PROCESSES = localLOGV || false;
    265     static final boolean DEBUG_PROVIDER = localLOGV || false;
    266     static final boolean DEBUG_RESULTS = localLOGV || false;
    267     static final boolean DEBUG_SERVICE = localLOGV || false;
    268     static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
    269     static final boolean DEBUG_STACK = localLOGV || false;
    270     static final boolean DEBUG_SWITCH = localLOGV || false;
    271     static final boolean DEBUG_TASKS = localLOGV || false;
    272     static final boolean DEBUG_THUMBNAILS = localLOGV || false;
    273     static final boolean DEBUG_TRANSITION = localLOGV || false;
    274     static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
    275     static final boolean DEBUG_USER_LEAVING = localLOGV || false;
    276     static final boolean DEBUG_VISBILITY = localLOGV || false;
    277     static final boolean DEBUG_PSS = localLOGV || false;
    278     static final boolean DEBUG_LOCKSCREEN = localLOGV || false;
    279     static final boolean DEBUG_RECENTS = localLOGV || false;
    280     static final boolean VALIDATE_TOKENS = false;
    281     static final boolean SHOW_ACTIVITY_START_TIME = true;
    282 
    283     // Control over CPU and battery monitoring.
    284     static final long BATTERY_STATS_TIME = 30*60*1000;      // write battery stats every 30 minutes.
    285     static final boolean MONITOR_CPU_USAGE = true;
    286     static final long MONITOR_CPU_MIN_TIME = 5*1000;        // don't sample cpu less than every 5 seconds.
    287     static final long MONITOR_CPU_MAX_TIME = 0x0fffffff;    // wait possibly forever for next cpu sample.
    288     static final boolean MONITOR_THREAD_CPU_USAGE = false;
    289 
    290     // The flags that are set for all calls we make to the package manager.
    291     static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
    292 
    293     private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
    294 
    295     static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
    296 
    297     // Maximum number recent bitmaps to keep in memory.
    298     static final int MAX_RECENT_BITMAPS = 3;
    299 
    300     // Amount of time after a call to stopAppSwitches() during which we will
    301     // prevent further untrusted switches from happening.
    302     static final long APP_SWITCH_DELAY_TIME = 5*1000;
    303 
    304     // How long we wait for a launched process to attach to the activity manager
    305     // before we decide it's never going to come up for real.
    306     static final int PROC_START_TIMEOUT = 10*1000;
    307 
    308     // How long we wait for a launched process to attach to the activity manager
    309     // before we decide it's never going to come up for real, when the process was
    310     // started with a wrapper for instrumentation (such as Valgrind) because it
    311     // could take much longer than usual.
    312     static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000;
    313 
    314     // How long to wait after going idle before forcing apps to GC.
    315     static final int GC_TIMEOUT = 5*1000;
    316 
    317     // The minimum amount of time between successive GC requests for a process.
    318     static final int GC_MIN_INTERVAL = 60*1000;
    319 
    320     // The minimum amount of time between successive PSS requests for a process.
    321     static final int FULL_PSS_MIN_INTERVAL = 10*60*1000;
    322 
    323     // The minimum amount of time between successive PSS requests for a process
    324     // when the request is due to the memory state being lowered.
    325     static final int FULL_PSS_LOWERED_INTERVAL = 2*60*1000;
    326 
    327     // The rate at which we check for apps using excessive power -- 15 mins.
    328     static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
    329 
    330     // The minimum sample duration we will allow before deciding we have
    331     // enough data on wake locks to start killing things.
    332     static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
    333 
    334     // The minimum sample duration we will allow before deciding we have
    335     // enough data on CPU usage to start killing things.
    336     static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
    337 
    338     // How long we allow a receiver to run before giving up on it.
    339     static final int BROADCAST_FG_TIMEOUT = 10*1000;
    340     static final int BROADCAST_BG_TIMEOUT = 60*1000;
    341 
    342     // How long we wait until we timeout on key dispatching.
    343     static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
    344 
    345     // How long we wait until we timeout on key dispatching during instrumentation.
    346     static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
    347 
    348     // Amount of time we wait for observers to handle a user switch before
    349     // giving up on them and unfreezing the screen.
    350     static final int USER_SWITCH_TIMEOUT = 2*1000;
    351 
    352     // Maximum number of users we allow to be running at a time.
    353     static final int MAX_RUNNING_USERS = 3;
    354 
    355     // How long to wait in getAssistContextExtras for the activity and foreground services
    356     // to respond with the result.
    357     static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
    358 
    359     // Maximum number of persisted Uri grants a package is allowed
    360     static final int MAX_PERSISTED_URI_GRANTS = 128;
    361 
    362     static final int MY_PID = Process.myPid();
    363 
    364     static final String[] EMPTY_STRING_ARRAY = new String[0];
    365 
    366     // How many bytes to write into the dropbox log before truncating
    367     static final int DROPBOX_MAX_SIZE = 256 * 1024;
    368 
    369     // Access modes for handleIncomingUser.
    370     static final int ALLOW_NON_FULL = 0;
    371     static final int ALLOW_NON_FULL_IN_PROFILE = 1;
    372     static final int ALLOW_FULL_ONLY = 2;
    373 
    374     static final int LAST_PREBOOT_DELIVERED_FILE_VERSION = 10000;
    375 
    376     // Delay in notifying task stack change listeners (in millis)
    377     static final int NOTIFY_TASK_STACK_CHANGE_LISTENERS_DELAY = 1000;
    378 
    379     /** All system services */
    380     SystemServiceManager mSystemServiceManager;
    381 
    382     private Installer mInstaller;
    383 
    384     /** Run all ActivityStacks through this */
    385     ActivityStackSupervisor mStackSupervisor;
    386 
    387     /** Task stack change listeners. */
    388     private RemoteCallbackList<ITaskStackListener> mTaskStackListeners =
    389             new RemoteCallbackList<ITaskStackListener>();
    390 
    391     public IntentFirewall mIntentFirewall;
    392 
    393     // Whether we should show our dialogs (ANR, crash, etc) or just perform their
    394     // default actuion automatically.  Important for devices without direct input
    395     // devices.
    396     private boolean mShowDialogs = true;
    397 
    398     BroadcastQueue mFgBroadcastQueue;
    399     BroadcastQueue mBgBroadcastQueue;
    400     // Convenient for easy iteration over the queues. Foreground is first
    401     // so that dispatch of foreground broadcasts gets precedence.
    402     final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
    403 
    404     BroadcastQueue broadcastQueueForIntent(Intent intent) {
    405         final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
    406         if (DEBUG_BACKGROUND_BROADCAST) {
    407             Slog.i(TAG, "Broadcast intent " + intent + " on "
    408                     + (isFg ? "foreground" : "background")
    409                     + " queue");
    410         }
    411         return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
    412     }
    413 
    414     BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
    415         for (BroadcastQueue queue : mBroadcastQueues) {
    416             BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
    417             if (r != null) {
    418                 return r;
    419             }
    420         }
    421         return null;
    422     }
    423 
    424     /**
    425      * Activity we have told the window manager to have key focus.
    426      */
    427     ActivityRecord mFocusedActivity = null;
    428 
    429     /**
    430      * List of intents that were used to start the most recent tasks.
    431      */
    432     ArrayList<TaskRecord> mRecentTasks;
    433     ArrayList<TaskRecord> mTmpRecents = new ArrayList<TaskRecord>();
    434 
    435     /**
    436      * For addAppTask: cached of the last activity component that was added.
    437      */
    438     ComponentName mLastAddedTaskComponent;
    439 
    440     /**
    441      * For addAppTask: cached of the last activity uid that was added.
    442      */
    443     int mLastAddedTaskUid;
    444 
    445     /**
    446      * For addAppTask: cached of the last ActivityInfo that was added.
    447      */
    448     ActivityInfo mLastAddedTaskActivity;
    449 
    450     public class PendingAssistExtras extends Binder implements Runnable {
    451         public final ActivityRecord activity;
    452         public final Bundle extras;
    453         public final Intent intent;
    454         public final String hint;
    455         public final int userHandle;
    456         public boolean haveResult = false;
    457         public Bundle result = null;
    458         public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
    459                 String _hint, int _userHandle) {
    460             activity = _activity;
    461             extras = _extras;
    462             intent = _intent;
    463             hint = _hint;
    464             userHandle = _userHandle;
    465         }
    466         @Override
    467         public void run() {
    468             Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
    469             synchronized (this) {
    470                 haveResult = true;
    471                 notifyAll();
    472             }
    473         }
    474     }
    475 
    476     final ArrayList<PendingAssistExtras> mPendingAssistExtras
    477             = new ArrayList<PendingAssistExtras>();
    478 
    479     /**
    480      * Process management.
    481      */
    482     final ProcessList mProcessList = new ProcessList();
    483 
    484     /**
    485      * All of the applications we currently have running organized by name.
    486      * The keys are strings of the application package name (as
    487      * returned by the package manager), and the keys are ApplicationRecord
    488      * objects.
    489      */
    490     final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
    491 
    492     /**
    493      * Tracking long-term execution of processes to look for abuse and other
    494      * bad app behavior.
    495      */
    496     final ProcessStatsService mProcessStats;
    497 
    498     /**
    499      * The currently running isolated processes.
    500      */
    501     final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
    502 
    503     /**
    504      * Counter for assigning isolated process uids, to avoid frequently reusing the
    505      * same ones.
    506      */
    507     int mNextIsolatedProcessUid = 0;
    508 
    509     /**
    510      * The currently running heavy-weight process, if any.
    511      */
    512     ProcessRecord mHeavyWeightProcess = null;
    513 
    514     /**
    515      * The last time that various processes have crashed.
    516      */
    517     final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
    518 
    519     /**
    520      * Information about a process that is currently marked as bad.
    521      */
    522     static final class BadProcessInfo {
    523         BadProcessInfo(long time, String shortMsg, String longMsg, String stack) {
    524             this.time = time;
    525             this.shortMsg = shortMsg;
    526             this.longMsg = longMsg;
    527             this.stack = stack;
    528         }
    529 
    530         final long time;
    531         final String shortMsg;
    532         final String longMsg;
    533         final String stack;
    534     }
    535 
    536     /**
    537      * Set of applications that we consider to be bad, and will reject
    538      * incoming broadcasts from (which the user has no control over).
    539      * Processes are added to this set when they have crashed twice within
    540      * a minimum amount of time; they are removed from it when they are
    541      * later restarted (hopefully due to some user action).  The value is the
    542      * time it was added to the list.
    543      */
    544     final ProcessMap<BadProcessInfo> mBadProcesses = new ProcessMap<BadProcessInfo>();
    545 
    546     /**
    547      * All of the processes we currently have running organized by pid.
    548      * The keys are the pid running the application.
    549      *
    550      * <p>NOTE: This object is protected by its own lock, NOT the global
    551      * activity manager lock!
    552      */
    553     final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
    554 
    555     /**
    556      * All of the processes that have been forced to be foreground.  The key
    557      * is the pid of the caller who requested it (we hold a death
    558      * link on it).
    559      */
    560     abstract class ForegroundToken implements IBinder.DeathRecipient {
    561         int pid;
    562         IBinder token;
    563     }
    564     final SparseArray<ForegroundToken> mForegroundProcesses = new SparseArray<ForegroundToken>();
    565 
    566     /**
    567      * List of records for processes that someone had tried to start before the
    568      * system was ready.  We don't start them at that point, but ensure they
    569      * are started by the time booting is complete.
    570      */
    571     final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>();
    572 
    573     /**
    574      * List of persistent applications that are in the process
    575      * of being started.
    576      */
    577     final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>();
    578 
    579     /**
    580      * Processes that are being forcibly torn down.
    581      */
    582     final ArrayList<ProcessRecord> mRemovedProcesses = new ArrayList<ProcessRecord>();
    583 
    584     /**
    585      * List of running applications, sorted by recent usage.
    586      * The first entry in the list is the least recently used.
    587      */
    588     final ArrayList<ProcessRecord> mLruProcesses = new ArrayList<ProcessRecord>();
    589 
    590     /**
    591      * Where in mLruProcesses that the processes hosting activities start.
    592      */
    593     int mLruProcessActivityStart = 0;
    594 
    595     /**
    596      * Where in mLruProcesses that the processes hosting services start.
    597      * This is after (lower index) than mLruProcessesActivityStart.
    598      */
    599     int mLruProcessServiceStart = 0;
    600 
    601     /**
    602      * List of processes that should gc as soon as things are idle.
    603      */
    604     final ArrayList<ProcessRecord> mProcessesToGc = new ArrayList<ProcessRecord>();
    605 
    606     /**
    607      * Processes we want to collect PSS data from.
    608      */
    609     final ArrayList<ProcessRecord> mPendingPssProcesses = new ArrayList<ProcessRecord>();
    610 
    611     /**
    612      * Last time we requested PSS data of all processes.
    613      */
    614     long mLastFullPssTime = SystemClock.uptimeMillis();
    615 
    616     /**
    617      * If set, the next time we collect PSS data we should do a full collection
    618      * with data from native processes and the kernel.
    619      */
    620     boolean mFullPssPending = false;
    621 
    622     /**
    623      * This is the process holding what we currently consider to be
    624      * the "home" activity.
    625      */
    626     ProcessRecord mHomeProcess;
    627 
    628     /**
    629      * This is the process holding the activity the user last visited that
    630      * is in a different process from the one they are currently in.
    631      */
    632     ProcessRecord mPreviousProcess;
    633 
    634     /**
    635      * The time at which the previous process was last visible.
    636      */
    637     long mPreviousProcessVisibleTime;
    638 
    639     /**
    640      * Which uses have been started, so are allowed to run code.
    641      */
    642     final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
    643 
    644     /**
    645      * LRU list of history of current users.  Most recently current is at the end.
    646      */
    647     final ArrayList<Integer> mUserLru = new ArrayList<Integer>();
    648 
    649     /**
    650      * Constant array of the users that are currently started.
    651      */
    652     int[] mStartedUserArray = new int[] { 0 };
    653 
    654     /**
    655      * Registered observers of the user switching mechanics.
    656      */
    657     final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
    658             = new RemoteCallbackList<IUserSwitchObserver>();
    659 
    660     /**
    661      * Currently active user switch.
    662      */
    663     Object mCurUserSwitchCallback;
    664 
    665     /**
    666      * Packages that the user has asked to have run in screen size
    667      * compatibility mode instead of filling the screen.
    668      */
    669     final CompatModePackages mCompatModePackages;
    670 
    671     /**
    672      * Set of IntentSenderRecord objects that are currently active.
    673      */
    674     final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
    675             = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
    676 
    677     /**
    678      * Fingerprints (hashCode()) of stack traces that we've
    679      * already logged DropBox entries for.  Guarded by itself.  If
    680      * something (rogue user app) forces this over
    681      * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
    682      */
    683     private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
    684     private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
    685 
    686     /**
    687      * Strict Mode background batched logging state.
    688      *
    689      * The string buffer is guarded by itself, and its lock is also
    690      * used to determine if another batched write is already
    691      * in-flight.
    692      */
    693     private final StringBuilder mStrictModeBuffer = new StringBuilder();
    694 
    695     /**
    696      * Keeps track of all IIntentReceivers that have been registered for
    697      * broadcasts.  Hash keys are the receiver IBinder, hash value is
    698      * a ReceiverList.
    699      */
    700     final HashMap<IBinder, ReceiverList> mRegisteredReceivers =
    701             new HashMap<IBinder, ReceiverList>();
    702 
    703     /**
    704      * Resolver for broadcast intents to registered receivers.
    705      * Holds BroadcastFilter (subclass of IntentFilter).
    706      */
    707     final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
    708             = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
    709         @Override
    710         protected boolean allowFilterResult(
    711                 BroadcastFilter filter, List<BroadcastFilter> dest) {
    712             IBinder target = filter.receiverList.receiver.asBinder();
    713             for (int i=dest.size()-1; i>=0; i--) {
    714                 if (dest.get(i).receiverList.receiver.asBinder() == target) {
    715                     return false;
    716                 }
    717             }
    718             return true;
    719         }
    720 
    721         @Override
    722         protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
    723             if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
    724                     || userId == filter.owningUserId) {
    725                 return super.newResult(filter, match, userId);
    726             }
    727             return null;
    728         }
    729 
    730         @Override
    731         protected BroadcastFilter[] newArray(int size) {
    732             return new BroadcastFilter[size];
    733         }
    734 
    735         @Override
    736         protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) {
    737             return packageName.equals(filter.packageName);
    738         }
    739     };
    740 
    741     /**
    742      * State of all active sticky broadcasts per user.  Keys are the action of the
    743      * sticky Intent, values are an ArrayList of all broadcasted intents with
    744      * that action (which should usually be one).  The SparseArray is keyed
    745      * by the user ID the sticky is for, and can include UserHandle.USER_ALL
    746      * for stickies that are sent to all users.
    747      */
    748     final SparseArray<ArrayMap<String, ArrayList<Intent>>> mStickyBroadcasts =
    749             new SparseArray<ArrayMap<String, ArrayList<Intent>>>();
    750 
    751     final ActiveServices mServices;
    752 
    753     final static class Association {
    754         final int mSourceUid;
    755         final String mSourceProcess;
    756         final int mTargetUid;
    757         final ComponentName mTargetComponent;
    758         final String mTargetProcess;
    759 
    760         int mCount;
    761         long mTime;
    762 
    763         int mNesting;
    764         long mStartTime;
    765 
    766         Association(int sourceUid, String sourceProcess, int targetUid,
    767                 ComponentName targetComponent, String targetProcess) {
    768             mSourceUid = sourceUid;
    769             mSourceProcess = sourceProcess;
    770             mTargetUid = targetUid;
    771             mTargetComponent = targetComponent;
    772             mTargetProcess = targetProcess;
    773         }
    774     }
    775 
    776     /**
    777      * When service association tracking is enabled, this is all of the associations we
    778      * have seen.  Mapping is target uid -> target component -> source uid -> source process name
    779      * -> association data.
    780      */
    781     final SparseArray<ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>>>
    782             mAssociations = new SparseArray<>();
    783     boolean mTrackingAssociations;
    784 
    785     /**
    786      * Backup/restore process management
    787      */
    788     String mBackupAppName = null;
    789     BackupRecord mBackupTarget = null;
    790 
    791     final ProviderMap mProviderMap;
    792 
    793     /**
    794      * List of content providers who have clients waiting for them.  The
    795      * application is currently being launched and the provider will be
    796      * removed from this list once it is published.
    797      */
    798     final ArrayList<ContentProviderRecord> mLaunchingProviders
    799             = new ArrayList<ContentProviderRecord>();
    800 
    801     /**
    802      * File storing persisted {@link #mGrantedUriPermissions}.
    803      */
    804     private final AtomicFile mGrantFile;
    805 
    806     /** XML constants used in {@link #mGrantFile} */
    807     private static final String TAG_URI_GRANTS = "uri-grants";
    808     private static final String TAG_URI_GRANT = "uri-grant";
    809     private static final String ATTR_USER_HANDLE = "userHandle";
    810     private static final String ATTR_SOURCE_USER_ID = "sourceUserId";
    811     private static final String ATTR_TARGET_USER_ID = "targetUserId";
    812     private static final String ATTR_SOURCE_PKG = "sourcePkg";
    813     private static final String ATTR_TARGET_PKG = "targetPkg";
    814     private static final String ATTR_URI = "uri";
    815     private static final String ATTR_MODE_FLAGS = "modeFlags";
    816     private static final String ATTR_CREATED_TIME = "createdTime";
    817     private static final String ATTR_PREFIX = "prefix";
    818 
    819     /**
    820      * Global set of specific {@link Uri} permissions that have been granted.
    821      * This optimized lookup structure maps from {@link UriPermission#targetUid}
    822      * to {@link UriPermission#uri} to {@link UriPermission}.
    823      */
    824     @GuardedBy("this")
    825     private final SparseArray<ArrayMap<GrantUri, UriPermission>>
    826             mGrantedUriPermissions = new SparseArray<ArrayMap<GrantUri, UriPermission>>();
    827 
    828     public static class GrantUri {
    829         public final int sourceUserId;
    830         public final Uri uri;
    831         public boolean prefix;
    832 
    833         public GrantUri(int sourceUserId, Uri uri, boolean prefix) {
    834             this.sourceUserId = sourceUserId;
    835             this.uri = uri;
    836             this.prefix = prefix;
    837         }
    838 
    839         @Override
    840         public int hashCode() {
    841             int hashCode = 1;
    842             hashCode = 31 * hashCode + sourceUserId;
    843             hashCode = 31 * hashCode + uri.hashCode();
    844             hashCode = 31 * hashCode + (prefix ? 1231 : 1237);
    845             return hashCode;
    846         }
    847 
    848         @Override
    849         public boolean equals(Object o) {
    850             if (o instanceof GrantUri) {
    851                 GrantUri other = (GrantUri) o;
    852                 return uri.equals(other.uri) && (sourceUserId == other.sourceUserId)
    853                         && prefix == other.prefix;
    854             }
    855             return false;
    856         }
    857 
    858         @Override
    859         public String toString() {
    860             String result = Integer.toString(sourceUserId) + " @ " + uri.toString();
    861             if (prefix) result += " [prefix]";
    862             return result;
    863         }
    864 
    865         public String toSafeString() {
    866             String result = Integer.toString(sourceUserId) + " @ " + uri.toSafeString();
    867             if (prefix) result += " [prefix]";
    868             return result;
    869         }
    870 
    871         public static GrantUri resolve(int defaultSourceUserHandle, Uri uri) {
    872             return new GrantUri(ContentProvider.getUserIdFromUri(uri, defaultSourceUserHandle),
    873                     ContentProvider.getUriWithoutUserId(uri), false);
    874         }
    875     }
    876 
    877     CoreSettingsObserver mCoreSettingsObserver;
    878 
    879     /**
    880      * Thread-local storage used to carry caller permissions over through
    881      * indirect content-provider access.
    882      */
    883     private class Identity {
    884         public final IBinder token;
    885         public final int pid;
    886         public final int uid;
    887 
    888         Identity(IBinder _token, int _pid, int _uid) {
    889             token = _token;
    890             pid = _pid;
    891             uid = _uid;
    892         }
    893     }
    894 
    895     private static final ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
    896 
    897     /**
    898      * All information we have collected about the runtime performance of
    899      * any user id that can impact battery performance.
    900      */
    901     final BatteryStatsService mBatteryStatsService;
    902 
    903     /**
    904      * Information about component usage
    905      */
    906     UsageStatsManagerInternal mUsageStatsService;
    907 
    908     /**
    909      * Information about and control over application operations
    910      */
    911     final AppOpsService mAppOpsService;
    912 
    913     /**
    914      * Save recent tasks information across reboots.
    915      */
    916     final TaskPersister mTaskPersister;
    917 
    918     /**
    919      * Current configuration information.  HistoryRecord objects are given
    920      * a reference to this object to indicate which configuration they are
    921      * currently running in, so this object must be kept immutable.
    922      */
    923     Configuration mConfiguration = new Configuration();
    924 
    925     /**
    926      * Current sequencing integer of the configuration, for skipping old
    927      * configurations.
    928      */
    929     int mConfigurationSeq = 0;
    930 
    931     /**
    932      * Hardware-reported OpenGLES version.
    933      */
    934     final int GL_ES_VERSION;
    935 
    936     /**
    937      * List of initialization arguments to pass to all processes when binding applications to them.
    938      * For example, references to the commonly used services.
    939      */
    940     HashMap<String, IBinder> mAppBindArgs;
    941 
    942     /**
    943      * Temporary to avoid allocations.  Protected by main lock.
    944      */
    945     final StringBuilder mStringBuilder = new StringBuilder(256);
    946 
    947     /**
    948      * Used to control how we initialize the service.
    949      */
    950     ComponentName mTopComponent;
    951     String mTopAction = Intent.ACTION_MAIN;
    952     String mTopData;
    953     boolean mProcessesReady = false;
    954     boolean mSystemReady = false;
    955     boolean mBooting = false;
    956     boolean mCallFinishBooting = false;
    957     boolean mBootAnimationComplete = false;
    958     boolean mWaitingUpdate = false;
    959     boolean mDidUpdate = false;
    960     boolean mOnBattery = false;
    961     boolean mLaunchWarningShown = false;
    962 
    963     Context mContext;
    964 
    965     int mFactoryTest;
    966 
    967     boolean mCheckedForSetup;
    968 
    969     /**
    970      * The time at which we will allow normal application switches again,
    971      * after a call to {@link #stopAppSwitches()}.
    972      */
    973     long mAppSwitchesAllowedTime;
    974 
    975     /**
    976      * This is set to true after the first switch after mAppSwitchesAllowedTime
    977      * is set; any switches after that will clear the time.
    978      */
    979     boolean mDidAppSwitch;
    980 
    981     /**
    982      * Last time (in realtime) at which we checked for power usage.
    983      */
    984     long mLastPowerCheckRealtime;
    985 
    986     /**
    987      * Last time (in uptime) at which we checked for power usage.
    988      */
    989     long mLastPowerCheckUptime;
    990 
    991     /**
    992      * Set while we are wanting to sleep, to prevent any
    993      * activities from being started/resumed.
    994      */
    995     private boolean mSleeping = false;
    996 
    997     /**
    998      * Set while we are running a voice interaction.  This overrides
    999      * sleeping while it is active.
   1000      */
   1001     private boolean mRunningVoice = false;
   1002 
   1003     /**
   1004      * State of external calls telling us if the device is awake or asleep.
   1005      */
   1006     private int mWakefulness = PowerManagerInternal.WAKEFULNESS_AWAKE;
   1007 
   1008     static final int LOCK_SCREEN_HIDDEN = 0;
   1009     static final int LOCK_SCREEN_LEAVING = 1;
   1010     static final int LOCK_SCREEN_SHOWN = 2;
   1011     /**
   1012      * State of external call telling us if the lock screen is shown.
   1013      */
   1014     int mLockScreenShown = LOCK_SCREEN_HIDDEN;
   1015 
   1016     /**
   1017      * Set if we are shutting down the system, similar to sleeping.
   1018      */
   1019     boolean mShuttingDown = false;
   1020 
   1021     /**
   1022      * Current sequence id for oom_adj computation traversal.
   1023      */
   1024     int mAdjSeq = 0;
   1025 
   1026     /**
   1027      * Current sequence id for process LRU updating.
   1028      */
   1029     int mLruSeq = 0;
   1030 
   1031     /**
   1032      * Keep track of the non-cached/empty process we last found, to help
   1033      * determine how to distribute cached/empty processes next time.
   1034      */
   1035     int mNumNonCachedProcs = 0;
   1036 
   1037     /**
   1038      * Keep track of the number of cached hidden procs, to balance oom adj
   1039      * distribution between those and empty procs.
   1040      */
   1041     int mNumCachedHiddenProcs = 0;
   1042 
   1043     /**
   1044      * Keep track of the number of service processes we last found, to
   1045      * determine on the next iteration which should be B services.
   1046      */
   1047     int mNumServiceProcs = 0;
   1048     int mNewNumAServiceProcs = 0;
   1049     int mNewNumServiceProcs = 0;
   1050 
   1051     /**
   1052      * Allow the current computed overall memory level of the system to go down?
   1053      * This is set to false when we are killing processes for reasons other than
   1054      * memory management, so that the now smaller process list will not be taken as
   1055      * an indication that memory is tighter.
   1056      */
   1057     boolean mAllowLowerMemLevel = false;
   1058 
   1059     /**
   1060      * The last computed memory level, for holding when we are in a state that
   1061      * processes are going away for other reasons.
   1062      */
   1063     int mLastMemoryLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
   1064 
   1065     /**
   1066      * The last total number of process we have, to determine if changes actually look
   1067      * like a shrinking number of process due to lower RAM.
   1068      */
   1069     int mLastNumProcesses;
   1070 
   1071     /**
   1072      * The uptime of the last time we performed idle maintenance.
   1073      */
   1074     long mLastIdleTime = SystemClock.uptimeMillis();
   1075 
   1076     /**
   1077      * Total time spent with RAM that has been added in the past since the last idle time.
   1078      */
   1079     long mLowRamTimeSinceLastIdle = 0;
   1080 
   1081     /**
   1082      * If RAM is currently low, when that horrible situation started.
   1083      */
   1084     long mLowRamStartTime = 0;
   1085 
   1086     /**
   1087      * For reporting to battery stats the current top application.
   1088      */
   1089     private String mCurResumedPackage = null;
   1090     private int mCurResumedUid = -1;
   1091 
   1092     /**
   1093      * For reporting to battery stats the apps currently running foreground
   1094      * service.  The ProcessMap is package/uid tuples; each of these contain
   1095      * an array of the currently foreground processes.
   1096      */
   1097     final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages
   1098             = new ProcessMap<ArrayList<ProcessRecord>>();
   1099 
   1100     /**
   1101      * This is set if we had to do a delayed dexopt of an app before launching
   1102      * it, to increase the ANR timeouts in that case.
   1103      */
   1104     boolean mDidDexOpt;
   1105 
   1106     /**
   1107      * Set if the systemServer made a call to enterSafeMode.
   1108      */
   1109     boolean mSafeMode;
   1110 
   1111     /**
   1112      * If true, we are running under a test environment so will sample PSS from processes
   1113      * much more rapidly to try to collect better data when the tests are rapidly
   1114      * running through apps.
   1115      */
   1116     boolean mTestPssMode = false;
   1117 
   1118     String mDebugApp = null;
   1119     boolean mWaitForDebugger = false;
   1120     boolean mDebugTransient = false;
   1121     String mOrigDebugApp = null;
   1122     boolean mOrigWaitForDebugger = false;
   1123     boolean mAlwaysFinishActivities = false;
   1124     IActivityController mController = null;
   1125     String mProfileApp = null;
   1126     ProcessRecord mProfileProc = null;
   1127     String mProfileFile;
   1128     ParcelFileDescriptor mProfileFd;
   1129     int mSamplingInterval = 0;
   1130     boolean mAutoStopProfiler = false;
   1131     int mProfileType = 0;
   1132     String mOpenGlTraceApp = null;
   1133 
   1134     final long[] mTmpLong = new long[1];
   1135 
   1136     static class ProcessChangeItem {
   1137         static final int CHANGE_ACTIVITIES = 1<<0;
   1138         static final int CHANGE_PROCESS_STATE = 1<<1;
   1139         int changes;
   1140         int uid;
   1141         int pid;
   1142         int processState;
   1143         boolean foregroundActivities;
   1144     }
   1145 
   1146     final RemoteCallbackList<IProcessObserver> mProcessObservers
   1147             = new RemoteCallbackList<IProcessObserver>();
   1148     ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
   1149 
   1150     final ArrayList<ProcessChangeItem> mPendingProcessChanges
   1151             = new ArrayList<ProcessChangeItem>();
   1152     final ArrayList<ProcessChangeItem> mAvailProcessChanges
   1153             = new ArrayList<ProcessChangeItem>();
   1154 
   1155     /**
   1156      * Runtime CPU use collection thread.  This object's lock is used to
   1157      * perform synchronization with the thread (notifying it to run).
   1158      */
   1159     final Thread mProcessCpuThread;
   1160 
   1161     /**
   1162      * Used to collect per-process CPU use for ANRs, battery stats, etc.
   1163      * Must acquire this object's lock when accessing it.
   1164      * NOTE: this lock will be held while doing long operations (trawling
   1165      * through all processes in /proc), so it should never be acquired by
   1166      * any critical paths such as when holding the main activity manager lock.
   1167      */
   1168     final ProcessCpuTracker mProcessCpuTracker = new ProcessCpuTracker(
   1169             MONITOR_THREAD_CPU_USAGE);
   1170     final AtomicLong mLastCpuTime = new AtomicLong(0);
   1171     final AtomicBoolean mProcessCpuMutexFree = new AtomicBoolean(true);
   1172 
   1173     long mLastWriteTime = 0;
   1174 
   1175     /**
   1176      * Used to retain an update lock when the foreground activity is in
   1177      * immersive mode.
   1178      */
   1179     final UpdateLock mUpdateLock = new UpdateLock("immersive");
   1180 
   1181     /**
   1182      * Set to true after the system has finished booting.
   1183      */
   1184     boolean mBooted = false;
   1185 
   1186     int mProcessLimit = ProcessList.MAX_CACHED_APPS;
   1187     int mProcessLimitOverride = -1;
   1188 
   1189     WindowManagerService mWindowManager;
   1190 
   1191     final ActivityThread mSystemThread;
   1192 
   1193     // Holds the current foreground user's id
   1194     int mCurrentUserId = 0;
   1195     // Holds the target user's id during a user switch
   1196     int mTargetUserId = UserHandle.USER_NULL;
   1197     // If there are multiple profiles for the current user, their ids are here
   1198     // Currently only the primary user can have managed profiles
   1199     int[] mCurrentProfileIds = new int[] {UserHandle.USER_OWNER}; // Accessed by ActivityStack
   1200 
   1201     /**
   1202      * Mapping from each known user ID to the profile group ID it is associated with.
   1203      */
   1204     SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
   1205 
   1206     private UserManagerService mUserManager;
   1207 
   1208     private final class AppDeathRecipient implements IBinder.DeathRecipient {
   1209         final ProcessRecord mApp;
   1210         final int mPid;
   1211         final IApplicationThread mAppThread;
   1212 
   1213         AppDeathRecipient(ProcessRecord app, int pid,
   1214                 IApplicationThread thread) {
   1215             if (localLOGV) Slog.v(
   1216                 TAG, "New death recipient " + this
   1217                 + " for thread " + thread.asBinder());
   1218             mApp = app;
   1219             mPid = pid;
   1220             mAppThread = thread;
   1221         }
   1222 
   1223         @Override
   1224         public void binderDied() {
   1225             if (localLOGV) Slog.v(
   1226                 TAG, "Death received in " + this
   1227                 + " for thread " + mAppThread.asBinder());
   1228             synchronized(ActivityManagerService.this) {
   1229                 appDiedLocked(mApp, mPid, mAppThread);
   1230             }
   1231         }
   1232     }
   1233 
   1234     static final int SHOW_ERROR_MSG = 1;
   1235     static final int SHOW_NOT_RESPONDING_MSG = 2;
   1236     static final int SHOW_FACTORY_ERROR_MSG = 3;
   1237     static final int UPDATE_CONFIGURATION_MSG = 4;
   1238     static final int GC_BACKGROUND_PROCESSES_MSG = 5;
   1239     static final int WAIT_FOR_DEBUGGER_MSG = 6;
   1240     static final int SERVICE_TIMEOUT_MSG = 12;
   1241     static final int UPDATE_TIME_ZONE = 13;
   1242     static final int SHOW_UID_ERROR_MSG = 14;
   1243     static final int SHOW_FINGERPRINT_ERROR_MSG = 15;
   1244     static final int PROC_START_TIMEOUT_MSG = 20;
   1245     static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
   1246     static final int KILL_APPLICATION_MSG = 22;
   1247     static final int FINALIZE_PENDING_INTENT_MSG = 23;
   1248     static final int POST_HEAVY_NOTIFICATION_MSG = 24;
   1249     static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
   1250     static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
   1251     static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
   1252     static final int CLEAR_DNS_CACHE_MSG = 28;
   1253     static final int UPDATE_HTTP_PROXY_MSG = 29;
   1254     static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
   1255     static final int DISPATCH_PROCESSES_CHANGED = 31;
   1256     static final int DISPATCH_PROCESS_DIED = 32;
   1257     static final int REPORT_MEM_USAGE_MSG = 33;
   1258     static final int REPORT_USER_SWITCH_MSG = 34;
   1259     static final int CONTINUE_USER_SWITCH_MSG = 35;
   1260     static final int USER_SWITCH_TIMEOUT_MSG = 36;
   1261     static final int IMMERSIVE_MODE_LOCK_MSG = 37;
   1262     static final int PERSIST_URI_GRANTS_MSG = 38;
   1263     static final int REQUEST_ALL_PSS_MSG = 39;
   1264     static final int START_PROFILES_MSG = 40;
   1265     static final int UPDATE_TIME = 41;
   1266     static final int SYSTEM_USER_START_MSG = 42;
   1267     static final int SYSTEM_USER_CURRENT_MSG = 43;
   1268     static final int ENTER_ANIMATION_COMPLETE_MSG = 44;
   1269     static final int FINISH_BOOTING_MSG = 45;
   1270     static final int START_USER_SWITCH_MSG = 46;
   1271     static final int SEND_LOCALE_TO_MOUNT_DAEMON_MSG = 47;
   1272     static final int DISMISS_DIALOG_MSG = 48;
   1273     static final int NOTIFY_TASK_STACK_CHANGE_LISTENERS_MSG = 49;
   1274 
   1275     static final int FIRST_ACTIVITY_STACK_MSG = 100;
   1276     static final int FIRST_BROADCAST_QUEUE_MSG = 200;
   1277     static final int FIRST_COMPAT_MODE_MSG = 300;
   1278     static final int FIRST_SUPERVISOR_STACK_MSG = 100;
   1279 
   1280     CompatModeDialog mCompatModeDialog;
   1281     long mLastMemUsageReportTime = 0;
   1282 
   1283     /**
   1284      * Flag whether the current user is a "monkey", i.e. whether
   1285      * the UI is driven by a UI automation tool.
   1286      */
   1287     private boolean mUserIsMonkey;
   1288 
   1289     /** Flag whether the device has a Recents UI */
   1290     boolean mHasRecents;
   1291 
   1292     /** The dimensions of the thumbnails in the Recents UI. */
   1293     int mThumbnailWidth;
   1294     int mThumbnailHeight;
   1295 
   1296     final ServiceThread mHandlerThread;
   1297     final MainHandler mHandler;
   1298 
   1299     final class MainHandler extends Handler {
   1300         public MainHandler(Looper looper) {
   1301             super(looper, null, true);
   1302         }
   1303 
   1304         @Override
   1305         public void handleMessage(Message msg) {
   1306             switch (msg.what) {
   1307             case SHOW_ERROR_MSG: {
   1308                 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
   1309                 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
   1310                         Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
   1311                 synchronized (ActivityManagerService.this) {
   1312                     ProcessRecord proc = (ProcessRecord)data.get("app");
   1313                     AppErrorResult res = (AppErrorResult) data.get("result");
   1314                     if (proc != null && proc.crashDialog != null) {
   1315                         Slog.e(TAG, "App already has crash dialog: " + proc);
   1316                         if (res != null) {
   1317                             res.set(0);
   1318                         }
   1319                         return;
   1320                     }
   1321                     boolean isBackground = (UserHandle.getAppId(proc.uid)
   1322                             >= Process.FIRST_APPLICATION_UID
   1323                             && proc.pid != MY_PID);
   1324                     for (int userId : mCurrentProfileIds) {
   1325                         isBackground &= (proc.userId != userId);
   1326                     }
   1327                     if (isBackground && !showBackground) {
   1328                         Slog.w(TAG, "Skipping crash dialog of " + proc + ": background");
   1329                         if (res != null) {
   1330                             res.set(0);
   1331                         }
   1332                         return;
   1333                     }
   1334                     if (mShowDialogs && !mSleeping && !mShuttingDown) {
   1335                         Dialog d = new AppErrorDialog(mContext,
   1336                                 ActivityManagerService.this, res, proc);
   1337                         d.show();
   1338                         proc.crashDialog = d;
   1339                     } else {
   1340                         // The device is asleep, so just pretend that the user
   1341                         // saw a crash dialog and hit "force quit".
   1342                         if (res != null) {
   1343                             res.set(0);
   1344                         }
   1345                     }
   1346                 }
   1347 
   1348                 ensureBootCompleted();
   1349             } break;
   1350             case SHOW_NOT_RESPONDING_MSG: {
   1351                 synchronized (ActivityManagerService.this) {
   1352                     HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
   1353                     ProcessRecord proc = (ProcessRecord)data.get("app");
   1354                     if (proc != null && proc.anrDialog != null) {
   1355                         Slog.e(TAG, "App already has anr dialog: " + proc);
   1356                         return;
   1357                     }
   1358 
   1359                     Intent intent = new Intent("android.intent.action.ANR");
   1360                     if (!mProcessesReady) {
   1361                         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
   1362                                 | Intent.FLAG_RECEIVER_FOREGROUND);
   1363                     }
   1364                     broadcastIntentLocked(null, null, intent,
   1365                             null, null, 0, null, null, null, AppOpsManager.OP_NONE,
   1366                             false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
   1367 
   1368                     if (mShowDialogs) {
   1369                         Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
   1370                                 mContext, proc, (ActivityRecord)data.get("activity"),
   1371                                 msg.arg1 != 0);
   1372                         d.show();
   1373                         proc.anrDialog = d;
   1374                     } else {
   1375                         // Just kill the app if there is no dialog to be shown.
   1376                         killAppAtUsersRequest(proc, null);
   1377                     }
   1378                 }
   1379 
   1380                 ensureBootCompleted();
   1381             } break;
   1382             case SHOW_STRICT_MODE_VIOLATION_MSG: {
   1383                 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
   1384                 synchronized (ActivityManagerService.this) {
   1385                     ProcessRecord proc = (ProcessRecord) data.get("app");
   1386                     if (proc == null) {
   1387                         Slog.e(TAG, "App not found when showing strict mode dialog.");
   1388                         break;
   1389                     }
   1390                     if (proc.crashDialog != null) {
   1391                         Slog.e(TAG, "App already has strict mode dialog: " + proc);
   1392                         return;
   1393                     }
   1394                     AppErrorResult res = (AppErrorResult) data.get("result");
   1395                     if (mShowDialogs && !mSleeping && !mShuttingDown) {
   1396                         Dialog d = new StrictModeViolationDialog(mContext,
   1397                                 ActivityManagerService.this, res, proc);
   1398                         d.show();
   1399                         proc.crashDialog = d;
   1400                     } else {
   1401                         // The device is asleep, so just pretend that the user
   1402                         // saw a crash dialog and hit "force quit".
   1403                         res.set(0);
   1404                     }
   1405                 }
   1406                 ensureBootCompleted();
   1407             } break;
   1408             case SHOW_FACTORY_ERROR_MSG: {
   1409                 Dialog d = new FactoryErrorDialog(
   1410                     mContext, msg.getData().getCharSequence("msg"));
   1411                 d.show();
   1412                 ensureBootCompleted();
   1413             } break;
   1414             case UPDATE_CONFIGURATION_MSG: {
   1415                 final ContentResolver resolver = mContext.getContentResolver();
   1416                 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
   1417             } break;
   1418             case GC_BACKGROUND_PROCESSES_MSG: {
   1419                 synchronized (ActivityManagerService.this) {
   1420                     performAppGcsIfAppropriateLocked();
   1421                 }
   1422             } break;
   1423             case WAIT_FOR_DEBUGGER_MSG: {
   1424                 synchronized (ActivityManagerService.this) {
   1425                     ProcessRecord app = (ProcessRecord)msg.obj;
   1426                     if (msg.arg1 != 0) {
   1427                         if (!app.waitedForDebugger) {
   1428                             Dialog d = new AppWaitingForDebuggerDialog(
   1429                                     ActivityManagerService.this,
   1430                                     mContext, app);
   1431                             app.waitDialog = d;
   1432                             app.waitedForDebugger = true;
   1433                             d.show();
   1434                         }
   1435                     } else {
   1436                         if (app.waitDialog != null) {
   1437                             app.waitDialog.dismiss();
   1438                             app.waitDialog = null;
   1439                         }
   1440                     }
   1441                 }
   1442             } break;
   1443             case SERVICE_TIMEOUT_MSG: {
   1444                 if (mDidDexOpt) {
   1445                     mDidDexOpt = false;
   1446                     Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
   1447                     nmsg.obj = msg.obj;
   1448                     mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
   1449                     return;
   1450                 }
   1451                 mServices.serviceTimeout((ProcessRecord)msg.obj);
   1452             } break;
   1453             case UPDATE_TIME_ZONE: {
   1454                 synchronized (ActivityManagerService.this) {
   1455                     for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
   1456                         ProcessRecord r = mLruProcesses.get(i);
   1457                         if (r.thread != null) {
   1458                             try {
   1459                                 r.thread.updateTimeZone();
   1460                             } catch (RemoteException ex) {
   1461                                 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
   1462                             }
   1463                         }
   1464                     }
   1465                 }
   1466             } break;
   1467             case CLEAR_DNS_CACHE_MSG: {
   1468                 synchronized (ActivityManagerService.this) {
   1469                     for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
   1470                         ProcessRecord r = mLruProcesses.get(i);
   1471                         if (r.thread != null) {
   1472                             try {
   1473                                 r.thread.clearDnsCache();
   1474                             } catch (RemoteException ex) {
   1475                                 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
   1476                             }
   1477                         }
   1478                     }
   1479                 }
   1480             } break;
   1481             case UPDATE_HTTP_PROXY_MSG: {
   1482                 ProxyInfo proxy = (ProxyInfo)msg.obj;
   1483                 String host = "";
   1484                 String port = "";
   1485                 String exclList = "";
   1486                 Uri pacFileUrl = Uri.EMPTY;
   1487                 if (proxy != null) {
   1488                     host = proxy.getHost();
   1489                     port = Integer.toString(proxy.getPort());
   1490                     exclList = proxy.getExclusionListAsString();
   1491                     pacFileUrl = proxy.getPacFileUrl();
   1492                 }
   1493                 synchronized (ActivityManagerService.this) {
   1494                     for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
   1495                         ProcessRecord r = mLruProcesses.get(i);
   1496                         if (r.thread != null) {
   1497                             try {
   1498                                 r.thread.setHttpProxy(host, port, exclList, pacFileUrl);
   1499                             } catch (RemoteException ex) {
   1500                                 Slog.w(TAG, "Failed to update http proxy for: " +
   1501                                         r.info.processName);
   1502                             }
   1503                         }
   1504                     }
   1505                 }
   1506             } break;
   1507             case SHOW_UID_ERROR_MSG: {
   1508                 if (mShowDialogs) {
   1509                     AlertDialog d = new BaseErrorDialog(mContext);
   1510                     d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
   1511                     d.setCancelable(false);
   1512                     d.setTitle(mContext.getText(R.string.android_system_label));
   1513                     d.setMessage(mContext.getText(R.string.system_error_wipe_data));
   1514                     d.setButton(DialogInterface.BUTTON_POSITIVE, mContext.getText(R.string.ok),
   1515                             mHandler.obtainMessage(DISMISS_DIALOG_MSG, d));
   1516                     d.show();
   1517                 }
   1518             } break;
   1519             case SHOW_FINGERPRINT_ERROR_MSG: {
   1520                 if (mShowDialogs) {
   1521                     AlertDialog d = new BaseErrorDialog(mContext);
   1522                     d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
   1523                     d.setCancelable(false);
   1524                     d.setTitle(mContext.getText(R.string.android_system_label));
   1525                     d.setMessage(mContext.getText(R.string.system_error_manufacturer));
   1526                     d.setButton(DialogInterface.BUTTON_POSITIVE, mContext.getText(R.string.ok),
   1527                             mHandler.obtainMessage(DISMISS_DIALOG_MSG, d));
   1528                     d.show();
   1529                 }
   1530             } break;
   1531             case PROC_START_TIMEOUT_MSG: {
   1532                 if (mDidDexOpt) {
   1533                     mDidDexOpt = false;
   1534                     Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
   1535                     nmsg.obj = msg.obj;
   1536                     mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
   1537                     return;
   1538                 }
   1539                 ProcessRecord app = (ProcessRecord)msg.obj;
   1540                 synchronized (ActivityManagerService.this) {
   1541                     processStartTimedOutLocked(app);
   1542                 }
   1543             } break;
   1544             case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
   1545                 synchronized (ActivityManagerService.this) {
   1546                     mStackSupervisor.doPendingActivityLaunchesLocked(true);
   1547                 }
   1548             } break;
   1549             case KILL_APPLICATION_MSG: {
   1550                 synchronized (ActivityManagerService.this) {
   1551                     int appid = msg.arg1;
   1552                     boolean restart = (msg.arg2 == 1);
   1553                     Bundle bundle = (Bundle)msg.obj;
   1554                     String pkg = bundle.getString("pkg");
   1555                     String reason = bundle.getString("reason");
   1556                     forceStopPackageLocked(pkg, appid, restart, false, true, false,
   1557                             false, UserHandle.USER_ALL, reason);
   1558                 }
   1559             } break;
   1560             case FINALIZE_PENDING_INTENT_MSG: {
   1561                 ((PendingIntentRecord)msg.obj).completeFinalize();
   1562             } break;
   1563             case POST_HEAVY_NOTIFICATION_MSG: {
   1564                 INotificationManager inm = NotificationManager.getService();
   1565                 if (inm == null) {
   1566                     return;
   1567                 }
   1568 
   1569                 ActivityRecord root = (ActivityRecord)msg.obj;
   1570                 ProcessRecord process = root.app;
   1571                 if (process == null) {
   1572                     return;
   1573                 }
   1574 
   1575                 try {
   1576                     Context context = mContext.createPackageContext(process.info.packageName, 0);
   1577                     String text = mContext.getString(R.string.heavy_weight_notification,
   1578                             context.getApplicationInfo().loadLabel(context.getPackageManager()));
   1579                     Notification notification = new Notification();
   1580                     notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
   1581                     notification.when = 0;
   1582                     notification.flags = Notification.FLAG_ONGOING_EVENT;
   1583                     notification.tickerText = text;
   1584                     notification.defaults = 0; // please be quiet
   1585                     notification.sound = null;
   1586                     notification.vibrate = null;
   1587                     notification.color = mContext.getResources().getColor(
   1588                             com.android.internal.R.color.system_notification_accent_color);
   1589                     notification.setLatestEventInfo(context, text,
   1590                             mContext.getText(R.string.heavy_weight_notification_detail),
   1591                             PendingIntent.getActivityAsUser(mContext, 0, root.intent,
   1592                                     PendingIntent.FLAG_CANCEL_CURRENT, null,
   1593                                     new UserHandle(root.userId)));
   1594 
   1595                     try {
   1596                         int[] outId = new int[1];
   1597                         inm.enqueueNotificationWithTag("android", "android", null,
   1598                                 R.string.heavy_weight_notification,
   1599                                 notification, outId, root.userId);
   1600                     } catch (RuntimeException e) {
   1601                         Slog.w(ActivityManagerService.TAG,
   1602                                 "Error showing notification for heavy-weight app", e);
   1603                     } catch (RemoteException e) {
   1604                     }
   1605                 } catch (NameNotFoundException e) {
   1606                     Slog.w(TAG, "Unable to create context for heavy notification", e);
   1607                 }
   1608             } break;
   1609             case CANCEL_HEAVY_NOTIFICATION_MSG: {
   1610                 INotificationManager inm = NotificationManager.getService();
   1611                 if (inm == null) {
   1612                     return;
   1613                 }
   1614                 try {
   1615                     inm.cancelNotificationWithTag("android", null,
   1616                             R.string.heavy_weight_notification,  msg.arg1);
   1617                 } catch (RuntimeException e) {
   1618                     Slog.w(ActivityManagerService.TAG,
   1619                             "Error canceling notification for service", e);
   1620                 } catch (RemoteException e) {
   1621                 }
   1622             } break;
   1623             case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
   1624                 synchronized (ActivityManagerService.this) {
   1625                     checkExcessivePowerUsageLocked(true);
   1626                     removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
   1627                     Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
   1628                     sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
   1629                 }
   1630             } break;
   1631             case SHOW_COMPAT_MODE_DIALOG_MSG: {
   1632                 synchronized (ActivityManagerService.this) {
   1633                     ActivityRecord ar = (ActivityRecord)msg.obj;
   1634                     if (mCompatModeDialog != null) {
   1635                         if (mCompatModeDialog.mAppInfo.packageName.equals(
   1636                                 ar.info.applicationInfo.packageName)) {
   1637                             return;
   1638                         }
   1639                         mCompatModeDialog.dismiss();
   1640                         mCompatModeDialog = null;
   1641                     }
   1642                     if (ar != null && false) {
   1643                         if (mCompatModePackages.getPackageAskCompatModeLocked(
   1644                                 ar.packageName)) {
   1645                             int mode = mCompatModePackages.computeCompatModeLocked(
   1646                                     ar.info.applicationInfo);
   1647                             if (mode == ActivityManager.COMPAT_MODE_DISABLED
   1648                                     || mode == ActivityManager.COMPAT_MODE_ENABLED) {
   1649                                 mCompatModeDialog = new CompatModeDialog(
   1650                                         ActivityManagerService.this, mContext,
   1651                                         ar.info.applicationInfo);
   1652                                 mCompatModeDialog.show();
   1653                             }
   1654                         }
   1655                     }
   1656                 }
   1657                 break;
   1658             }
   1659             case DISPATCH_PROCESSES_CHANGED: {
   1660                 dispatchProcessesChanged();
   1661                 break;
   1662             }
   1663             case DISPATCH_PROCESS_DIED: {
   1664                 final int pid = msg.arg1;
   1665                 final int uid = msg.arg2;
   1666                 dispatchProcessDied(pid, uid);
   1667                 break;
   1668             }
   1669             case REPORT_MEM_USAGE_MSG: {
   1670                 final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>)msg.obj;
   1671                 Thread thread = new Thread() {
   1672                     @Override public void run() {
   1673                         reportMemUsage(memInfos);
   1674                     }
   1675                 };
   1676                 thread.start();
   1677                 break;
   1678             }
   1679             case START_USER_SWITCH_MSG: {
   1680                 showUserSwitchDialog(msg.arg1, (String) msg.obj);
   1681                 break;
   1682             }
   1683             case REPORT_USER_SWITCH_MSG: {
   1684                 dispatchUserSwitch((UserStartedState) msg.obj, msg.arg1, msg.arg2);
   1685                 break;
   1686             }
   1687             case CONTINUE_USER_SWITCH_MSG: {
   1688                 continueUserSwitch((UserStartedState) msg.obj, msg.arg1, msg.arg2);
   1689                 break;
   1690             }
   1691             case USER_SWITCH_TIMEOUT_MSG: {
   1692                 timeoutUserSwitch((UserStartedState) msg.obj, msg.arg1, msg.arg2);
   1693                 break;
   1694             }
   1695             case IMMERSIVE_MODE_LOCK_MSG: {
   1696                 final boolean nextState = (msg.arg1 != 0);
   1697                 if (mUpdateLock.isHeld() != nextState) {
   1698                     if (DEBUG_IMMERSIVE) {
   1699                         final ActivityRecord r = (ActivityRecord) msg.obj;
   1700                         Slog.d(TAG, "Applying new update lock state '" + nextState + "' for " + r);
   1701                     }
   1702                     if (nextState) {
   1703                         mUpdateLock.acquire();
   1704                     } else {
   1705                         mUpdateLock.release();
   1706                     }
   1707                 }
   1708                 break;
   1709             }
   1710             case PERSIST_URI_GRANTS_MSG: {
   1711                 writeGrantedUriPermissions();
   1712                 break;
   1713             }
   1714             case REQUEST_ALL_PSS_MSG: {
   1715                 synchronized (ActivityManagerService.this) {
   1716                     requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false);
   1717                 }
   1718                 break;
   1719             }
   1720             case START_PROFILES_MSG: {
   1721                 synchronized (ActivityManagerService.this) {
   1722                     startProfilesLocked();
   1723                 }
   1724                 break;
   1725             }
   1726             case UPDATE_TIME: {
   1727                 synchronized (ActivityManagerService.this) {
   1728                     for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
   1729                         ProcessRecord r = mLruProcesses.get(i);
   1730                         if (r.thread != null) {
   1731                             try {
   1732                                 r.thread.updateTimePrefs(msg.arg1 == 0 ? false : true);
   1733                             } catch (RemoteException ex) {
   1734                                 Slog.w(TAG, "Failed to update preferences for: " + r.info.processName);
   1735                             }
   1736                         }
   1737                     }
   1738                 }
   1739                 break;
   1740             }
   1741             case SYSTEM_USER_START_MSG: {
   1742                 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
   1743                         Integer.toString(msg.arg1), msg.arg1);
   1744                 mSystemServiceManager.startUser(msg.arg1);
   1745                 break;
   1746             }
   1747             case SYSTEM_USER_CURRENT_MSG: {
   1748                 mBatteryStatsService.noteEvent(
   1749                         BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_FINISH,
   1750                         Integer.toString(msg.arg2), msg.arg2);
   1751                 mBatteryStatsService.noteEvent(
   1752                         BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
   1753                         Integer.toString(msg.arg1), msg.arg1);
   1754                 mSystemServiceManager.switchUser(msg.arg1);
   1755                 break;
   1756             }
   1757             case ENTER_ANIMATION_COMPLETE_MSG: {
   1758                 synchronized (ActivityManagerService.this) {
   1759                     ActivityRecord r = ActivityRecord.forToken((IBinder) msg.obj);
   1760                     if (r != null && r.app != null && r.app.thread != null) {
   1761                         try {
   1762                             r.app.thread.scheduleEnterAnimationComplete(r.appToken);
   1763                         } catch (RemoteException e) {
   1764                         }
   1765                     }
   1766                 }
   1767                 break;
   1768             }
   1769             case FINISH_BOOTING_MSG: {
   1770                 if (msg.arg1 != 0) {
   1771                     finishBooting();
   1772                 }
   1773                 if (msg.arg2 != 0) {
   1774                     enableScreenAfterBoot();
   1775                 }
   1776                 break;
   1777             }
   1778             case SEND_LOCALE_TO_MOUNT_DAEMON_MSG: {
   1779                 try {
   1780                     Locale l = (Locale) msg.obj;
   1781                     IBinder service = ServiceManager.getService("mount");
   1782                     IMountService mountService = IMountService.Stub.asInterface(service);
   1783                     Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
   1784                     mountService.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
   1785                 } catch (RemoteException e) {
   1786                     Log.e(TAG, "Error storing locale for decryption UI", e);
   1787                 }
   1788                 break;
   1789             }
   1790             case DISMISS_DIALOG_MSG: {
   1791                 final Dialog d = (Dialog) msg.obj;
   1792                 d.dismiss();
   1793                 break;
   1794             }
   1795             case NOTIFY_TASK_STACK_CHANGE_LISTENERS_MSG: {
   1796                 synchronized (ActivityManagerService.this) {
   1797                     int i = mTaskStackListeners.beginBroadcast();
   1798                     while (i > 0) {
   1799                         i--;
   1800                         try {
   1801                             // Make a one-way callback to the listener
   1802                             mTaskStackListeners.getBroadcastItem(i).onTaskStackChanged();
   1803                         } catch (RemoteException e){
   1804                             // Handled by the RemoteCallbackList
   1805                         }
   1806                     }
   1807                     mTaskStackListeners.finishBroadcast();
   1808                 }
   1809                 break;
   1810             }
   1811             }
   1812         }
   1813     };
   1814 
   1815     static final int COLLECT_PSS_BG_MSG = 1;
   1816 
   1817     final Handler mBgHandler = new Handler(BackgroundThread.getHandler().getLooper()) {
   1818         @Override
   1819         public void handleMessage(Message msg) {
   1820             switch (msg.what) {
   1821             case COLLECT_PSS_BG_MSG: {
   1822                 long start = SystemClock.uptimeMillis();
   1823                 MemInfoReader memInfo = null;
   1824                 synchronized (ActivityManagerService.this) {
   1825                     if (mFullPssPending) {
   1826                         mFullPssPending = false;
   1827                         memInfo = new MemInfoReader();
   1828                     }
   1829                 }
   1830                 if (memInfo != null) {
   1831                     updateCpuStatsNow();
   1832                     long nativeTotalPss = 0;
   1833                     synchronized (mProcessCpuTracker) {
   1834                         final int N = mProcessCpuTracker.countStats();
   1835                         for (int j=0; j<N; j++) {
   1836                             ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(j);
   1837                             if (st.vsize <= 0 || st.uid >= Process.FIRST_APPLICATION_UID) {
   1838                                 // This is definitely an application process; skip it.
   1839                                 continue;
   1840                             }
   1841                             synchronized (mPidsSelfLocked) {
   1842                                 if (mPidsSelfLocked.indexOfKey(st.pid) >= 0) {
   1843                                     // This is one of our own processes; skip it.
   1844                                     continue;
   1845                                 }
   1846                             }
   1847                             nativeTotalPss += Debug.getPss(st.pid, null, null);
   1848                         }
   1849                     }
   1850                     memInfo.readMemInfo();
   1851                     synchronized (ActivityManagerService.this) {
   1852                         if (DEBUG_PSS) Slog.d(TAG, "Collected native and kernel memory in "
   1853                                 + (SystemClock.uptimeMillis()-start) + "ms");
   1854                         mProcessStats.addSysMemUsageLocked(memInfo.getCachedSizeKb(),
   1855                                 memInfo.getFreeSizeKb(), memInfo.getZramTotalSizeKb(),
   1856                                 memInfo.getKernelUsedSizeKb(), nativeTotalPss);
   1857                     }
   1858                 }
   1859 
   1860                 int num = 0;
   1861                 long[] tmp = new long[1];
   1862                 do {
   1863                     ProcessRecord proc;
   1864                     int procState;
   1865                     int pid;
   1866                     long lastPssTime;
   1867                     synchronized (ActivityManagerService.this) {
   1868                         if (mPendingPssProcesses.size() <= 0) {
   1869                             if (mTestPssMode || DEBUG_PSS) Slog.d(TAG, "Collected PSS of " + num
   1870                                     + " processes in " + (SystemClock.uptimeMillis()-start) + "ms");
   1871                             mPendingPssProcesses.clear();
   1872                             return;
   1873                         }
   1874                         proc = mPendingPssProcesses.remove(0);
   1875                         procState = proc.pssProcState;
   1876                         lastPssTime = proc.lastPssTime;
   1877                         if (proc.thread != null && procState == proc.setProcState
   1878                                 && (lastPssTime+ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE)
   1879                                         < SystemClock.uptimeMillis()) {
   1880                             pid = proc.pid;
   1881                         } else {
   1882                             proc = null;
   1883                             pid = 0;
   1884                         }
   1885                     }
   1886                     if (proc != null) {
   1887                         long pss = Debug.getPss(pid, tmp, null);
   1888                         synchronized (ActivityManagerService.this) {
   1889                             if (pss != 0 && proc.thread != null && proc.setProcState == procState
   1890                                     && proc.pid == pid && proc.lastPssTime == lastPssTime) {
   1891                                 num++;
   1892                                 recordPssSample(proc, procState, pss, tmp[0],
   1893                                         SystemClock.uptimeMillis());
   1894                             }
   1895                         }
   1896                     }
   1897                 } while (true);
   1898             }
   1899             }
   1900         }
   1901     };
   1902 
   1903     public void setSystemProcess() {
   1904         try {
   1905             ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
   1906             ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
   1907             ServiceManager.addService("meminfo", new MemBinder(this));
   1908             ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
   1909             ServiceManager.addService("dbinfo", new DbBinder(this));
   1910             if (MONITOR_CPU_USAGE) {
   1911                 ServiceManager.addService("cpuinfo", new CpuBinder(this));
   1912             }
   1913             ServiceManager.addService("permission", new PermissionController(this));
   1914 
   1915             ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
   1916                     "android", STOCK_PM_FLAGS);
   1917             mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
   1918 
   1919             synchronized (this) {
   1920                 ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
   1921                 app.persistent = true;
   1922                 app.pid = MY_PID;
   1923                 app.maxAdj = ProcessList.SYSTEM_ADJ;
   1924                 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
   1925                 mProcessNames.put(app.processName, app.uid, app);
   1926                 synchronized (mPidsSelfLocked) {
   1927                     mPidsSelfLocked.put(app.pid, app);
   1928                 }
   1929                 updateLruProcessLocked(app, false, null);
   1930                 updateOomAdjLocked();
   1931             }
   1932         } catch (PackageManager.NameNotFoundException e) {
   1933             throw new RuntimeException(
   1934                     "Unable to find android system package", e);
   1935         }
   1936     }
   1937 
   1938     public void setWindowManager(WindowManagerService wm) {
   1939         mWindowManager = wm;
   1940         mStackSupervisor.setWindowManager(wm);
   1941     }
   1942 
   1943     public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
   1944         mUsageStatsService = usageStatsManager;
   1945     }
   1946 
   1947     public void startObservingNativeCrashes() {
   1948         final NativeCrashListener ncl = new NativeCrashListener(this);
   1949         ncl.start();
   1950     }
   1951 
   1952     public IAppOpsService getAppOpsService() {
   1953         return mAppOpsService;
   1954     }
   1955 
   1956     static class MemBinder extends Binder {
   1957         ActivityManagerService mActivityManagerService;
   1958         MemBinder(ActivityManagerService activityManagerService) {
   1959             mActivityManagerService = activityManagerService;
   1960         }
   1961 
   1962         @Override
   1963         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   1964             if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
   1965                     != PackageManager.PERMISSION_GRANTED) {
   1966                 pw.println("Permission Denial: can't dump meminfo from from pid="
   1967                         + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
   1968                         + " without permission " + android.Manifest.permission.DUMP);
   1969                 return;
   1970             }
   1971 
   1972             mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, "  ", args, false, null);
   1973         }
   1974     }
   1975 
   1976     static class GraphicsBinder extends Binder {
   1977         ActivityManagerService mActivityManagerService;
   1978         GraphicsBinder(ActivityManagerService activityManagerService) {
   1979             mActivityManagerService = activityManagerService;
   1980         }
   1981 
   1982         @Override
   1983         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   1984             if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
   1985                     != PackageManager.PERMISSION_GRANTED) {
   1986                 pw.println("Permission Denial: can't dump gfxinfo from from pid="
   1987                         + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
   1988                         + " without permission " + android.Manifest.permission.DUMP);
   1989                 return;
   1990             }
   1991 
   1992             mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
   1993         }
   1994     }
   1995 
   1996     static class DbBinder extends Binder {
   1997         ActivityManagerService mActivityManagerService;
   1998         DbBinder(ActivityManagerService activityManagerService) {
   1999             mActivityManagerService = activityManagerService;
   2000         }
   2001 
   2002         @Override
   2003         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   2004             if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
   2005                     != PackageManager.PERMISSION_GRANTED) {
   2006                 pw.println("Permission Denial: can't dump dbinfo from from pid="
   2007                         + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
   2008                         + " without permission " + android.Manifest.permission.DUMP);
   2009                 return;
   2010             }
   2011 
   2012             mActivityManagerService.dumpDbInfo(fd, pw, args);
   2013         }
   2014     }
   2015 
   2016     static class CpuBinder extends Binder {
   2017         ActivityManagerService mActivityManagerService;
   2018         CpuBinder(ActivityManagerService activityManagerService) {
   2019             mActivityManagerService = activityManagerService;
   2020         }
   2021 
   2022         @Override
   2023         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   2024             if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
   2025                     != PackageManager.PERMISSION_GRANTED) {
   2026                 pw.println("Permission Denial: can't dump cpuinfo from from pid="
   2027                         + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
   2028                         + " without permission " + android.Manifest.permission.DUMP);
   2029                 return;
   2030             }
   2031 
   2032             synchronized (mActivityManagerService.mProcessCpuTracker) {
   2033                 pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentLoad());
   2034                 pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentState(
   2035                         SystemClock.uptimeMillis()));
   2036             }
   2037         }
   2038     }
   2039 
   2040     public static final class Lifecycle extends SystemService {
   2041         private final ActivityManagerService mService;
   2042 
   2043         public Lifecycle(Context context) {
   2044             super(context);
   2045             mService = new ActivityManagerService(context);
   2046         }
   2047 
   2048         @Override
   2049         public void onStart() {
   2050             mService.start();
   2051         }
   2052 
   2053         public ActivityManagerService getService() {
   2054             return mService;
   2055         }
   2056     }
   2057 
   2058     // Note: This method is invoked on the main thread but may need to attach various
   2059     // handlers to other threads.  So take care to be explicit about the looper.
   2060     public ActivityManagerService(Context systemContext) {
   2061         mContext = systemContext;
   2062         mFactoryTest = FactoryTest.getMode();
   2063         mSystemThread = ActivityThread.currentActivityThread();
   2064 
   2065         Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
   2066 
   2067         mHandlerThread = new ServiceThread(TAG,
   2068                 android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
   2069         mHandlerThread.start();
   2070         mHandler = new MainHandler(mHandlerThread.getLooper());
   2071 
   2072         mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
   2073                 "foreground", BROADCAST_FG_TIMEOUT, false);
   2074         mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
   2075                 "background", BROADCAST_BG_TIMEOUT, true);
   2076         mBroadcastQueues[0] = mFgBroadcastQueue;
   2077         mBroadcastQueues[1] = mBgBroadcastQueue;
   2078 
   2079         mServices = new ActiveServices(this);
   2080         mProviderMap = new ProviderMap(this);
   2081 
   2082         // TODO: Move creation of battery stats service outside of activity manager service.
   2083         File dataDir = Environment.getDataDirectory();
   2084         File systemDir = new File(dataDir, "system");
   2085         systemDir.mkdirs();
   2086         mBatteryStatsService = new BatteryStatsService(systemDir, mHandler);
   2087         mBatteryStatsService.getActiveStatistics().readLocked();
   2088         mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
   2089         mOnBattery = DEBUG_POWER ? true
   2090                 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
   2091         mBatteryStatsService.getActiveStatistics().setCallback(this);
   2092 
   2093         mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
   2094 
   2095         mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml"), mHandler);
   2096 
   2097         mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"));
   2098 
   2099         // User 0 is the first and only user that runs at boot.
   2100         mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
   2101         mUserLru.add(Integer.valueOf(0));
   2102         updateStartedUserArrayLocked();
   2103 
   2104         GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
   2105             ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
   2106 
   2107         mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
   2108 
   2109         mConfiguration.setToDefaults();
   2110         mConfiguration.locale = Locale.getDefault();
   2111 
   2112         mConfigurationSeq = mConfiguration.seq = 1;
   2113         mProcessCpuTracker.init();
   2114 
   2115         mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
   2116         mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
   2117         mStackSupervisor = new ActivityStackSupervisor(this);
   2118         mTaskPersister = new TaskPersister(systemDir, mStackSupervisor);
   2119 
   2120         mProcessCpuThread = new Thread("CpuTracker") {
   2121             @Override
   2122             public void run() {
   2123                 while (true) {
   2124                     try {
   2125                         try {
   2126                             synchronized(this) {
   2127                                 final long now = SystemClock.uptimeMillis();
   2128                                 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
   2129                                 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
   2130                                 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
   2131                                 //        + ", write delay=" + nextWriteDelay);
   2132                                 if (nextWriteDelay < nextCpuDelay) {
   2133                                     nextCpuDelay = nextWriteDelay;
   2134                                 }
   2135                                 if (nextCpuDelay > 0) {
   2136                                     mProcessCpuMutexFree.set(true);
   2137                                     this.wait(nextCpuDelay);
   2138                                 }
   2139                             }
   2140                         } catch (InterruptedException e) {
   2141                         }
   2142                         updateCpuStatsNow();
   2143                     } catch (Exception e) {
   2144                         Slog.e(TAG, "Unexpected exception collecting process stats", e);
   2145                     }
   2146                 }
   2147             }
   2148         };
   2149 
   2150         Watchdog.getInstance().addMonitor(this);
   2151         Watchdog.getInstance().addThread(mHandler);
   2152     }
   2153 
   2154     public void setSystemServiceManager(SystemServiceManager mgr) {
   2155         mSystemServiceManager = mgr;
   2156     }
   2157 
   2158     public void setInstaller(Installer installer) {
   2159         mInstaller = installer;
   2160     }
   2161 
   2162     private void start() {
   2163         Process.removeAllProcessGroups();
   2164         mProcessCpuThread.start();
   2165 
   2166         mBatteryStatsService.publish(mContext);
   2167         mAppOpsService.publish(mContext);
   2168         Slog.d("AppOps", "AppOpsService published");
   2169         LocalServices.addService(ActivityManagerInternal.class, new LocalService());
   2170     }
   2171 
   2172     public void initPowerManagement() {
   2173         mStackSupervisor.initPowerManagement();
   2174         mBatteryStatsService.initPowerManagement();
   2175     }
   2176 
   2177     @Override
   2178     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
   2179             throws RemoteException {
   2180         if (code == SYSPROPS_TRANSACTION) {
   2181             // We need to tell all apps about the system property change.
   2182             ArrayList<IBinder> procs = new ArrayList<IBinder>();
   2183             synchronized(this) {
   2184                 final int NP = mProcessNames.getMap().size();
   2185                 for (int ip=0; ip<NP; ip++) {
   2186                     SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
   2187                     final int NA = apps.size();
   2188                     for (int ia=0; ia<NA; ia++) {
   2189                         ProcessRecord app = apps.valueAt(ia);
   2190                         if (app.thread != null) {
   2191                             procs.add(app.thread.asBinder());
   2192                         }
   2193                     }
   2194                 }
   2195             }
   2196 
   2197             int N = procs.size();
   2198             for (int i=0; i<N; i++) {
   2199                 Parcel data2 = Parcel.obtain();
   2200                 try {
   2201                     procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
   2202                 } catch (RemoteException e) {
   2203                 }
   2204                 data2.recycle();
   2205             }
   2206         }
   2207         try {
   2208             return super.onTransact(code, data, reply, flags);
   2209         } catch (RuntimeException e) {
   2210             // The activity manager only throws security exceptions, so let's
   2211             // log all others.
   2212             if (!(e instanceof SecurityException)) {
   2213                 Slog.wtf(TAG, "Activity Manager Crash", e);
   2214             }
   2215             throw e;
   2216         }
   2217     }
   2218 
   2219     void updateCpuStats() {
   2220         final long now = SystemClock.uptimeMillis();
   2221         if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
   2222             return;
   2223         }
   2224         if (mProcessCpuMutexFree.compareAndSet(true, false)) {
   2225             synchronized (mProcessCpuThread) {
   2226                 mProcessCpuThread.notify();
   2227             }
   2228         }
   2229     }
   2230 
   2231     void updateCpuStatsNow() {
   2232         synchronized (mProcessCpuTracker) {
   2233             mProcessCpuMutexFree.set(false);
   2234             final long now = SystemClock.uptimeMillis();
   2235             boolean haveNewCpuStats = false;
   2236 
   2237             if (MONITOR_CPU_USAGE &&
   2238                     mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
   2239                 mLastCpuTime.set(now);
   2240                 haveNewCpuStats = true;
   2241                 mProcessCpuTracker.update();
   2242                 //Slog.i(TAG, mProcessCpu.printCurrentState());
   2243                 //Slog.i(TAG, "Total CPU usage: "
   2244                 //        + mProcessCpu.getTotalCpuPercent() + "%");
   2245 
   2246                 // Slog the cpu usage if the property is set.
   2247                 if ("true".equals(SystemProperties.get("events.cpu"))) {
   2248                     int user = mProcessCpuTracker.getLastUserTime();
   2249                     int system = mProcessCpuTracker.getLastSystemTime();
   2250                     int iowait = mProcessCpuTracker.getLastIoWaitTime();
   2251                     int irq = mProcessCpuTracker.getLastIrqTime();
   2252                     int softIrq = mProcessCpuTracker.getLastSoftIrqTime();
   2253                     int idle = mProcessCpuTracker.getLastIdleTime();
   2254 
   2255                     int total = user + system + iowait + irq + softIrq + idle;
   2256                     if (total == 0) total = 1;
   2257 
   2258                     EventLog.writeEvent(EventLogTags.CPU,
   2259                             ((user+system+iowait+irq+softIrq) * 100) / total,
   2260                             (user * 100) / total,
   2261                             (system * 100) / total,
   2262                             (iowait * 100) / total,
   2263                             (irq * 100) / total,
   2264                             (softIrq * 100) / total);
   2265                 }
   2266             }
   2267 
   2268             long[] cpuSpeedTimes = mProcessCpuTracker.getLastCpuSpeedTimes();
   2269             final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
   2270             synchronized(bstats) {
   2271                 synchronized(mPidsSelfLocked) {
   2272                     if (haveNewCpuStats) {
   2273                         if (mOnBattery) {
   2274                             int perc = bstats.startAddingCpuLocked();
   2275                             int totalUTime = 0;
   2276                             int totalSTime = 0;
   2277                             final int N = mProcessCpuTracker.countStats();
   2278                             for (int i=0; i<N; i++) {
   2279                                 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
   2280                                 if (!st.working) {
   2281                                     continue;
   2282                                 }
   2283                                 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
   2284                                 int otherUTime = (st.rel_utime*perc)/100;
   2285                                 int otherSTime = (st.rel_stime*perc)/100;
   2286                                 totalUTime += otherUTime;
   2287                                 totalSTime += otherSTime;
   2288                                 if (pr != null) {
   2289                                     BatteryStatsImpl.Uid.Proc ps = pr.curProcBatteryStats;
   2290                                     if (ps == null || !ps.isActive()) {
   2291                                         pr.curProcBatteryStats = ps = bstats.getProcessStatsLocked(
   2292                                                 pr.info.uid, pr.processName);
   2293                                     }
   2294                                     ps.addCpuTimeLocked(st.rel_utime-otherUTime,
   2295                                             st.rel_stime-otherSTime);
   2296                                     ps.addSpeedStepTimes(cpuSpeedTimes);
   2297                                     pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
   2298                                 } else {
   2299                                     BatteryStatsImpl.Uid.Proc ps = st.batteryStats;
   2300                                     if (ps == null || !ps.isActive()) {
   2301                                         st.batteryStats = ps = bstats.getProcessStatsLocked(
   2302                                                 bstats.mapUid(st.uid), st.name);
   2303                                     }
   2304                                     ps.addCpuTimeLocked(st.rel_utime-otherUTime,
   2305                                             st.rel_stime-otherSTime);
   2306                                     ps.addSpeedStepTimes(cpuSpeedTimes);
   2307                                 }
   2308                             }
   2309                             bstats.finishAddingCpuLocked(perc, totalUTime,
   2310                                     totalSTime, cpuSpeedTimes);
   2311                         }
   2312                     }
   2313                 }
   2314 
   2315                 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
   2316                     mLastWriteTime = now;
   2317                     mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
   2318                 }
   2319             }
   2320         }
   2321     }
   2322 
   2323     @Override
   2324     public void batteryNeedsCpuUpdate() {
   2325         updateCpuStatsNow();
   2326     }
   2327 
   2328     @Override
   2329     public void batteryPowerChanged(boolean onBattery) {
   2330         // When plugging in, update the CPU stats first before changing
   2331         // the plug state.
   2332         updateCpuStatsNow();
   2333         synchronized (this) {
   2334             synchronized(mPidsSelfLocked) {
   2335                 mOnBattery = DEBUG_POWER ? true : onBattery;
   2336             }
   2337         }
   2338     }
   2339 
   2340     /**
   2341      * Initialize the application bind args. These are passed to each
   2342      * process when the bindApplication() IPC is sent to the process. They're
   2343      * lazily setup to make sure the services are running when they're asked for.
   2344      */
   2345     private HashMap<String, IBinder> getCommonServicesLocked(boolean isolated) {
   2346         if (mAppBindArgs == null) {
   2347             mAppBindArgs = new HashMap<>();
   2348 
   2349             // Isolated processes won't get this optimization, so that we don't
   2350             // violate the rules about which services they have access to.
   2351             if (!isolated) {
   2352                 // Setup the application init args
   2353                 mAppBindArgs.put("package", ServiceManager.getService("package"));
   2354                 mAppBindArgs.put("window", ServiceManager.getService("window"));
   2355                 mAppBindArgs.put(Context.ALARM_SERVICE,
   2356                         ServiceManager.getService(Context.ALARM_SERVICE));
   2357             }
   2358         }
   2359         return mAppBindArgs;
   2360     }
   2361 
   2362     final void setFocusedActivityLocked(ActivityRecord r, String reason) {
   2363         if (mFocusedActivity != r) {
   2364             if (DEBUG_FOCUS) Slog.d(TAG, "setFocusedActivityLocked: r=" + r);
   2365             mFocusedActivity = r;
   2366             if (r.task != null && r.task.voiceInteractor != null) {
   2367                 startRunningVoiceLocked();
   2368             } else {
   2369                 finishRunningVoiceLocked();
   2370             }
   2371             mStackSupervisor.setFocusedStack(r, reason + " setFocusedActivity");
   2372             if (r != null) {
   2373                 mWindowManager.setFocusedApp(r.appToken, true);
   2374             }
   2375             applyUpdateLockStateLocked(r);
   2376         }
   2377         EventLog.writeEvent(EventLogTags.AM_FOCUSED_ACTIVITY, mCurrentUserId,
   2378                 mFocusedActivity == null ? "NULL" : mFocusedActivity.shortComponentName);
   2379     }
   2380 
   2381     final void clearFocusedActivity(ActivityRecord r) {
   2382         if (mFocusedActivity == r) {
   2383             mFocusedActivity = null;
   2384         }
   2385     }
   2386 
   2387     @Override
   2388     public void setFocusedStack(int stackId) {
   2389         if (DEBUG_FOCUS) Slog.d(TAG, "setFocusedStack: stackId=" + stackId);
   2390         synchronized (ActivityManagerService.this) {
   2391             ActivityStack stack = mStackSupervisor.getStack(stackId);
   2392             if (stack != null) {
   2393                 ActivityRecord r = stack.topRunningActivityLocked(null);
   2394                 if (r != null) {
   2395                     setFocusedActivityLocked(r, "setFocusedStack");
   2396                 }
   2397             }
   2398         }
   2399     }
   2400 
   2401     /** Sets the task stack listener that gets callbacks when a task stack changes. */
   2402     @Override
   2403     public void registerTaskStackListener(ITaskStackListener listener) throws RemoteException {
   2404         synchronized (ActivityManagerService.this) {
   2405             if (listener != null) {
   2406                 mTaskStackListeners.register(listener);
   2407             }
   2408         }
   2409     }
   2410 
   2411     @Override
   2412     public void notifyActivityDrawn(IBinder token) {
   2413         if (DEBUG_VISBILITY) Slog.d(TAG, "notifyActivityDrawn: token=" + token);
   2414         synchronized (this) {
   2415             ActivityRecord r= mStackSupervisor.isInAnyStackLocked(token);
   2416             if (r != null) {
   2417                 r.task.stack.notifyActivityDrawnLocked(r);
   2418             }
   2419         }
   2420     }
   2421 
   2422     final void applyUpdateLockStateLocked(ActivityRecord r) {
   2423         // Modifications to the UpdateLock state are done on our handler, outside
   2424         // the activity manager's locks.  The new state is determined based on the
   2425         // state *now* of the relevant activity record.  The object is passed to
   2426         // the handler solely for logging detail, not to be consulted/modified.
   2427         final boolean nextState = r != null && r.immersive;
   2428         mHandler.sendMessage(
   2429                 mHandler.obtainMessage(IMMERSIVE_MODE_LOCK_MSG, (nextState) ? 1 : 0, 0, r));
   2430     }
   2431 
   2432     final void showAskCompatModeDialogLocked(ActivityRecord r) {
   2433         Message msg = Message.obtain();
   2434         msg.what = SHOW_COMPAT_MODE_DIALOG_MSG;
   2435         msg.obj = r.task.askedCompatMode ? null : r;
   2436         mHandler.sendMessage(msg);
   2437     }
   2438 
   2439     private int updateLruProcessInternalLocked(ProcessRecord app, long now, int index,
   2440             String what, Object obj, ProcessRecord srcApp) {
   2441         app.lastActivityTime = now;
   2442 
   2443         if (app.activities.size() > 0) {
   2444             // Don't want to touch dependent processes that are hosting activities.
   2445             return index;
   2446         }
   2447 
   2448         int lrui = mLruProcesses.lastIndexOf(app);
   2449         if (lrui < 0) {
   2450             Slog.wtf(TAG, "Adding dependent process " + app + " not on LRU list: "
   2451                     + what + " " + obj + " from " + srcApp);
   2452             return index;
   2453         }
   2454 
   2455         if (lrui >= index) {
   2456             // Don't want to cause this to move dependent processes *back* in the
   2457             // list as if they were less frequently used.
   2458             return index;
   2459         }
   2460 
   2461         if (lrui >= mLruProcessActivityStart) {
   2462             // Don't want to touch dependent processes that are hosting activities.
   2463             return index;
   2464         }
   2465 
   2466         mLruProcesses.remove(lrui);
   2467         if (index > 0) {
   2468             index--;
   2469         }
   2470         if (DEBUG_LRU) Slog.d(TAG, "Moving dep from " + lrui + " to " + index
   2471                 + " in LRU list: " + app);
   2472         mLruProcesses.add(index, app);
   2473         return index;
   2474     }
   2475 
   2476     final void removeLruProcessLocked(ProcessRecord app) {
   2477         int lrui = mLruProcesses.lastIndexOf(app);
   2478         if (lrui >= 0) {
   2479             if (!app.killed) {
   2480                 Slog.wtfStack(TAG, "Removing process that hasn't been killed: " + app);
   2481                 Process.killProcessQuiet(app.pid);
   2482                 Process.killProcessGroup(app.info.uid, app.pid);
   2483             }
   2484             if (lrui <= mLruProcessActivityStart) {
   2485                 mLruProcessActivityStart--;
   2486             }
   2487             if (lrui <= mLruProcessServiceStart) {
   2488                 mLruProcessServiceStart--;
   2489             }
   2490             mLruProcesses.remove(lrui);
   2491         }
   2492     }
   2493 
   2494     final void updateLruProcessLocked(ProcessRecord app, boolean activityChange,
   2495             ProcessRecord client) {
   2496         final boolean hasActivity = app.activities.size() > 0 || app.hasClientActivities
   2497                 || app.treatLikeActivity;
   2498         final boolean hasService = false; // not impl yet. app.services.size() > 0;
   2499         if (!activityChange && hasActivity) {
   2500             // The process has activities, so we are only allowing activity-based adjustments
   2501             // to move it.  It should be kept in the front of the list with other
   2502             // processes that have activities, and we don't want those to change their
   2503             // order except due to activity operations.
   2504             return;
   2505         }
   2506 
   2507         mLruSeq++;
   2508         final long now = SystemClock.uptimeMillis();
   2509         app.lastActivityTime = now;
   2510 
   2511         // First a quick reject: if the app is already at the position we will
   2512         // put it, then there is nothing to do.
   2513         if (hasActivity) {
   2514             final int N = mLruProcesses.size();
   2515             if (N > 0 && mLruProcesses.get(N-1) == app) {
   2516                 if (DEBUG_LRU) Slog.d(TAG, "Not moving, already top activity: " + app);
   2517                 return;
   2518             }
   2519         } else {
   2520             if (mLruProcessServiceStart > 0
   2521                     && mLruProcesses.get(mLruProcessServiceStart-1) == app) {
   2522                 if (DEBUG_LRU) Slog.d(TAG, "Not moving, already top other: " + app);
   2523                 return;
   2524             }
   2525         }
   2526 
   2527         int lrui = mLruProcesses.lastIndexOf(app);
   2528 
   2529         if (app.persistent && lrui >= 0) {
   2530             // We don't care about the position of persistent processes, as long as
   2531             // they are in the list.
   2532             if (DEBUG_LRU) Slog.d(TAG, "Not moving, persistent: " + app);
   2533             return;
   2534         }
   2535 
   2536         /* In progress: compute new position first, so we can avoid doing work
   2537            if the process is not actually going to move.  Not yet working.
   2538         int addIndex;
   2539         int nextIndex;
   2540         boolean inActivity = false, inService = false;
   2541         if (hasActivity) {
   2542             // Process has activities, put it at the very tipsy-top.
   2543             addIndex = mLruProcesses.size();
   2544             nextIndex = mLruProcessServiceStart;
   2545             inActivity = true;
   2546         } else if (hasService) {
   2547             // Process has services, put it at the top of the service list.
   2548             addIndex = mLruProcessActivityStart;
   2549             nextIndex = mLruProcessServiceStart;
   2550             inActivity = true;
   2551             inService = true;
   2552         } else  {
   2553             // Process not otherwise of interest, it goes to the top of the non-service area.
   2554             addIndex = mLruProcessServiceStart;
   2555             if (client != null) {
   2556                 int clientIndex = mLruProcesses.lastIndexOf(client);
   2557                 if (clientIndex < 0) Slog.d(TAG, "Unknown client " + client + " when updating "
   2558                         + app);
   2559                 if (clientIndex >= 0 && addIndex > clientIndex) {
   2560                     addIndex = clientIndex;
   2561                 }
   2562             }
   2563             nextIndex = addIndex > 0 ? addIndex-1 : addIndex;
   2564         }
   2565 
   2566         Slog.d(TAG, "Update LRU at " + lrui + " to " + addIndex + " (act="
   2567                 + mLruProcessActivityStart + "): " + app);
   2568         */
   2569 
   2570         if (lrui >= 0) {
   2571             if (lrui < mLruProcessActivityStart) {
   2572                 mLruProcessActivityStart--;
   2573             }
   2574             if (lrui < mLruProcessServiceStart) {
   2575                 mLruProcessServiceStart--;
   2576             }
   2577             /*
   2578             if (addIndex > lrui) {
   2579                 addIndex--;
   2580             }
   2581             if (nextIndex > lrui) {
   2582                 nextIndex--;
   2583             }
   2584             */
   2585             mLruProcesses.remove(lrui);
   2586         }
   2587 
   2588         /*
   2589         mLruProcesses.add(addIndex, app);
   2590         if (inActivity) {
   2591             mLruProcessActivityStart++;
   2592         }
   2593         if (inService) {
   2594             mLruProcessActivityStart++;
   2595         }
   2596         */
   2597 
   2598         int nextIndex;
   2599         if (hasActivity) {
   2600             final int N = mLruProcesses.size();
   2601             if (app.activities.size() == 0 && mLruProcessActivityStart < (N-1)) {
   2602                 // Process doesn't have activities, but has clients with
   2603                 // activities...  move it up, but one below the top (the top
   2604                 // should always have a real activity).
   2605                 if (DEBUG_LRU) Slog.d(TAG, "Adding to second-top of LRU activity list: " + app);
   2606                 mLruProcesses.add(N-1, app);
   2607                 // To keep it from spamming the LRU list (by making a bunch of clients),
   2608                 // we will push down any other entries owned by the app.
   2609                 final int uid = app.info.uid;
   2610                 for (int i=N-2; i>mLruProcessActivityStart; i--) {
   2611                     ProcessRecord subProc = mLruProcesses.get(i);
   2612                     if (subProc.info.uid == uid) {
   2613                         // We want to push this one down the list.  If the process after
   2614                         // it is for the same uid, however, don't do so, because we don't
   2615                         // want them internally to be re-ordered.
   2616                         if (mLruProcesses.get(i-1).info.uid != uid) {
   2617                             if (DEBUG_LRU) Slog.d(TAG, "Pushing uid " + uid + " swapping at " + i
   2618                                     + ": " + mLruProcesses.get(i) + " : " + mLruProcesses.get(i-1));
   2619                             ProcessRecord tmp = mLruProcesses.get(i);
   2620                             mLruProcesses.set(i, mLruProcesses.get(i-1));
   2621                             mLruProcesses.set(i-1, tmp);
   2622                             i--;
   2623                         }
   2624                     } else {
   2625                         // A gap, we can stop here.
   2626                         break;
   2627                     }
   2628                 }
   2629             } else {
   2630                 // Process has activities, put it at the very tipsy-top.
   2631                 if (DEBUG_LRU) Slog.d(TAG, "Adding to top of LRU activity list: " + app);
   2632                 mLruProcesses.add(app);
   2633             }
   2634             nextIndex =