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 com.android.internal.telephony.TelephonyIntents;
     20 import com.google.android.collect.Lists;
     21 import com.google.android.collect.Maps;
     22 import com.android.internal.R;
     23 import com.android.internal.annotations.GuardedBy;
     24 import com.android.internal.app.AssistUtils;
     25 import com.android.internal.app.DumpHeapActivity;
     26 import com.android.internal.app.IAppOpsCallback;
     27 import com.android.internal.app.IAppOpsService;
     28 import com.android.internal.app.IVoiceInteractor;
     29 import com.android.internal.app.ProcessMap;
     30 import com.android.internal.app.SystemUserHomeActivity;
     31 import com.android.internal.app.procstats.ProcessStats;
     32 import com.android.internal.os.BackgroundThread;
     33 import com.android.internal.os.BatteryStatsImpl;
     34 import com.android.internal.os.IResultReceiver;
     35 import com.android.internal.os.ProcessCpuTracker;
     36 import com.android.internal.os.TransferPipe;
     37 import com.android.internal.os.Zygote;
     38 import com.android.internal.os.InstallerConnection.InstallerException;
     39 import com.android.internal.util.ArrayUtils;
     40 import com.android.internal.util.FastPrintWriter;
     41 import com.android.internal.util.FastXmlSerializer;
     42 import com.android.internal.util.MemInfoReader;
     43 import com.android.internal.util.Preconditions;
     44 import com.android.server.AppOpsService;
     45 import com.android.server.AttributeCache;
     46 import com.android.server.DeviceIdleController;
     47 import com.android.server.IntentResolver;
     48 import com.android.server.LocalServices;
     49 import com.android.server.LockGuard;
     50 import com.android.server.ServiceThread;
     51 import com.android.server.SystemService;
     52 import com.android.server.SystemServiceManager;
     53 import com.android.server.Watchdog;
     54 import com.android.server.am.ActivityStack.ActivityState;
     55 import com.android.server.firewall.IntentFirewall;
     56 import com.android.server.pm.Installer;
     57 import com.android.server.statusbar.StatusBarManagerInternal;
     58 import com.android.server.vr.VrManagerInternal;
     59 import com.android.server.wm.WindowManagerService;
     60 
     61 import org.xmlpull.v1.XmlPullParser;
     62 import org.xmlpull.v1.XmlPullParserException;
     63 import org.xmlpull.v1.XmlSerializer;
     64 
     65 import android.Manifest;
     66 import android.Manifest.permission;
     67 import android.annotation.NonNull;
     68 import android.annotation.UserIdInt;
     69 import android.app.Activity;
     70 import android.app.ActivityManager;
     71 import android.app.ActivityManager.RunningTaskInfo;
     72 import android.app.ActivityManager.StackId;
     73 import android.app.ActivityManager.StackInfo;
     74 import android.app.ActivityManager.TaskThumbnailInfo;
     75 import android.app.ActivityManagerInternal;
     76 import android.app.ActivityManagerInternal.SleepToken;
     77 import android.app.ActivityManagerNative;
     78 import android.app.ActivityOptions;
     79 import android.app.ActivityThread;
     80 import android.app.AlertDialog;
     81 import android.app.AppGlobals;
     82 import android.app.AppOpsManager;
     83 import android.app.ApplicationErrorReport;
     84 import android.app.ApplicationThreadNative;
     85 import android.app.BroadcastOptions;
     86 import android.app.Dialog;
     87 import android.app.IActivityContainer;
     88 import android.app.IActivityContainerCallback;
     89 import android.app.IActivityController;
     90 import android.app.IAppTask;
     91 import android.app.IApplicationThread;
     92 import android.app.IInstrumentationWatcher;
     93 import android.app.INotificationManager;
     94 import android.app.IProcessObserver;
     95 import android.app.IServiceConnection;
     96 import android.app.IStopUserCallback;
     97 import android.app.ITaskStackListener;
     98 import android.app.IUiAutomationConnection;
     99 import android.app.IUidObserver;
    100 import android.app.IUserSwitchObserver;
    101 import android.app.Instrumentation;
    102 import android.app.Notification;
    103 import android.app.NotificationManager;
    104 import android.app.PendingIntent;
    105 import android.app.ProfilerInfo;
    106 import android.app.admin.DevicePolicyManager;
    107 import android.app.assist.AssistContent;
    108 import android.app.assist.AssistStructure;
    109 import android.app.backup.IBackupManager;
    110 import android.app.usage.UsageEvents;
    111 import android.app.usage.UsageStatsManagerInternal;
    112 import android.appwidget.AppWidgetManager;
    113 import android.content.ActivityNotFoundException;
    114 import android.content.BroadcastReceiver;
    115 import android.content.ClipData;
    116 import android.content.ComponentCallbacks2;
    117 import android.content.ComponentName;
    118 import android.content.ContentProvider;
    119 import android.content.ContentResolver;
    120 import android.content.Context;
    121 import android.content.DialogInterface;
    122 import android.content.IContentProvider;
    123 import android.content.IIntentReceiver;
    124 import android.content.IIntentSender;
    125 import android.content.Intent;
    126 import android.content.IntentFilter;
    127 import android.content.IntentSender;
    128 import android.content.pm.ActivityInfo;
    129 import android.content.pm.ApplicationInfo;
    130 import android.content.pm.ConfigurationInfo;
    131 import android.content.pm.IPackageDataObserver;
    132 import android.content.pm.IPackageManager;
    133 import android.content.pm.InstrumentationInfo;
    134 import android.content.pm.PackageInfo;
    135 import android.content.pm.PackageManager;
    136 import android.content.pm.PackageManager.NameNotFoundException;
    137 import android.content.pm.PackageManagerInternal;
    138 import android.content.pm.ParceledListSlice;
    139 import android.content.pm.PathPermission;
    140 import android.content.pm.PermissionInfo;
    141 import android.content.pm.ProviderInfo;
    142 import android.content.pm.ResolveInfo;
    143 import android.content.pm.ServiceInfo;
    144 import android.content.pm.UserInfo;
    145 import android.content.res.CompatibilityInfo;
    146 import android.content.res.Configuration;
    147 import android.content.res.Resources;
    148 import android.database.ContentObserver;
    149 import android.graphics.Bitmap;
    150 import android.graphics.Point;
    151 import android.graphics.Rect;
    152 import android.location.LocationManager;
    153 import android.net.Proxy;
    154 import android.net.ProxyInfo;
    155 import android.net.Uri;
    156 import android.os.BatteryStats;
    157 import android.os.Binder;
    158 import android.os.Build;
    159 import android.os.Bundle;
    160 import android.os.Debug;
    161 import android.os.DropBoxManager;
    162 import android.os.Environment;
    163 import android.os.FactoryTest;
    164 import android.os.FileObserver;
    165 import android.os.FileUtils;
    166 import android.os.Handler;
    167 import android.os.IBinder;
    168 import android.os.IPermissionController;
    169 import android.os.IProcessInfoService;
    170 import android.os.IProgressListener;
    171 import android.os.LocaleList;
    172 import android.os.Looper;
    173 import android.os.Message;
    174 import android.os.Parcel;
    175 import android.os.ParcelFileDescriptor;
    176 import android.os.PersistableBundle;
    177 import android.os.PowerManager;
    178 import android.os.PowerManagerInternal;
    179 import android.os.Process;
    180 import android.os.RemoteCallbackList;
    181 import android.os.RemoteException;
    182 import android.os.ResultReceiver;
    183 import android.os.ServiceManager;
    184 import android.os.StrictMode;
    185 import android.os.SystemClock;
    186 import android.os.SystemProperties;
    187 import android.os.Trace;
    188 import android.os.TransactionTooLargeException;
    189 import android.os.UpdateLock;
    190 import android.os.UserHandle;
    191 import android.os.UserManager;
    192 import android.os.WorkSource;
    193 import android.os.storage.IMountService;
    194 import android.os.storage.MountServiceInternal;
    195 import android.os.storage.StorageManager;
    196 import android.provider.Settings;
    197 import android.service.voice.IVoiceInteractionSession;
    198 import android.service.voice.VoiceInteractionManagerInternal;
    199 import android.service.voice.VoiceInteractionSession;
    200 import android.telecom.TelecomManager;
    201 import android.text.format.DateUtils;
    202 import android.text.format.Time;
    203 import android.text.style.SuggestionSpan;
    204 import android.util.ArrayMap;
    205 import android.util.ArraySet;
    206 import android.util.AtomicFile;
    207 import android.util.DebugUtils;
    208 import android.util.DisplayMetrics;
    209 import android.util.EventLog;
    210 import android.util.Log;
    211 import android.util.Pair;
    212 import android.util.PrintWriterPrinter;
    213 import android.util.Slog;
    214 import android.util.SparseArray;
    215 import android.util.TimeUtils;
    216 import android.util.Xml;
    217 import android.view.Display;
    218 import android.view.Gravity;
    219 import android.view.LayoutInflater;
    220 import android.view.View;
    221 import android.view.WindowManager;
    222 
    223 import java.io.File;
    224 import java.io.FileDescriptor;
    225 import java.io.FileInputStream;
    226 import java.io.FileNotFoundException;
    227 import java.io.FileOutputStream;
    228 import java.io.IOException;
    229 import java.io.InputStreamReader;
    230 import java.io.PrintWriter;
    231 import java.io.StringWriter;
    232 import java.lang.ref.WeakReference;
    233 import java.nio.charset.StandardCharsets;
    234 import java.util.ArrayList;
    235 import java.util.Arrays;
    236 import java.util.Collections;
    237 import java.util.Comparator;
    238 import java.util.HashMap;
    239 import java.util.HashSet;
    240 import java.util.Iterator;
    241 import java.util.List;
    242 import java.util.Locale;
    243 import java.util.Map;
    244 import java.util.Objects;
    245 import java.util.Set;
    246 import java.util.concurrent.atomic.AtomicBoolean;
    247 import java.util.concurrent.atomic.AtomicLong;
    248 
    249 import dalvik.system.VMRuntime;
    250 
    251 import libcore.io.IoUtils;
    252 import libcore.util.EmptyArray;
    253 
    254 import static android.Manifest.permission.INTERACT_ACROSS_USERS;
    255 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
    256 import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
    257 import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
    258 import static android.app.ActivityManager.DOCKED_STACK_CREATE_MODE_TOP_OR_LEFT;
    259 import static android.app.ActivityManager.RESIZE_MODE_PRESERVE_WINDOW;
    260 import static android.app.ActivityManager.StackId.DOCKED_STACK_ID;
    261 import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID;
    262 import static android.app.ActivityManager.StackId.FULLSCREEN_WORKSPACE_STACK_ID;
    263 import static android.app.ActivityManager.StackId.HOME_STACK_ID;
    264 import static android.app.ActivityManager.StackId.INVALID_STACK_ID;
    265 import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
    266 import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
    267 import static android.content.pm.PackageManager.FEATURE_LEANBACK_ONLY;
    268 import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
    269 import static android.content.pm.PackageManager.GET_PROVIDERS;
    270 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
    271 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
    272 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
    273 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
    274 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
    275 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
    276 import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
    277 import static android.os.Process.PROC_CHAR;
    278 import static android.os.Process.PROC_OUT_LONG;
    279 import static android.os.Process.PROC_PARENS;
    280 import static android.os.Process.PROC_SPACE_TERM;
    281 import static android.provider.Settings.Global.ALWAYS_FINISH_ACTIVITIES;
    282 import static android.provider.Settings.Global.DEBUG_APP;
    283 import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
    284 import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
    285 import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
    286 import static android.provider.Settings.Global.LENIENT_BACKGROUND_CHECK;
    287 import static android.provider.Settings.Global.WAIT_FOR_DEBUGGER;
    288 import static android.provider.Settings.System.FONT_SCALE;
    289 import static com.android.internal.util.XmlUtils.readBooleanAttribute;
    290 import static com.android.internal.util.XmlUtils.readIntAttribute;
    291 import static com.android.internal.util.XmlUtils.readLongAttribute;
    292 import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
    293 import static com.android.internal.util.XmlUtils.writeIntAttribute;
    294 import static com.android.internal.util.XmlUtils.writeLongAttribute;
    295 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
    296 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ANR;
    297 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKUP;
    298 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST;
    299 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_BACKGROUND;
    300 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_LIGHT;
    301 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_CLEANUP;
    302 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_CONFIGURATION;
    303 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOCUS;
    304 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_IMMERSIVE;
    305 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKSCREEN;
    306 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKTASK;
    307 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LRU;
    308 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
    309 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_OOM_ADJ;
    310 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW;
    311 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_POWER;
    312 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_POWER_QUICK;
    313 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESSES;
    314 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESS_OBSERVERS;
    315 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROVIDER;
    316 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PSS;
    317 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RECENTS;
    318 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE;
    319 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STACK;
    320 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SWITCH;
    321 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TASKS;
    322 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_UID_OBSERVERS;
    323 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_URI_PERMISSION;
    324 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_USAGE_STATS;
    325 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_VISIBILITY;
    326 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_VISIBLE_BEHIND;
    327 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_WHITELISTS;
    328 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BACKUP;
    329 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BROADCAST;
    330 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CLEANUP;
    331 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CONFIGURATION;
    332 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_FOCUS;
    333 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_IMMERSIVE;
    334 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LOCKSCREEN;
    335 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LOCKTASK;
    336 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LRU;
    337 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU;
    338 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_OOM_ADJ;
    339 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_POWER;
    340 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROCESSES;
    341 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROCESS_OBSERVERS;
    342 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROVIDER;
    343 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PSS;
    344 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RECENTS;
    345 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE;
    346 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STACK;
    347 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SWITCH;
    348 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_UID_OBSERVERS;
    349 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_URI_PERMISSION;
    350 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_VISIBILITY;
    351 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_VISIBLE_BEHIND;
    352 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
    353 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
    354 import static com.android.server.am.ActivityRecord.RECENTS_ACTIVITY_TYPE;
    355 import static com.android.server.am.ActivityStackSupervisor.ActivityContainer.FORCE_NEW_TASK_FLAGS;
    356 import static com.android.server.am.ActivityStackSupervisor.DEFER_RESUME;
    357 import static com.android.server.am.ActivityStackSupervisor.FORCE_FOCUS;
    358 import static com.android.server.am.ActivityStackSupervisor.ON_TOP;
    359 import static com.android.server.am.ActivityStackSupervisor.PRESERVE_WINDOWS;
    360 import static com.android.server.am.ActivityStackSupervisor.RESTORE_FROM_RECENTS;
    361 import static com.android.server.am.TaskRecord.INVALID_TASK_ID;
    362 import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
    363 import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV;
    364 import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_PINNABLE;
    365 import static com.android.server.wm.AppTransition.TRANSIT_ACTIVITY_OPEN;
    366 import static com.android.server.wm.AppTransition.TRANSIT_ACTIVITY_RELAUNCH;
    367 import static com.android.server.wm.AppTransition.TRANSIT_TASK_IN_PLACE;
    368 import static com.android.server.wm.AppTransition.TRANSIT_TASK_OPEN;
    369 import static com.android.server.wm.AppTransition.TRANSIT_TASK_TO_FRONT;
    370 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
    371 import static org.xmlpull.v1.XmlPullParser.START_TAG;
    372 
    373 public final class ActivityManagerService extends ActivityManagerNative
    374         implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
    375 
    376     private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityManagerService" : TAG_AM;
    377     private static final String TAG_BACKUP = TAG + POSTFIX_BACKUP;
    378     private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
    379     private static final String TAG_CLEANUP = TAG + POSTFIX_CLEANUP;
    380     private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
    381     private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
    382     private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
    383     private static final String TAG_LOCKSCREEN = TAG + POSTFIX_LOCKSCREEN;
    384     private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
    385     private static final String TAG_LRU = TAG + POSTFIX_LRU;
    386     private static final String TAG_MU = TAG + POSTFIX_MU;
    387     private static final String TAG_OOM_ADJ = TAG + POSTFIX_OOM_ADJ;
    388     private static final String TAG_POWER = TAG + POSTFIX_POWER;
    389     private static final String TAG_PROCESS_OBSERVERS = TAG + POSTFIX_PROCESS_OBSERVERS;
    390     private static final String TAG_PROCESSES = TAG + POSTFIX_PROCESSES;
    391     private static final String TAG_PROVIDER = TAG + POSTFIX_PROVIDER;
    392     private static final String TAG_PSS = TAG + POSTFIX_PSS;
    393     private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS;
    394     private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
    395     private static final String TAG_STACK = TAG + POSTFIX_STACK;
    396     private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
    397     private static final String TAG_UID_OBSERVERS = TAG + POSTFIX_UID_OBSERVERS;
    398     private static final String TAG_URI_PERMISSION = TAG + POSTFIX_URI_PERMISSION;
    399     private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
    400     private static final String TAG_VISIBLE_BEHIND = TAG + POSTFIX_VISIBLE_BEHIND;
    401 
    402     // Mock "pretend we're idle now" broadcast action to the job scheduler; declared
    403     // here so that while the job scheduler can depend on AMS, the other way around
    404     // need not be the case.
    405     public static final String ACTION_TRIGGER_IDLE = "com.android.server.ACTION_TRIGGER_IDLE";
    406 
    407     /** Control over CPU and battery monitoring */
    408     // write battery stats every 30 minutes.
    409     static final long BATTERY_STATS_TIME = 30 * 60 * 1000;
    410     static final boolean MONITOR_CPU_USAGE = true;
    411     // don't sample cpu less than every 5 seconds.
    412     static final long MONITOR_CPU_MIN_TIME = 5 * 1000;
    413     // wait possibly forever for next cpu sample.
    414     static final long MONITOR_CPU_MAX_TIME = 0x0fffffff;
    415     static final boolean MONITOR_THREAD_CPU_USAGE = false;
    416 
    417     // The flags that are set for all calls we make to the package manager.
    418     static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
    419 
    420     static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
    421 
    422     static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
    423 
    424     // Amount of time after a call to stopAppSwitches() during which we will
    425     // prevent further untrusted switches from happening.
    426     static final long APP_SWITCH_DELAY_TIME = 5*1000;
    427 
    428     // How long we wait for a launched process to attach to the activity manager
    429     // before we decide it's never going to come up for real.
    430     static final int PROC_START_TIMEOUT = 10*1000;
    431     // How long we wait for an attached process to publish its content providers
    432     // before we decide it must be hung.
    433     static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT = 10*1000;
    434 
    435     // How long we will retain processes hosting content providers in the "last activity"
    436     // state before allowing them to drop down to the regular cached LRU list.  This is
    437     // to avoid thrashing of provider processes under low memory situations.
    438     static final int CONTENT_PROVIDER_RETAIN_TIME = 20*1000;
    439 
    440     // How long we wait for a launched process to attach to the activity manager
    441     // before we decide it's never going to come up for real, when the process was
    442     // started with a wrapper for instrumentation (such as Valgrind) because it
    443     // could take much longer than usual.
    444     static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000;
    445 
    446     // How long to wait after going idle before forcing apps to GC.
    447     static final int GC_TIMEOUT = 5*1000;
    448 
    449     // The minimum amount of time between successive GC requests for a process.
    450     static final int GC_MIN_INTERVAL = 60*1000;
    451 
    452     // The minimum amount of time between successive PSS requests for a process.
    453     static final int FULL_PSS_MIN_INTERVAL = 10*60*1000;
    454 
    455     // The minimum amount of time between successive PSS requests for a process
    456     // when the request is due to the memory state being lowered.
    457     static final int FULL_PSS_LOWERED_INTERVAL = 2*60*1000;
    458 
    459     // The rate at which we check for apps using excessive power -- 15 mins.
    460     static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
    461 
    462     // The minimum sample duration we will allow before deciding we have
    463     // enough data on wake locks to start killing things.
    464     static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
    465 
    466     // The minimum sample duration we will allow before deciding we have
    467     // enough data on CPU usage to start killing things.
    468     static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
    469 
    470     // How long we allow a receiver to run before giving up on it.
    471     static final int BROADCAST_FG_TIMEOUT = 10*1000;
    472     static final int BROADCAST_BG_TIMEOUT = 60*1000;
    473 
    474     // How long we wait until we timeout on key dispatching.
    475     static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
    476 
    477     // How long we wait until we timeout on key dispatching during instrumentation.
    478     static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
    479 
    480     // This is the amount of time an app needs to be running a foreground service before
    481     // we will consider it to be doing interaction for usage stats.
    482     static final int SERVICE_USAGE_INTERACTION_TIME = 30*60*1000;
    483 
    484     // Maximum amount of time we will allow to elapse before re-reporting usage stats
    485     // interaction with foreground processes.
    486     static final long USAGE_STATS_INTERACTION_INTERVAL = 24*60*60*1000L;
    487 
    488     // This is the amount of time we allow an app to settle after it goes into the background,
    489     // before we start restricting what it can do.
    490     static final int BACKGROUND_SETTLE_TIME = 1*60*1000;
    491 
    492     // How long to wait in getAssistContextExtras for the activity and foreground services
    493     // to respond with the result.
    494     static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
    495 
    496     // How long top wait when going through the modern assist (which doesn't need to block
    497     // on getting this result before starting to launch its UI).
    498     static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
    499 
    500     // Maximum number of persisted Uri grants a package is allowed
    501     static final int MAX_PERSISTED_URI_GRANTS = 128;
    502 
    503     static final int MY_PID = Process.myPid();
    504 
    505     static final String[] EMPTY_STRING_ARRAY = new String[0];
    506 
    507     // How many bytes to write into the dropbox log before truncating
    508     static final int DROPBOX_MAX_SIZE = 192 * 1024;
    509     // Assumes logcat entries average around 100 bytes; that's not perfect stack traces count
    510     // as one line, but close enough for now.
    511     static final int RESERVED_BYTES_PER_LOGCAT_LINE = 100;
    512 
    513     // Access modes for handleIncomingUser.
    514     static final int ALLOW_NON_FULL = 0;
    515     static final int ALLOW_NON_FULL_IN_PROFILE = 1;
    516     static final int ALLOW_FULL_ONLY = 2;
    517 
    518     // Delay in notifying task stack change listeners (in millis)
    519     static final int NOTIFY_TASK_STACK_CHANGE_LISTENERS_DELAY = 100;
    520 
    521     // Necessary ApplicationInfo flags to mark an app as persistent
    522     private static final int PERSISTENT_MASK =
    523             ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT;
    524 
    525     // Intent sent when remote bugreport collection has been completed
    526     private static final String INTENT_REMOTE_BUGREPORT_FINISHED =
    527             "android.intent.action.REMOTE_BUGREPORT_FINISHED";
    528 
    529     // Delay to disable app launch boost
    530     static final int APP_BOOST_MESSAGE_DELAY = 3000;
    531     // Lower delay than APP_BOOST_MESSAGE_DELAY to disable the boost
    532     static final int APP_BOOST_TIMEOUT = 2500;
    533 
    534     // Used to indicate that a task is removed it should also be removed from recents.
    535     private static final boolean REMOVE_FROM_RECENTS = true;
    536     // Used to indicate that an app transition should be animated.
    537     static final boolean ANIMATE = true;
    538 
    539     // Determines whether to take full screen screenshots
    540     static final boolean TAKE_FULLSCREEN_SCREENSHOTS = true;
    541     public static final float FULLSCREEN_SCREENSHOT_SCALE = 0.6f;
    542 
    543     private static native int nativeMigrateToBoost();
    544     private static native int nativeMigrateFromBoost();
    545     private boolean mIsBoosted = false;
    546     private long mBoostStartTime = 0;
    547 
    548     /** All system services */
    549     SystemServiceManager mSystemServiceManager;
    550 
    551     private Installer mInstaller;
    552 
    553     /** Run all ActivityStacks through this */
    554     final ActivityStackSupervisor mStackSupervisor;
    555 
    556     final ActivityStarter mActivityStarter;
    557 
    558     /** Task stack change listeners. */
    559     private final RemoteCallbackList<ITaskStackListener> mTaskStackListeners =
    560             new RemoteCallbackList<ITaskStackListener>();
    561 
    562     final InstrumentationReporter mInstrumentationReporter = new InstrumentationReporter();
    563 
    564     public IntentFirewall mIntentFirewall;
    565 
    566     // Whether we should show our dialogs (ANR, crash, etc) or just perform their
    567     // default actuion automatically.  Important for devices without direct input
    568     // devices.
    569     private boolean mShowDialogs = true;
    570     private boolean mInVrMode = false;
    571 
    572     // Whether we should use SCHED_FIFO for UI and RenderThreads.
    573     private boolean mUseFifoUiScheduling = false;
    574 
    575     BroadcastQueue mFgBroadcastQueue;
    576     BroadcastQueue mBgBroadcastQueue;
    577     // Convenient for easy iteration over the queues. Foreground is first
    578     // so that dispatch of foreground broadcasts gets precedence.
    579     final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
    580 
    581     BroadcastStats mLastBroadcastStats;
    582     BroadcastStats mCurBroadcastStats;
    583 
    584     BroadcastQueue broadcastQueueForIntent(Intent intent) {
    585         final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
    586         if (DEBUG_BROADCAST_BACKGROUND) Slog.i(TAG_BROADCAST,
    587                 "Broadcast intent " + intent + " on "
    588                 + (isFg ? "foreground" : "background") + " queue");
    589         return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
    590     }
    591 
    592     /**
    593      * Activity we have told the window manager to have key focus.
    594      */
    595     ActivityRecord mFocusedActivity = null;
    596 
    597     /**
    598      * User id of the last activity mFocusedActivity was set to.
    599      */
    600     private int mLastFocusedUserId;
    601 
    602     /**
    603      * If non-null, we are tracking the time the user spends in the currently focused app.
    604      */
    605     private AppTimeTracker mCurAppTimeTracker;
    606 
    607     /**
    608      * List of intents that were used to start the most recent tasks.
    609      */
    610     final RecentTasks mRecentTasks;
    611 
    612     /**
    613      * For addAppTask: cached of the last activity component that was added.
    614      */
    615     ComponentName mLastAddedTaskComponent;
    616 
    617     /**
    618      * For addAppTask: cached of the last activity uid that was added.
    619      */
    620     int mLastAddedTaskUid;
    621 
    622     /**
    623      * For addAppTask: cached of the last ActivityInfo that was added.
    624      */
    625     ActivityInfo mLastAddedTaskActivity;
    626 
    627     /**
    628      * List of packages whitelisted by DevicePolicyManager for locktask. Indexed by userId.
    629      */
    630     SparseArray<String[]> mLockTaskPackages = new SparseArray<>();
    631 
    632     /**
    633      * The package name of the DeviceOwner. This package is not permitted to have its data cleared.
    634      */
    635     String mDeviceOwnerName;
    636 
    637     final UserController mUserController;
    638 
    639     final AppErrors mAppErrors;
    640 
    641     boolean mDoingSetFocusedActivity;
    642 
    643     public boolean canShowErrorDialogs() {
    644         return mShowDialogs && !mSleeping && !mShuttingDown
    645                 && mLockScreenShown != LOCK_SCREEN_SHOWN;
    646     }
    647 
    648     private static final class PriorityState {
    649         // Acts as counter for number of synchronized region that needs to acquire 'this' as a lock
    650         // the current thread is currently in. When it drops down to zero, we will no longer boost
    651         // the thread's priority.
    652         private int regionCounter = 0;
    653 
    654         // The thread's previous priority before boosting.
    655         private int prevPriority = Integer.MIN_VALUE;
    656     }
    657 
    658     static ThreadLocal<PriorityState> sThreadPriorityState = new ThreadLocal<PriorityState>() {
    659         @Override protected PriorityState initialValue() {
    660             return new PriorityState();
    661         }
    662     };
    663 
    664     static void boostPriorityForLockedSection() {
    665         int tid = Process.myTid();
    666         int prevPriority = Process.getThreadPriority(tid);
    667         PriorityState state = sThreadPriorityState.get();
    668         if (state.regionCounter == 0 && prevPriority > -2) {
    669             state.prevPriority = prevPriority;
    670             Process.setThreadPriority(tid, -2);
    671         }
    672         state.regionCounter++;
    673     }
    674 
    675     static void resetPriorityAfterLockedSection() {
    676         PriorityState state = sThreadPriorityState.get();
    677         state.regionCounter--;
    678         if (state.regionCounter == 0 && state.prevPriority > -2) {
    679             Process.setThreadPriority(Process.myTid(), state.prevPriority);
    680         }
    681     }
    682 
    683     public class PendingAssistExtras extends Binder implements Runnable {
    684         public final ActivityRecord activity;
    685         public final Bundle extras;
    686         public final Intent intent;
    687         public final String hint;
    688         public final IResultReceiver receiver;
    689         public final int userHandle;
    690         public boolean haveResult = false;
    691         public Bundle result = null;
    692         public AssistStructure structure = null;
    693         public AssistContent content = null;
    694         public Bundle receiverExtras;
    695 
    696         public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
    697                 String _hint, IResultReceiver _receiver, Bundle _receiverExtras, int _userHandle) {
    698             activity = _activity;
    699             extras = _extras;
    700             intent = _intent;
    701             hint = _hint;
    702             receiver = _receiver;
    703             receiverExtras = _receiverExtras;
    704             userHandle = _userHandle;
    705         }
    706         @Override
    707         public void run() {
    708             Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
    709             synchronized (this) {
    710                 haveResult = true;
    711                 notifyAll();
    712             }
    713             pendingAssistExtrasTimedOut(this);
    714         }
    715     }
    716 
    717     final ArrayList<PendingAssistExtras> mPendingAssistExtras
    718             = new ArrayList<PendingAssistExtras>();
    719 
    720     /**
    721      * Process management.
    722      */
    723     final ProcessList mProcessList = new ProcessList();
    724 
    725     /**
    726      * All of the applications we currently have running organized by name.
    727      * The keys are strings of the application package name (as
    728      * returned by the package manager), and the keys are ApplicationRecord
    729      * objects.
    730      */
    731     final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
    732 
    733     /**
    734      * Tracking long-term execution of processes to look for abuse and other
    735      * bad app behavior.
    736      */
    737     final ProcessStatsService mProcessStats;
    738 
    739     /**
    740      * The currently running isolated processes.
    741      */
    742     final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
    743 
    744     /**
    745      * Counter for assigning isolated process uids, to avoid frequently reusing the
    746      * same ones.
    747      */
    748     int mNextIsolatedProcessUid = 0;
    749 
    750     /**
    751      * The currently running heavy-weight process, if any.
    752      */
    753     ProcessRecord mHeavyWeightProcess = null;
    754 
    755     /**
    756      * All of the processes we currently have running organized by pid.
    757      * The keys are the pid running the application.
    758      *
    759      * <p>NOTE: This object is protected by its own lock, NOT the global
    760      * activity manager lock!
    761      */
    762     final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
    763 
    764     /**
    765      * All of the processes that have been forced to be foreground.  The key
    766      * is the pid of the caller who requested it (we hold a death
    767      * link on it).
    768      */
    769     abstract class ForegroundToken implements IBinder.DeathRecipient {
    770         int pid;
    771         IBinder token;
    772     }
    773     final SparseArray<ForegroundToken> mForegroundProcesses = new SparseArray<ForegroundToken>();
    774 
    775     /**
    776      * List of records for processes that someone had tried to start before the
    777      * system was ready.  We don't start them at that point, but ensure they
    778      * are started by the time booting is complete.
    779      */
    780     final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>();
    781 
    782     /**
    783      * List of persistent applications that are in the process
    784      * of being started.
    785      */
    786     final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>();
    787 
    788     /**
    789      * Processes that are being forcibly torn down.
    790      */
    791     final ArrayList<ProcessRecord> mRemovedProcesses = new ArrayList<ProcessRecord>();
    792 
    793     /**
    794      * List of running applications, sorted by recent usage.
    795      * The first entry in the list is the least recently used.
    796      */
    797     final ArrayList<ProcessRecord> mLruProcesses = new ArrayList<ProcessRecord>();
    798 
    799     /**
    800      * Where in mLruProcesses that the processes hosting activities start.
    801      */
    802     int mLruProcessActivityStart = 0;
    803 
    804     /**
    805      * Where in mLruProcesses that the processes hosting services start.
    806      * This is after (lower index) than mLruProcessesActivityStart.
    807      */
    808     int mLruProcessServiceStart = 0;
    809 
    810     /**
    811      * List of processes that should gc as soon as things are idle.
    812      */
    813     final ArrayList<ProcessRecord> mProcessesToGc = new ArrayList<ProcessRecord>();
    814 
    815     /**
    816      * Processes we want to collect PSS data from.
    817      */
    818     final ArrayList<ProcessRecord> mPendingPssProcesses = new ArrayList<ProcessRecord>();
    819 
    820     private boolean mBinderTransactionTrackingEnabled = false;
    821 
    822     /**
    823      * Last time we requested PSS data of all processes.
    824      */
    825     long mLastFullPssTime = SystemClock.uptimeMillis();
    826 
    827     /**
    828      * If set, the next time we collect PSS data we should do a full collection
    829      * with data from native processes and the kernel.
    830      */
    831     boolean mFullPssPending = false;
    832 
    833     /**
    834      * This is the process holding what we currently consider to be
    835      * the "home" activity.
    836      */
    837     ProcessRecord mHomeProcess;
    838 
    839     /**
    840      * This is the process holding the activity the user last visited that
    841      * is in a different process from the one they are currently in.
    842      */
    843     ProcessRecord mPreviousProcess;
    844 
    845     /**
    846      * The time at which the previous process was last visible.
    847      */
    848     long mPreviousProcessVisibleTime;
    849 
    850     /**
    851      * Track all uids that have actively running processes.
    852      */
    853     final SparseArray<UidRecord> mActiveUids = new SparseArray<>();
    854 
    855     /**
    856      * This is for verifying the UID report flow.
    857      */
    858     static final boolean VALIDATE_UID_STATES = true;
    859     final SparseArray<UidRecord> mValidateUids = new SparseArray<>();
    860 
    861     /**
    862      * Packages that the user has asked to have run in screen size
    863      * compatibility mode instead of filling the screen.
    864      */
    865     final CompatModePackages mCompatModePackages;
    866 
    867     /**
    868      * Set of IntentSenderRecord objects that are currently active.
    869      */
    870     final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
    871             = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
    872 
    873     /**
    874      * Fingerprints (hashCode()) of stack traces that we've
    875      * already logged DropBox entries for.  Guarded by itself.  If
    876      * something (rogue user app) forces this over
    877      * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
    878      */
    879     private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
    880     private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
    881 
    882     /**
    883      * Strict Mode background batched logging state.
    884      *
    885      * The string buffer is guarded by itself, and its lock is also
    886      * used to determine if another batched write is already
    887      * in-flight.
    888      */
    889     private final StringBuilder mStrictModeBuffer = new StringBuilder();
    890 
    891     /**
    892      * Keeps track of all IIntentReceivers that have been registered for broadcasts.
    893      * Hash keys are the receiver IBinder, hash value is a ReceiverList.
    894      */
    895     final HashMap<IBinder, ReceiverList> mRegisteredReceivers = new HashMap<>();
    896 
    897     /**
    898      * Resolver for broadcast intents to registered receivers.
    899      * Holds BroadcastFilter (subclass of IntentFilter).
    900      */
    901     final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
    902             = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
    903         @Override
    904         protected boolean allowFilterResult(
    905                 BroadcastFilter filter, List<BroadcastFilter> dest) {
    906             IBinder target = filter.receiverList.receiver.asBinder();
    907             for (int i = dest.size() - 1; i >= 0; i--) {
    908                 if (dest.get(i).receiverList.receiver.asBinder() == target) {
    909                     return false;
    910                 }
    911             }
    912             return true;
    913         }
    914 
    915         @Override
    916         protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
    917             if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
    918                     || userId == filter.owningUserId) {
    919                 return super.newResult(filter, match, userId);
    920             }
    921             return null;
    922         }
    923 
    924         @Override
    925         protected BroadcastFilter[] newArray(int size) {
    926             return new BroadcastFilter[size];
    927         }
    928 
    929         @Override
    930         protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) {
    931             return packageName.equals(filter.packageName);
    932         }
    933     };
    934 
    935     /**
    936      * State of all active sticky broadcasts per user.  Keys are the action of the
    937      * sticky Intent, values are an ArrayList of all broadcasted intents with
    938      * that action (which should usually be one).  The SparseArray is keyed
    939      * by the user ID the sticky is for, and can include UserHandle.USER_ALL
    940      * for stickies that are sent to all users.
    941      */
    942     final SparseArray<ArrayMap<String, ArrayList<Intent>>> mStickyBroadcasts =
    943             new SparseArray<ArrayMap<String, ArrayList<Intent>>>();
    944 
    945     final ActiveServices mServices;
    946 
    947     final static class Association {
    948         final int mSourceUid;
    949         final String mSourceProcess;
    950         final int mTargetUid;
    951         final ComponentName mTargetComponent;
    952         final String mTargetProcess;
    953 
    954         int mCount;
    955         long mTime;
    956 
    957         int mNesting;
    958         long mStartTime;
    959 
    960         // states of the source process when the bind occurred.
    961         int mLastState = ActivityManager.MAX_PROCESS_STATE + 1;
    962         long mLastStateUptime;
    963         long[] mStateTimes = new long[ActivityManager.MAX_PROCESS_STATE
    964                 - ActivityManager.MIN_PROCESS_STATE+1];
    965 
    966         Association(int sourceUid, String sourceProcess, int targetUid,
    967                 ComponentName targetComponent, String targetProcess) {
    968             mSourceUid = sourceUid;
    969             mSourceProcess = sourceProcess;
    970             mTargetUid = targetUid;
    971             mTargetComponent = targetComponent;
    972             mTargetProcess = targetProcess;
    973         }
    974     }
    975 
    976     /**
    977      * When service association tracking is enabled, this is all of the associations we
    978      * have seen.  Mapping is target uid -> target component -> source uid -> source process name
    979      * -> association data.
    980      */
    981     final SparseArray<ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>>>
    982             mAssociations = new SparseArray<>();
    983     boolean mTrackingAssociations;
    984 
    985     /**
    986      * Backup/restore process management
    987      */
    988     String mBackupAppName = null;
    989     BackupRecord mBackupTarget = null;
    990 
    991     final ProviderMap mProviderMap;
    992 
    993     /**
    994      * List of content providers who have clients waiting for them.  The
    995      * application is currently being launched and the provider will be
    996      * removed from this list once it is published.
    997      */
    998     final ArrayList<ContentProviderRecord> mLaunchingProviders
    999             = new ArrayList<ContentProviderRecord>();
   1000 
   1001     /**
   1002      * File storing persisted {@link #mGrantedUriPermissions}.
   1003      */
   1004     private final AtomicFile mGrantFile;
   1005 
   1006     /** XML constants used in {@link #mGrantFile} */
   1007     private static final String TAG_URI_GRANTS = "uri-grants";
   1008     private static final String TAG_URI_GRANT = "uri-grant";
   1009     private static final String ATTR_USER_HANDLE = "userHandle";
   1010     private static final String ATTR_SOURCE_USER_ID = "sourceUserId";
   1011     private static final String ATTR_TARGET_USER_ID = "targetUserId";
   1012     private static final String ATTR_SOURCE_PKG = "sourcePkg";
   1013     private static final String ATTR_TARGET_PKG = "targetPkg";
   1014     private static final String ATTR_URI = "uri";
   1015     private static final String ATTR_MODE_FLAGS = "modeFlags";
   1016     private static final String ATTR_CREATED_TIME = "createdTime";
   1017     private static final String ATTR_PREFIX = "prefix";
   1018 
   1019     /**
   1020      * Global set of specific {@link Uri} permissions that have been granted.
   1021      * This optimized lookup structure maps from {@link UriPermission#targetUid}
   1022      * to {@link UriPermission#uri} to {@link UriPermission}.
   1023      */
   1024     @GuardedBy("this")
   1025     private final SparseArray<ArrayMap<GrantUri, UriPermission>>
   1026             mGrantedUriPermissions = new SparseArray<ArrayMap<GrantUri, UriPermission>>();
   1027 
   1028     public static class GrantUri {
   1029         public final int sourceUserId;
   1030         public final Uri uri;
   1031         public boolean prefix;
   1032 
   1033         public GrantUri(int sourceUserId, Uri uri, boolean prefix) {
   1034             this.sourceUserId = sourceUserId;
   1035             this.uri = uri;
   1036             this.prefix = prefix;
   1037         }
   1038 
   1039         @Override
   1040         public int hashCode() {
   1041             int hashCode = 1;
   1042             hashCode = 31 * hashCode + sourceUserId;
   1043             hashCode = 31 * hashCode + uri.hashCode();
   1044             hashCode = 31 * hashCode + (prefix ? 1231 : 1237);
   1045             return hashCode;
   1046         }
   1047 
   1048         @Override
   1049         public boolean equals(Object o) {
   1050             if (o instanceof GrantUri) {
   1051                 GrantUri other = (GrantUri) o;
   1052                 return uri.equals(other.uri) && (sourceUserId == other.sourceUserId)
   1053                         && prefix == other.prefix;
   1054             }
   1055             return false;
   1056         }
   1057 
   1058         @Override
   1059         public String toString() {
   1060             String result = Integer.toString(sourceUserId) + " @ " + uri.toString();
   1061             if (prefix) result += " [prefix]";
   1062             return result;
   1063         }
   1064 
   1065         public String toSafeString() {
   1066             String result = Integer.toString(sourceUserId) + " @ " + uri.toSafeString();
   1067             if (prefix) result += " [prefix]";
   1068             return result;
   1069         }
   1070 
   1071         public static GrantUri resolve(int defaultSourceUserHandle, Uri uri) {
   1072             return new GrantUri(ContentProvider.getUserIdFromUri(uri, defaultSourceUserHandle),
   1073                     ContentProvider.getUriWithoutUserId(uri), false);
   1074         }
   1075     }
   1076 
   1077     CoreSettingsObserver mCoreSettingsObserver;
   1078 
   1079     FontScaleSettingObserver mFontScaleSettingObserver;
   1080 
   1081     private final class FontScaleSettingObserver extends ContentObserver {
   1082         private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
   1083 
   1084         public FontScaleSettingObserver() {
   1085             super(mHandler);
   1086             ContentResolver resolver = mContext.getContentResolver();
   1087             resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
   1088         }
   1089 
   1090         @Override
   1091         public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
   1092             if (mFontScaleUri.equals(uri)) {
   1093                 updateFontScaleIfNeeded(userId);
   1094             }
   1095         }
   1096     }
   1097 
   1098     /**
   1099      * Thread-local storage used to carry caller permissions over through
   1100      * indirect content-provider access.
   1101      */
   1102     private class Identity {
   1103         public final IBinder token;
   1104         public final int pid;
   1105         public final int uid;
   1106 
   1107         Identity(IBinder _token, int _pid, int _uid) {
   1108             token = _token;
   1109             pid = _pid;
   1110             uid = _uid;
   1111         }
   1112     }
   1113 
   1114     private static final ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
   1115 
   1116     /**
   1117      * All information we have collected about the runtime performance of
   1118      * any user id that can impact battery performance.
   1119      */
   1120     final BatteryStatsService mBatteryStatsService;
   1121 
   1122     /**
   1123      * Information about component usage
   1124      */
   1125     UsageStatsManagerInternal mUsageStatsService;
   1126 
   1127     /**
   1128      * Access to DeviceIdleController service.
   1129      */
   1130     DeviceIdleController.LocalService mLocalDeviceIdleController;
   1131 
   1132     /**
   1133      * Information about and control over application operations
   1134      */
   1135     final AppOpsService mAppOpsService;
   1136 
   1137     /**
   1138      * Current configuration information.  HistoryRecord objects are given
   1139      * a reference to this object to indicate which configuration they are
   1140      * currently running in, so this object must be kept immutable.
   1141      */
   1142     Configuration mConfiguration = new Configuration();
   1143 
   1144     /**
   1145      * Current sequencing integer of the configuration, for skipping old
   1146      * configurations.
   1147      */
   1148     int mConfigurationSeq = 0;
   1149 
   1150     boolean mSuppressResizeConfigChanges = false;
   1151 
   1152     /**
   1153      * Hardware-reported OpenGLES version.
   1154      */
   1155     final int GL_ES_VERSION;
   1156 
   1157     /**
   1158      * List of initialization arguments to pass to all processes when binding applications to them.
   1159      * For example, references to the commonly used services.
   1160      */
   1161     HashMap<String, IBinder> mAppBindArgs;
   1162     HashMap<String, IBinder> mIsolatedAppBindArgs;
   1163 
   1164     /**
   1165      * Temporary to avoid allocations.  Protected by main lock.
   1166      */
   1167     final StringBuilder mStringBuilder = new StringBuilder(256);
   1168 
   1169     /**
   1170      * Used to control how we initialize the service.
   1171      */
   1172     ComponentName mTopComponent;
   1173     String mTopAction = Intent.ACTION_MAIN;
   1174     String mTopData;
   1175 
   1176     volatile boolean mProcessesReady = false;
   1177     volatile boolean mSystemReady = false;
   1178     volatile boolean mOnBattery = false;
   1179     volatile int mFactoryTest;
   1180 
   1181     @GuardedBy("this") boolean mBooting = false;
   1182     @GuardedBy("this") boolean mCallFinishBooting = false;
   1183     @GuardedBy("this") boolean mBootAnimationComplete = false;
   1184     @GuardedBy("this") boolean mLaunchWarningShown = false;
   1185     @GuardedBy("this") boolean mCheckedForSetup = false;
   1186 
   1187     Context mContext;
   1188 
   1189     /**
   1190      * The time at which we will allow normal application switches again,
   1191      * after a call to {@link #stopAppSwitches()}.
   1192      */
   1193     long mAppSwitchesAllowedTime;
   1194 
   1195     /**
   1196      * This is set to true after the first switch after mAppSwitchesAllowedTime
   1197      * is set; any switches after that will clear the time.
   1198      */
   1199     boolean mDidAppSwitch;
   1200 
   1201     /**
   1202      * Last time (in realtime) at which we checked for power usage.
   1203      */
   1204     long mLastPowerCheckRealtime;
   1205 
   1206     /**
   1207      * Last time (in uptime) at which we checked for power usage.
   1208      */
   1209     long mLastPowerCheckUptime;
   1210 
   1211     /**
   1212      * Set while we are wanting to sleep, to prevent any
   1213      * activities from being started/resumed.
   1214      */
   1215     private boolean mSleeping = false;
   1216 
   1217     /**
   1218      * The process state used for processes that are running the top activities.
   1219      * This changes between TOP and TOP_SLEEPING to following mSleeping.
   1220      */
   1221     int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
   1222 
   1223     /**
   1224      * Set while we are running a voice interaction.  This overrides
   1225      * sleeping while it is active.
   1226      */
   1227     private IVoiceInteractionSession mRunningVoice;
   1228 
   1229     /**
   1230      * For some direct access we need to power manager.
   1231      */
   1232     PowerManagerInternal mLocalPowerManager;
   1233 
   1234     /**
   1235      * We want to hold a wake lock while running a voice interaction session, since
   1236      * this may happen with the screen off and we need to keep the CPU running to
   1237      * be able to continue to interact with the user.
   1238      */
   1239     PowerManager.WakeLock mVoiceWakeLock;
   1240 
   1241     /**
   1242      * State of external calls telling us if the device is awake or asleep.
   1243      */
   1244     private int mWakefulness = PowerManagerInternal.WAKEFULNESS_AWAKE;
   1245 
   1246     /**
   1247      * A list of tokens that cause the top activity to be put to sleep.
   1248      * They are used by components that may hide and block interaction with underlying
   1249      * activities.
   1250      */
   1251     final ArrayList<SleepToken> mSleepTokens = new ArrayList<SleepToken>();
   1252 
   1253     static final int LOCK_SCREEN_HIDDEN = 0;
   1254     static final int LOCK_SCREEN_LEAVING = 1;
   1255     static final int LOCK_SCREEN_SHOWN = 2;
   1256     /**
   1257      * State of external call telling us if the lock screen is shown.
   1258      */
   1259     int mLockScreenShown = LOCK_SCREEN_HIDDEN;
   1260 
   1261     /**
   1262      * Set if we are shutting down the system, similar to sleeping.
   1263      */
   1264     boolean mShuttingDown = false;
   1265 
   1266     /**
   1267      * Current sequence id for oom_adj computation traversal.
   1268      */
   1269     int mAdjSeq = 0;
   1270 
   1271     /**
   1272      * Current sequence id for process LRU updating.
   1273      */
   1274     int mLruSeq = 0;
   1275 
   1276     /**
   1277      * Keep track of the non-cached/empty process we last found, to help
   1278      * determine how to distribute cached/empty processes next time.
   1279      */
   1280     int mNumNonCachedProcs = 0;
   1281 
   1282     /**
   1283      * Keep track of the number of cached hidden procs, to balance oom adj
   1284      * distribution between those and empty procs.
   1285      */
   1286     int mNumCachedHiddenProcs = 0;
   1287 
   1288     /**
   1289      * Keep track of the number of service processes we last found, to
   1290      * determine on the next iteration which should be B services.
   1291      */
   1292     int mNumServiceProcs = 0;
   1293     int mNewNumAServiceProcs = 0;
   1294     int mNewNumServiceProcs = 0;
   1295 
   1296     /**
   1297      * Allow the current computed overall memory level of the system to go down?
   1298      * This is set to false when we are killing processes for reasons other than
   1299      * memory management, so that the now smaller process list will not be taken as
   1300      * an indication that memory is tighter.
   1301      */
   1302     boolean mAllowLowerMemLevel = false;
   1303 
   1304     /**
   1305      * The last computed memory level, for holding when we are in a state that
   1306      * processes are going away for other reasons.
   1307      */
   1308     int mLastMemoryLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
   1309 
   1310     /**
   1311      * The last total number of process we have, to determine if changes actually look
   1312      * like a shrinking number of process due to lower RAM.
   1313      */
   1314     int mLastNumProcesses;
   1315 
   1316     /**
   1317      * The uptime of the last time we performed idle maintenance.
   1318      */
   1319     long mLastIdleTime = SystemClock.uptimeMillis();
   1320 
   1321     /**
   1322      * Total time spent with RAM that has been added in the past since the last idle time.
   1323      */
   1324     long mLowRamTimeSinceLastIdle = 0;
   1325 
   1326     /**
   1327      * If RAM is currently low, when that horrible situation started.
   1328      */
   1329     long mLowRamStartTime = 0;
   1330 
   1331     /**
   1332      * For reporting to battery stats the current top application.
   1333      */
   1334     private String mCurResumedPackage = null;
   1335     private int mCurResumedUid = -1;
   1336 
   1337     /**
   1338      * For reporting to battery stats the apps currently running foreground
   1339      * service.  The ProcessMap is package/uid tuples; each of these contain
   1340      * an array of the currently foreground processes.
   1341      */
   1342     final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages
   1343             = new ProcessMap<ArrayList<ProcessRecord>>();
   1344 
   1345     /**
   1346      * This is set if we had to do a delayed dexopt of an app before launching
   1347      * it, to increase the ANR timeouts in that case.
   1348      */
   1349     boolean mDidDexOpt;
   1350 
   1351     /**
   1352      * Set if the systemServer made a call to enterSafeMode.
   1353      */
   1354     boolean mSafeMode;
   1355 
   1356     /**
   1357      * If true, we are running under a test environment so will sample PSS from processes
   1358      * much more rapidly to try to collect better data when the tests are rapidly
   1359      * running through apps.
   1360      */
   1361     boolean mTestPssMode = false;
   1362 
   1363     String mDebugApp = null;
   1364     boolean mWaitForDebugger = false;
   1365     boolean mDebugTransient = false;
   1366     String mOrigDebugApp = null;
   1367     boolean mOrigWaitForDebugger = false;
   1368     boolean mAlwaysFinishActivities = false;
   1369     boolean mLenientBackgroundCheck = false;
   1370     boolean mForceResizableActivities;
   1371     boolean mSupportsMultiWindow;
   1372     boolean mSupportsFreeformWindowManagement;
   1373     boolean mSupportsPictureInPicture;
   1374     boolean mSupportsLeanbackOnly;
   1375     Rect mDefaultPinnedStackBounds;
   1376     IActivityController mController = null;
   1377     boolean mControllerIsAMonkey = false;
   1378     String mProfileApp = null;
   1379     ProcessRecord mProfileProc = null;
   1380     String mProfileFile;
   1381     ParcelFileDescriptor mProfileFd;
   1382     int mSamplingInterval = 0;
   1383     boolean mAutoStopProfiler = false;
   1384     int mProfileType = 0;
   1385     final ProcessMap<Pair<Long, String>> mMemWatchProcesses = new ProcessMap<>();
   1386     String mMemWatchDumpProcName;
   1387     String mMemWatchDumpFile;
   1388     int mMemWatchDumpPid;
   1389     int mMemWatchDumpUid;
   1390     String mTrackAllocationApp = null;
   1391     String mNativeDebuggingApp = null;
   1392 
   1393     final long[] mTmpLong = new long[2];
   1394 
   1395     static final class ProcessChangeItem {
   1396         static final int CHANGE_ACTIVITIES = 1<<0;
   1397         static final int CHANGE_PROCESS_STATE = 1<<1;
   1398         int changes;
   1399         int uid;
   1400         int pid;
   1401         int processState;
   1402         boolean foregroundActivities;
   1403     }
   1404 
   1405     final RemoteCallbackList<IProcessObserver> mProcessObservers = new RemoteCallbackList<>();
   1406     ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
   1407 
   1408     final ArrayList<ProcessChangeItem> mPendingProcessChanges = new ArrayList<>();
   1409     final ArrayList<ProcessChangeItem> mAvailProcessChanges = new ArrayList<>();
   1410 
   1411     final RemoteCallbackList<IUidObserver> mUidObservers = new RemoteCallbackList<>();
   1412     UidRecord.ChangeItem[] mActiveUidChanges = new UidRecord.ChangeItem[5];
   1413 
   1414     final ArrayList<UidRecord.ChangeItem> mPendingUidChanges = new ArrayList<>();
   1415     final ArrayList<UidRecord.ChangeItem> mAvailUidChanges = new ArrayList<>();
   1416 
   1417     /**
   1418      * Runtime CPU use collection thread.  This object's lock is used to
   1419      * perform synchronization with the thread (notifying it to run).
   1420      */
   1421     final Thread mProcessCpuThread;
   1422 
   1423     /**
   1424      * Used to collect per-process CPU use for ANRs, battery stats, etc.
   1425      * Must acquire this object's lock when accessing it.
   1426      * NOTE: this lock will be held while doing long operations (trawling
   1427      * through all processes in /proc), so it should never be acquired by
   1428      * any critical paths such as when holding the main activity manager lock.
   1429      */
   1430     final ProcessCpuTracker mProcessCpuTracker = new ProcessCpuTracker(
   1431             MONITOR_THREAD_CPU_USAGE);
   1432     final AtomicLong mLastCpuTime = new AtomicLong(0);
   1433     final AtomicBoolean mProcessCpuMutexFree = new AtomicBoolean(true);
   1434 
   1435     long mLastWriteTime = 0;
   1436 
   1437     /**
   1438      * Used to retain an update lock when the foreground activity is in
   1439      * immersive mode.
   1440      */
   1441     final UpdateLock mUpdateLock = new UpdateLock("immersive");
   1442 
   1443     /**
   1444      * Set to true after the system has finished booting.
   1445      */
   1446     boolean mBooted = false;
   1447 
   1448     int mProcessLimit = ProcessList.MAX_CACHED_APPS;
   1449     int mProcessLimitOverride = -1;
   1450 
   1451     WindowManagerService mWindowManager;
   1452     final ActivityThread mSystemThread;
   1453 
   1454     private final class AppDeathRecipient implements IBinder.DeathRecipient {
   1455         final ProcessRecord mApp;
   1456         final int mPid;
   1457         final IApplicationThread mAppThread;
   1458 
   1459         AppDeathRecipient(ProcessRecord app, int pid,
   1460                 IApplicationThread thread) {
   1461             if (DEBUG_ALL) Slog.v(
   1462                 TAG, "New death recipient " + this
   1463                 + " for thread " + thread.asBinder());
   1464             mApp = app;
   1465             mPid = pid;
   1466             mAppThread = thread;
   1467         }
   1468 
   1469         @Override
   1470         public void binderDied() {
   1471             if (DEBUG_ALL) Slog.v(
   1472                 TAG, "Death received in " + this
   1473                 + " for thread " + mAppThread.asBinder());
   1474             synchronized(ActivityManagerService.this) {
   1475                 appDiedLocked(mApp, mPid, mAppThread, true);
   1476             }
   1477         }
   1478     }
   1479 
   1480     static final int SHOW_ERROR_UI_MSG = 1;
   1481     static final int SHOW_NOT_RESPONDING_UI_MSG = 2;
   1482     static final int SHOW_FACTORY_ERROR_UI_MSG = 3;
   1483     static final int UPDATE_CONFIGURATION_MSG = 4;
   1484     static final int GC_BACKGROUND_PROCESSES_MSG = 5;
   1485     static final int WAIT_FOR_DEBUGGER_UI_MSG = 6;
   1486     static final int SERVICE_TIMEOUT_MSG = 12;
   1487     static final int UPDATE_TIME_ZONE = 13;
   1488     static final int SHOW_UID_ERROR_UI_MSG = 14;
   1489     static final int SHOW_FINGERPRINT_ERROR_UI_MSG = 15;
   1490     static final int PROC_START_TIMEOUT_MSG = 20;
   1491     static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
   1492     static final int KILL_APPLICATION_MSG = 22;
   1493     static final int FINALIZE_PENDING_INTENT_MSG = 23;
   1494     static final int POST_HEAVY_NOTIFICATION_MSG = 24;
   1495     static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
   1496     static final int SHOW_STRICT_MODE_VIOLATION_UI_MSG = 26;
   1497     static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
   1498     static final int CLEAR_DNS_CACHE_MSG = 28;
   1499     static final int UPDATE_HTTP_PROXY_MSG = 29;
   1500     static final int SHOW_COMPAT_MODE_DIALOG_UI_MSG = 30;
   1501     static final int DISPATCH_PROCESSES_CHANGED_UI_MSG = 31;
   1502     static final int DISPATCH_PROCESS_DIED_UI_MSG = 32;
   1503     static final int REPORT_MEM_USAGE_MSG = 33;
   1504     static final int REPORT_USER_SWITCH_MSG = 34;
   1505     static final int CONTINUE_USER_SWITCH_MSG = 35;
   1506     static final int USER_SWITCH_TIMEOUT_MSG = 36;
   1507     static final int IMMERSIVE_MODE_LOCK_MSG = 37;
   1508     static final int PERSIST_URI_GRANTS_MSG = 38;
   1509     static final int REQUEST_ALL_PSS_MSG = 39;
   1510     static final int START_PROFILES_MSG = 40;
   1511     static final int UPDATE_TIME = 41;
   1512     static final int SYSTEM_USER_START_MSG = 42;
   1513     static final int SYSTEM_USER_CURRENT_MSG = 43;
   1514     static final int ENTER_ANIMATION_COMPLETE_MSG = 44;
   1515     static final int FINISH_BOOTING_MSG = 45;
   1516     static final int START_USER_SWITCH_UI_MSG = 46;
   1517     static final int SEND_LOCALE_TO_MOUNT_DAEMON_MSG = 47;
   1518     static final int DISMISS_DIALOG_UI_MSG = 48;
   1519     static final int NOTIFY_TASK_STACK_CHANGE_LISTENERS_MSG = 49;
   1520     static final int NOTIFY_CLEARTEXT_NETWORK_MSG = 50;
   1521     static final int POST_DUMP_HEAP_NOTIFICATION_MSG = 51;
   1522     static final int DELETE_DUMPHEAP_MSG = 52;
   1523     static final int FOREGROUND_PROFILE_CHANGED_MSG = 53;
   1524     static final int DISPATCH_UIDS_CHANGED_UI_MSG = 54;
   1525     static final int REPORT_TIME_TRACKER_MSG = 55;
   1526     static final int REPORT_USER_SWITCH_COMPLETE_MSG = 56;
   1527     static final int SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG = 57;
   1528     static final int APP_BOOST_DEACTIVATE_MSG = 58;
   1529     static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG = 59;
   1530     static final int IDLE_UIDS_MSG = 60;
   1531     static final int SYSTEM_USER_UNLOCK_MSG = 61;
   1532     static final int LOG_STACK_STATE = 62;
   1533     static final int VR_MODE_CHANGE_MSG = 63;
   1534     static final int NOTIFY_ACTIVITY_PINNED_LISTENERS_MSG = 64;
   1535     static final int NOTIFY_PINNED_ACTIVITY_RESTART_ATTEMPT_LISTENERS_MSG = 65;
   1536     static final int NOTIFY_PINNED_STACK_ANIMATION_ENDED_LISTENERS_MSG = 66;
   1537     static final int NOTIFY_FORCED_RESIZABLE_MSG = 67;
   1538     static final int NOTIFY_ACTIVITY_DISMISSING_DOCKED_STACK_MSG = 68;
   1539     static final int VR_MODE_APPLY_IF_NEEDED_MSG = 69;
   1540     static final int SHOW_UNSUPPORTED_DISPLAY_SIZE_DIALOG_MSG = 70;
   1541 
   1542     static final int FIRST_ACTIVITY_STACK_MSG = 100;
   1543     static final int FIRST_BROADCAST_QUEUE_MSG = 200;
   1544     static final int FIRST_COMPAT_MODE_MSG = 300;
   1545     static final int FIRST_SUPERVISOR_STACK_MSG = 100;
   1546 
   1547     static ServiceThread sKillThread = null;
   1548     static KillHandler sKillHandler = null;
   1549 
   1550     CompatModeDialog mCompatModeDialog;
   1551     UnsupportedDisplaySizeDialog mUnsupportedDisplaySizeDialog;
   1552     long mLastMemUsageReportTime = 0;
   1553 
   1554     /**
   1555      * Flag whether the current user is a "monkey", i.e. whether
   1556      * the UI is driven by a UI automation tool.
   1557      */
   1558     private boolean mUserIsMonkey;
   1559 
   1560     /** Flag whether the device has a Recents UI */
   1561     boolean mHasRecents;
   1562 
   1563     /** The dimensions of the thumbnails in the Recents UI. */
   1564     int mThumbnailWidth;
   1565     int mThumbnailHeight;
   1566     float mFullscreenThumbnailScale;
   1567 
   1568     final ServiceThread mHandlerThread;
   1569     final MainHandler mHandler;
   1570     final UiHandler mUiHandler;
   1571 
   1572     PackageManagerInternal mPackageManagerInt;
   1573 
   1574     // VoiceInteraction session ID that changes for each new request except when
   1575     // being called for multiwindow assist in a single session.
   1576     private int mViSessionId = 1000;
   1577 
   1578     final class KillHandler extends Handler {
   1579         static final int KILL_PROCESS_GROUP_MSG = 4000;
   1580 
   1581         public KillHandler(Looper looper) {
   1582             super(looper, null, true);
   1583         }
   1584 
   1585         @Override
   1586         public void handleMessage(Message msg) {
   1587             switch (msg.what) {
   1588                 case KILL_PROCESS_GROUP_MSG:
   1589                 {
   1590                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "killProcessGroup");
   1591                     Process.killProcessGroup(msg.arg1 /* uid */, msg.arg2 /* pid */);
   1592                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
   1593                 }
   1594                 break;
   1595 
   1596                 default:
   1597                     super.handleMessage(msg);
   1598             }
   1599         }
   1600     }
   1601 
   1602     final class UiHandler extends Handler {
   1603         public UiHandler() {
   1604             super(com.android.server.UiThread.get().getLooper(), null, true);
   1605         }
   1606 
   1607         @Override
   1608         public void handleMessage(Message msg) {
   1609             switch (msg.what) {
   1610             case SHOW_ERROR_UI_MSG: {
   1611                 mAppErrors.handleShowAppErrorUi(msg);
   1612                 ensureBootCompleted();
   1613             } break;
   1614             case SHOW_NOT_RESPONDING_UI_MSG: {
   1615                 mAppErrors.handleShowAnrUi(msg);
   1616                 ensureBootCompleted();
   1617             } break;
   1618             case SHOW_STRICT_MODE_VIOLATION_UI_MSG: {
   1619                 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
   1620                 synchronized (ActivityManagerService.this) {
   1621                     ProcessRecord proc = (ProcessRecord) data.get("app");
   1622                     if (proc == null) {
   1623                         Slog.e(TAG, "App not found when showing strict mode dialog.");
   1624                         break;
   1625                     }
   1626                     if (proc.crashDialog != null) {
   1627                         Slog.e(TAG, "App already has strict mode dialog: " + proc);
   1628                         return;
   1629                     }
   1630                     AppErrorResult res = (AppErrorResult) data.get("result");
   1631                     if (mShowDialogs && !mSleeping && !mShuttingDown) {
   1632                         Dialog d = new StrictModeViolationDialog(mContext,
   1633                                 ActivityManagerService.this, res, proc);
   1634                         d.show();
   1635                         proc.crashDialog = d;
   1636                     } else {
   1637                         // The device is asleep, so just pretend that the user
   1638                         // saw a crash dialog and hit "force quit".
   1639                         res.set(0);
   1640                     }
   1641                 }
   1642                 ensureBootCompleted();
   1643             } break;
   1644             case SHOW_FACTORY_ERROR_UI_MSG: {
   1645                 Dialog d = new FactoryErrorDialog(
   1646                     mContext, msg.getData().getCharSequence("msg"));
   1647                 d.show();
   1648                 ensureBootCompleted();
   1649             } break;
   1650             case WAIT_FOR_DEBUGGER_UI_MSG: {
   1651                 synchronized (ActivityManagerService.this) {
   1652                     ProcessRecord app = (ProcessRecord)msg.obj;
   1653                     if (msg.arg1 != 0) {
   1654                         if (!app.waitedForDebugger) {
   1655                             Dialog d = new AppWaitingForDebuggerDialog(
   1656                                     ActivityManagerService.this,
   1657                                     mContext, app);
   1658                             app.waitDialog = d;
   1659                             app.waitedForDebugger = true;
   1660                             d.show();
   1661                         }
   1662                     } else {
   1663                         if (app.waitDialog != null) {
   1664                             app.waitDialog.dismiss();
   1665                             app.waitDialog = null;
   1666                         }
   1667                     }
   1668                 }
   1669             } break;
   1670             case SHOW_UID_ERROR_UI_MSG: {
   1671                 if (mShowDialogs) {
   1672                     AlertDialog d = new BaseErrorDialog(mContext);
   1673                     d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
   1674                     d.setCancelable(false);
   1675                     d.setTitle(mContext.getText(R.string.android_system_label));
   1676                     d.setMessage(mContext.getText(R.string.system_error_wipe_data));
   1677                     d.setButton(DialogInterface.BUTTON_POSITIVE, mContext.getText(R.string.ok),
   1678                             obtainMessage(DISMISS_DIALOG_UI_MSG, d));
   1679                     d.show();
   1680                 }
   1681             } break;
   1682             case SHOW_FINGERPRINT_ERROR_UI_MSG: {
   1683                 if (mShowDialogs) {
   1684                     AlertDialog d = new BaseErrorDialog(mContext);
   1685                     d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
   1686                     d.setCancelable(false);
   1687                     d.setTitle(mContext.getText(R.string.android_system_label));
   1688                     d.setMessage(mContext.getText(R.string.system_error_manufacturer));
   1689                     d.setButton(DialogInterface.BUTTON_POSITIVE, mContext.getText(R.string.ok),
   1690                             obtainMessage(DISMISS_DIALOG_UI_MSG, d));
   1691                     d.show();
   1692                 }
   1693             } break;
   1694             case SHOW_COMPAT_MODE_DIALOG_UI_MSG: {
   1695                 synchronized (ActivityManagerService.this) {
   1696                     ActivityRecord ar = (ActivityRecord) msg.obj;
   1697                     if (mCompatModeDialog != null) {
   1698                         if (mCompatModeDialog.mAppInfo.packageName.equals(
   1699                                 ar.info.applicationInfo.packageName)) {
   1700                             return;
   1701                         }
   1702                         mCompatModeDialog.dismiss();
   1703                         mCompatModeDialog = null;
   1704                     }
   1705                     if (ar != null && false) {
   1706                         if (mCompatModePackages.getPackageAskCompatModeLocked(
   1707                                 ar.packageName)) {
   1708                             int mode = mCompatModePackages.computeCompatModeLocked(
   1709                                     ar.info.applicationInfo);
   1710                             if (mode == ActivityManager.COMPAT_MODE_DISABLED
   1711                                     || mode == ActivityManager.COMPAT_MODE_ENABLED) {
   1712                                 mCompatModeDialog = new CompatModeDialog(
   1713                                         ActivityManagerService.this, mContext,
   1714                                         ar.info.applicationInfo);
   1715                                 mCompatModeDialog.show();
   1716                             }
   1717                         }
   1718                     }
   1719                 }
   1720                 break;
   1721             }
   1722             case SHOW_UNSUPPORTED_DISPLAY_SIZE_DIALOG_MSG: {
   1723                 synchronized (ActivityManagerService.this) {
   1724                     final ActivityRecord ar = (ActivityRecord) msg.obj;
   1725                     if (mUnsupportedDisplaySizeDialog != null) {
   1726                         mUnsupportedDisplaySizeDialog.dismiss();
   1727                         mUnsupportedDisplaySizeDialog = null;
   1728                     }
   1729                     if (ar != null && mCompatModePackages.getPackageNotifyUnsupportedZoomLocked(
   1730                             ar.packageName)) {
   1731                         mUnsupportedDisplaySizeDialog = new UnsupportedDisplaySizeDialog(
   1732                                 ActivityManagerService.this, mContext, ar.info.applicationInfo);
   1733                         mUnsupportedDisplaySizeDialog.show();
   1734                     }
   1735                 }
   1736                 break;
   1737             }
   1738             case START_USER_SWITCH_UI_MSG: {
   1739                 mUserController.showUserSwitchDialog((Pair<UserInfo, UserInfo>) msg.obj);
   1740                 break;
   1741             }
   1742             case DISMISS_DIALOG_UI_MSG: {
   1743                 final Dialog d = (Dialog) msg.obj;
   1744                 d.dismiss();
   1745                 break;
   1746             }
   1747             case DISPATCH_PROCESSES_CHANGED_UI_MSG: {
   1748                 dispatchProcessesChanged();
   1749                 break;
   1750             }
   1751             case DISPATCH_PROCESS_DIED_UI_MSG: {
   1752                 final int pid = msg.arg1;
   1753                 final int uid = msg.arg2;
   1754                 dispatchProcessDied(pid, uid);
   1755                 break;
   1756             }
   1757             case DISPATCH_UIDS_CHANGED_UI_MSG: {
   1758                 dispatchUidsChanged();
   1759             } break;
   1760             }
   1761         }
   1762     }
   1763 
   1764     final class MainHandler extends Handler {
   1765         public MainHandler(Looper looper) {
   1766             super(looper, null, true);
   1767         }
   1768 
   1769         @Override
   1770         public void handleMessage(Message msg) {
   1771             switch (msg.what) {
   1772             case UPDATE_CONFIGURATION_MSG: {
   1773                 final ContentResolver resolver = mContext.getContentResolver();
   1774                 Settings.System.putConfigurationForUser(resolver, (Configuration) msg.obj,
   1775                         msg.arg1);
   1776             } break;
   1777             case GC_BACKGROUND_PROCESSES_MSG: {
   1778                 synchronized (ActivityManagerService.this) {
   1779                     performAppGcsIfAppropriateLocked();
   1780                 }
   1781             } break;
   1782             case SERVICE_TIMEOUT_MSG: {
   1783                 if (mDidDexOpt) {
   1784                     mDidDexOpt = false;
   1785                     Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
   1786                     nmsg.obj = msg.obj;
   1787                     mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
   1788                     return;
   1789                 }
   1790                 mServices.serviceTimeout((ProcessRecord)msg.obj);
   1791             } break;
   1792             case UPDATE_TIME_ZONE: {
   1793                 synchronized (ActivityManagerService.this) {
   1794                     for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
   1795                         ProcessRecord r = mLruProcesses.get(i);
   1796                         if (r.thread != null) {
   1797                             try {
   1798                                 r.thread.updateTimeZone();
   1799                             } catch (RemoteException ex) {
   1800                                 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
   1801                             }
   1802                         }
   1803                     }
   1804                 }
   1805             } break;
   1806             case CLEAR_DNS_CACHE_MSG: {
   1807                 synchronized (ActivityManagerService.this) {
   1808                     for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
   1809                         ProcessRecord r = mLruProcesses.get(i);
   1810                         if (r.thread != null) {
   1811                             try {
   1812                                 r.thread.clearDnsCache();
   1813                             } catch (RemoteException ex) {
   1814                                 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
   1815                             }
   1816                         }
   1817                     }
   1818                 }
   1819             } break;
   1820             case UPDATE_HTTP_PROXY_MSG: {
   1821                 ProxyInfo proxy = (ProxyInfo)msg.obj;
   1822                 String host = "";
   1823                 String port = "";
   1824                 String exclList = "";
   1825                 Uri pacFileUrl = Uri.EMPTY;
   1826                 if (proxy != null) {
   1827                     host = proxy.getHost();
   1828                     port = Integer.toString(proxy.getPort());
   1829                     exclList = proxy.getExclusionListAsString();
   1830                     pacFileUrl = proxy.getPacFileUrl();
   1831                 }
   1832                 synchronized (ActivityManagerService.this) {
   1833                     for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
   1834                         ProcessRecord r = mLruProcesses.get(i);
   1835                         if (r.thread != null) {
   1836                             try {
   1837                                 r.thread.setHttpProxy(host, port, exclList, pacFileUrl);
   1838                             } catch (RemoteException ex) {
   1839                                 Slog.w(TAG, "Failed to update http proxy for: " +
   1840                                         r.info.processName);
   1841                             }
   1842                         }
   1843                     }
   1844                 }
   1845             } break;
   1846             case PROC_START_TIMEOUT_MSG: {
   1847                 if (mDidDexOpt) {
   1848                     mDidDexOpt = false;
   1849                     Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
   1850                     nmsg.obj = msg.obj;
   1851                     mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
   1852                     return;
   1853                 }
   1854                 ProcessRecord app = (ProcessRecord)msg.obj;
   1855                 synchronized (ActivityManagerService.this) {
   1856                     processStartTimedOutLocked(app);
   1857                 }
   1858             } break;
   1859             case CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG: {
   1860                 ProcessRecord app = (ProcessRecord)msg.obj;
   1861                 synchronized (ActivityManagerService.this) {
   1862                     processContentProviderPublishTimedOutLocked(app);
   1863                 }
   1864             } break;
   1865             case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
   1866                 synchronized (ActivityManagerService.this) {
   1867                     mActivityStarter.doPendingActivityLaunchesLocked(true);
   1868                 }
   1869             } break;
   1870             case KILL_APPLICATION_MSG: {
   1871                 synchronized (ActivityManagerService.this) {
   1872                     final int appId = msg.arg1;
   1873                     final int userId = msg.arg2;
   1874                     Bundle bundle = (Bundle)msg.obj;
   1875                     String pkg = bundle.getString("pkg");
   1876                     String reason = bundle.getString("reason");
   1877                     forceStopPackageLocked(pkg, appId, false, false, true, false,
   1878                             false, userId, reason);
   1879                 }
   1880             } break;
   1881             case FINALIZE_PENDING_INTENT_MSG: {
   1882                 ((PendingIntentRecord)msg.obj).completeFinalize();
   1883             } break;
   1884             case POST_HEAVY_NOTIFICATION_MSG: {
   1885                 INotificationManager inm = NotificationManager.getService();
   1886                 if (inm == null) {
   1887                     return;
   1888                 }
   1889 
   1890                 ActivityRecord root = (ActivityRecord)msg.obj;
   1891                 ProcessRecord process = root.app;
   1892                 if (process == null) {
   1893                     return;
   1894                 }
   1895 
   1896                 try {
   1897                     Context context = mContext.createPackageContext(process.info.packageName, 0);
   1898                     String text = mContext.getString(R.string.heavy_weight_notification,
   1899                             context.getApplicationInfo().loadLabel(context.getPackageManager()));
   1900                     Notification notification = new Notification.Builder(context)
   1901                             .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
   1902                             .setWhen(0)
   1903                             .setOngoing(true)
   1904                             .setTicker(text)
   1905                             .setColor(mContext.getColor(
   1906                                     com.android.internal.R.color.system_notification_accent_color))
   1907                             .setContentTitle(text)
   1908                             .setContentText(
   1909                                     mContext.getText(R.string.heavy_weight_notification_detail))
   1910                             .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
   1911                                     root.intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
   1912                                     new UserHandle(root.userId)))
   1913                             .build();
   1914                     try {
   1915                         int[] outId = new int[1];
   1916                         inm.enqueueNotificationWithTag("android", "android", null,
   1917                                 R.string.heavy_weight_notification,
   1918                                 notification, outId, root.userId);
   1919                     } catch (RuntimeException e) {
   1920                         Slog.w(ActivityManagerService.TAG,
   1921                                 "Error showing notification for heavy-weight app", e);
   1922                     } catch (RemoteException e) {
   1923                     }
   1924                 } catch (NameNotFoundException e) {
   1925                     Slog.w(TAG, "Unable to create context for heavy notification", e);
   1926                 }
   1927             } break;
   1928             case CANCEL_HEAVY_NOTIFICATION_MSG: {
   1929                 INotificationManager inm = NotificationManager.getService();
   1930                 if (inm == null) {
   1931                     return;
   1932                 }
   1933                 try {
   1934                     inm.cancelNotificationWithTag("android", null,
   1935                             R.string.heavy_weight_notification,  msg.arg1);
   1936                 } catch (RuntimeException e) {
   1937                     Slog.w(ActivityManagerService.TAG,
   1938                             "Error canceling notification for service", e);
   1939                 } catch (RemoteException e) {
   1940                 }
   1941             } break;
   1942             case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
   1943                 synchronized (ActivityManagerService.this) {
   1944                     checkExcessivePowerUsageLocked(true);
   1945                     removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
   1946                     Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
   1947                     sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
   1948                 }
   1949             } break;
   1950             case REPORT_MEM_USAGE_MSG: {
   1951                 final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>)msg.obj;
   1952                 Thread thread = new Thread() {
   1953                     @Override public void run() {
   1954                         reportMemUsage(memInfos);
   1955                     }
   1956                 };
   1957                 thread.start();
   1958                 break;
   1959             }
   1960             case REPORT_USER_SWITCH_MSG: {
   1961                 mUserController.dispatchUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2);
   1962                 break;
   1963             }
   1964             case CONTINUE_USER_SWITCH_MSG: {
   1965                 mUserController.continueUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2);
   1966                 break;
   1967             }
   1968             case USER_SWITCH_TIMEOUT_MSG: {
   1969                 mUserController.timeoutUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2);
   1970                 break;
   1971             }
   1972             case IMMERSIVE_MODE_LOCK_MSG: {
   1973                 final boolean nextState = (msg.arg1 != 0);
   1974                 if (mUpdateLock.isHeld() != nextState) {
   1975                     if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
   1976                             "Applying new update lock state '" + nextState
   1977                             + "' for " + (ActivityRecord)msg.obj);
   1978                     if (nextState) {
   1979                         mUpdateLock.acquire();
   1980                     } else {
   1981                         mUpdateLock.release();
   1982                     }
   1983                 }
   1984                 break;
   1985             }
   1986             case PERSIST_URI_GRANTS_MSG: {
   1987                 writeGrantedUriPermissions();
   1988                 break;
   1989             }
   1990             case REQUEST_ALL_PSS_MSG: {
   1991                 synchronized (ActivityManagerService.this) {
   1992                     requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false);
   1993                 }
   1994                 break;
   1995             }
   1996             case START_PROFILES_MSG: {
   1997                 synchronized (ActivityManagerService.this) {
   1998                     mUserController.startProfilesLocked();
   1999                 }
   2000                 break;
   2001             }
   2002             case UPDATE_TIME: {
   2003                 synchronized (ActivityManagerService.this) {
   2004                     for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
   2005                         ProcessRecord r = mLruProcesses.get(i);
   2006                         if (r.thread != null) {
   2007                             try {
   2008                                 r.thread.updateTimePrefs(msg.arg1 == 0 ? false : true);
   2009                             } catch (RemoteException ex) {
   2010                                 Slog.w(TAG, "Failed to update preferences for: " + r.info.processName);
   2011                             }
   2012                         }
   2013                     }
   2014                 }
   2015                 break;
   2016             }
   2017             case SYSTEM_USER_START_MSG: {
   2018                 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
   2019                         Integer.toString(msg.arg1), msg.arg1);
   2020                 mSystemServiceManager.startUser(msg.arg1);
   2021                 break;
   2022             }
   2023             case SYSTEM_USER_UNLOCK_MSG: {
   2024                 final int userId = msg.arg1;
   2025                 mSystemServiceManager.unlockUser(userId);
   2026                 synchronized (ActivityManagerService.this) {
   2027                     mRecentTasks.loadUserRecentsLocked(userId);
   2028                 }
   2029                 if (userId == UserHandle.USER_SYSTEM) {
   2030                     startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
   2031                 }
   2032                 installEncryptionUnawareProviders(userId);
   2033                 mUserController.finishUserUnlocked((UserState) msg.obj);
   2034                 break;
   2035             }
   2036             case SYSTEM_USER_CURRENT_MSG: {
   2037                 mBatteryStatsService.noteEvent(
   2038                         BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_FINISH,
   2039                         Integer.toString(msg.arg2), msg.arg2);
   2040                 mBatteryStatsService.noteEvent(
   2041                         BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
   2042                         Integer.toString(msg.arg1), msg.arg1);
   2043                 mSystemServiceManager.switchUser(msg.arg1);
   2044                 break;
   2045             }
   2046             case ENTER_ANIMATION_COMPLETE_MSG: {
   2047                 synchronized (ActivityManagerService.this) {
   2048                     ActivityRecord r = ActivityRecord.forTokenLocked((IBinder) msg.obj);
   2049                     if (r != null && r.app != null && r.app.thread != null) {
   2050                         try {
   2051                             r.app.thread.scheduleEnterAnimationComplete(r.appToken);
   2052                         } catch (RemoteException e) {
   2053                         }
   2054                     }
   2055                 }
   2056                 break;
   2057             }
   2058             case FINISH_BOOTING_MSG: {
   2059                 if (msg.arg1 != 0) {
   2060                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "FinishBooting");
   2061                     finishBooting();
   2062                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
   2063                 }
   2064                 if (msg.arg2 != 0) {
   2065                     enableScreenAfterBoot();
   2066                 }
   2067                 break;
   2068             }
   2069             case SEND_LOCALE_TO_MOUNT_DAEMON_MSG: {
   2070                 try {
   2071                     Locale l = (Locale) msg.obj;
   2072                     IBinder service = ServiceManager.getService("mount");
   2073                     IMountService mountService = IMountService.Stub.asInterface(service);
   2074                     Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
   2075                     mountService.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
   2076                 } catch (RemoteException e) {
   2077                     Log.e(TAG, "Error storing locale for decryption UI", e);
   2078                 }
   2079                 break;
   2080             }
   2081             case NOTIFY_TASK_STACK_CHANGE_LISTENERS_MSG: {
   2082                 synchronized (ActivityManagerService.this) {
   2083                     for (int i = mTaskStackListeners.beginBroadcast() - 1; i >= 0; i--) {
   2084                         try {
   2085                             // Make a one-way callback to the listener
   2086                             mTaskStackListeners.getBroadcastItem(i).onTaskStackChanged();
   2087                         } catch (RemoteException e){
   2088                             // Handled by the RemoteCallbackList
   2089                         }
   2090                     }
   2091                     mTaskStackListeners.finishBroadcast();
   2092                 }
   2093                 break;
   2094             }
   2095             case NOTIFY_ACTIVITY_PINNED_LISTENERS_MSG: {
   2096                 synchronized (ActivityManagerService.this) {
   2097                     for (int i = mTaskStackListeners.beginBroadcast() - 1; i >= 0; i--) {
   2098                         try {
   2099                             // Make a one-way callback to the listener
   2100                             mTaskStackListeners.getBroadcastItem(i).onActivityPinned();
   2101                         } catch (RemoteException e){
   2102                             // Handled by the RemoteCallbackList
   2103                         }
   2104                     }
   2105                     mTaskStackListeners.finishBroadcast();
   2106                 }
   2107                 break;
   2108             }
   2109             case NOTIFY_PINNED_ACTIVITY_RESTART_ATTEMPT_LISTENERS_MSG: {
   2110                 synchronized (ActivityManagerService.this) {
   2111                     for (int i = mTaskStackListeners.beginBroadcast() - 1; i >= 0; i--) {
   2112                         try {
   2113                             // Make a one-way callback to the listener
   2114                             mTaskStackListeners.getBroadcastItem(i).onPinnedActivityRestartAttempt();
   2115                         } catch (RemoteException e){
   2116                             // Handled by the RemoteCallbackList
   2117                         }
   2118                     }
   2119                     mTaskStackListeners.finishBroadcast();
   2120                 }
   2121                 break;
   2122             }
   2123             case NOTIFY_PINNED_STACK_ANIMATION_ENDED_LISTENERS_MSG: {
   2124                 synchronized (ActivityManagerService.this) {
   2125                     for (int i = mTaskStackListeners.beginBroadcast() - 1; i >= 0; i--) {
   2126                         try {
   2127                             // Make a one-way callback to the listener
   2128                             mTaskStackListeners.getBroadcastItem(i).onPinnedStackAnimationEnded();
   2129                         } catch (RemoteException e){
   2130                             // Handled by the RemoteCallbackList
   2131                         }
   2132                     }
   2133                     mTaskStackListeners.finishBroadcast();
   2134                 }
   2135                 break;
   2136             }
   2137             case NOTIFY_FORCED_RESIZABLE_MSG: {
   2138                 synchronized (ActivityManagerService.this) {
   2139                     for (int i = mTaskStackListeners.beginBroadcast() - 1; i >= 0; i--) {
   2140                         try {
   2141                             // Make a one-way callback to the listener
   2142                             mTaskStackListeners.getBroadcastItem(i).onActivityForcedResizable(
   2143                                     (String) msg.obj, msg.arg1);
   2144                         } catch (RemoteException e){
   2145                             // Handled by the RemoteCallbackList
   2146                         }
   2147                     }
   2148                     mTaskStackListeners.finishBroadcast();
   2149                 }
   2150                 break;
   2151             }
   2152                 case NOTIFY_ACTIVITY_DISMISSING_DOCKED_STACK_MSG: {
   2153                     synchronized (ActivityManagerService.this) {
   2154                         for (int i = mTaskStackListeners.beginBroadcast() - 1; i >= 0; i--) {
   2155                             try {
   2156                                 // Make a one-way callback to the listener
   2157                                 mTaskStackListeners.getBroadcastItem(i)
   2158                                         .onActivityDismissingDockedStack();
   2159                             } catch (RemoteException e){
   2160                                 // Handled by the RemoteCallbackList
   2161                             }
   2162                         }
   2163                         mTaskStackListeners.finishBroadcast();
   2164                     }
   2165                     break;
   2166                 }
   2167             case NOTIFY_CLEARTEXT_NETWORK_MSG: {
   2168                 final int uid = msg.arg1;
   2169                 final byte[] firstPacket = (byte[]) msg.obj;
   2170 
   2171                 synchronized (mPidsSelfLocked) {
   2172                     for (int i = 0; i < mPidsSelfLocked.size(); i++) {
   2173                         final ProcessRecord p = mPidsSelfLocked.valueAt(i);
   2174                         if (p.uid == uid) {
   2175                             try {
   2176                                 p.thread.notifyCleartextNetwork(firstPacket);
   2177                             } catch (RemoteException ignored) {
   2178                             }
   2179                         }
   2180                     }
   2181                 }
   2182                 break;
   2183             }
   2184             case POST_DUMP_HEAP_NOTIFICATION_MSG: {
   2185                 final String procName;
   2186                 final int uid;
   2187                 final long memLimit;
   2188                 final String reportPackage;
   2189                 synchronized (ActivityManagerService.this) {
   2190                     procName = mMemWatchDumpProcName;
   2191                     uid = mMemWatchDumpUid;
   2192                     Pair<Long, String> val = mMemWatchProcesses.get(procName, uid);
   2193                     if (val == null) {
   2194                         val = mMemWatchProcesses.get(procName, 0);
   2195                     }
   2196                     if (val != null) {
   2197                         memLimit = val.first;
   2198                         reportPackage = val.second;
   2199                     } else {
   2200                         memLimit = 0;
   2201                         reportPackage = null;
   2202                     }
   2203                 }
   2204                 if (procName == null) {
   2205                     return;
   2206                 }
   2207 
   2208                 if (DEBUG_PSS) Slog.d(TAG_PSS,
   2209                         "Showing dump heap notification from " + procName + "/" + uid);
   2210 
   2211                 INotificationManager inm = NotificationManager.getService();
   2212                 if (inm == null) {
   2213                     return;
   2214                 }
   2215 
   2216                 String text = mContext.getString(R.string.dump_heap_notification, procName);
   2217 
   2218 
   2219                 Intent deleteIntent = new Intent();
   2220                 deleteIntent.setAction(DumpHeapActivity.ACTION_DELETE_DUMPHEAP);
   2221                 Intent intent = new Intent();
   2222                 intent.setClassName("android", DumpHeapActivity.class.getName());
   2223                 intent.putExtra(DumpHeapActivity.KEY_PROCESS, procName);
   2224                 intent.putExtra(DumpHeapActivity.KEY_SIZE, memLimit);
   2225                 if (reportPackage != null) {
   2226                     intent.putExtra(DumpHeapActivity.KEY_DIRECT_LAUNCH, reportPackage);
   2227                 }
   2228                 int userId = UserHandle.getUserId(uid);
   2229                 Notification notification = new Notification.Builder(mContext)
   2230                         .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
   2231                         .setWhen(0)
   2232                         .setOngoing(true)
   2233                         .setAutoCancel(true)
   2234                         .setTicker(text)
   2235                         .setColor(mContext.getColor(
   2236                                 com.android.internal.R.color.system_notification_accent_color))
   2237                         .setContentTitle(text)
   2238                         .setContentText(
   2239                                 mContext.getText(R.string.dump_heap_notification_detail))
   2240                         .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
   2241                                 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
   2242                                 new UserHandle(userId)))
   2243                         .setDeleteIntent(PendingIntent.getBroadcastAsUser(mContext, 0,
   2244                                 deleteIntent, 0, UserHandle.SYSTEM))
   2245                         .build();
   2246 
   2247                 try {
   2248                     int[] outId = new int[1];
   2249                     inm.enqueueNotificationWithTag("android", "android", null,
   2250                             R.string.dump_heap_notification,
   2251                             notification, outId, userId);
   2252                 } catch (RuntimeException e) {
   2253                     Slog.w(ActivityManagerService.TAG,
   2254                             "Error showing notification for dump heap", e);
   2255                 } catch (RemoteException e) {
   2256                 }
   2257             } break;
   2258             case DELETE_DUMPHEAP_MSG: {
   2259                 revokeUriPermission(ActivityThread.currentActivityThread().getApplicationThread(),
   2260                         DumpHeapActivity.JAVA_URI,
   2261                         Intent.FLAG_GRANT_READ_URI_PERMISSION
   2262                                 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
   2263                         UserHandle.myUserId());
   2264                 synchronized (ActivityManagerService.this) {
   2265                     mMemWatchDumpFile = null;
   2266                     mMemWatchDumpProcName = null;
   2267                     mMemWatchDumpPid = -1;
   2268                     mMemWatchDumpUid = -1;
   2269                 }
   2270             } break;
   2271             case FOREGROUND_PROFILE_CHANGED_MSG: {
   2272                 mUserController.dispatchForegroundProfileChanged(msg.arg1);
   2273             } break;
   2274             case REPORT_TIME_TRACKER_MSG: {
   2275                 AppTimeTracker tracker = (AppTimeTracker)msg.obj;
   2276                 tracker.deliverResult(mContext);
   2277             } break;
   2278             case REPORT_USER_SWITCH_COMPLETE_MSG: {
   2279                 mUserController.dispatchUserSwitchComplete(msg.arg1);
   2280             } break;
   2281             case SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG: {
   2282                 IUiAutomationConnection connection = (IUiAutomationConnection) msg.obj;
   2283                 try {
   2284                     connection.shutdown();
   2285                 } catch (RemoteException e) {
   2286                     Slog.w(TAG, "Error shutting down UiAutomationConnection");
   2287                 }
   2288                 // Only a UiAutomation can set this flag and now that
   2289                 // it is finished we make sure it is reset to its default.
   2290                 mUserIsMonkey = false;
   2291             } break;
   2292             case APP_BOOST_DEACTIVATE_MSG: {
   2293                 synchronized(ActivityManagerService.this) {
   2294                     if (mIsBoosted) {
   2295                         if (mBoostStartTime < (SystemClock.uptimeMillis() - APP_BOOST_TIMEOUT)) {
   2296                             nativeMigrateFromBoost();
   2297                             mIsBoosted = false;
   2298                             mBoostStartTime = 0;
   2299                         } else {
   2300                             Message newmsg = mHandler.obtainMessage(APP_BOOST_DEACTIVATE_MSG);
   2301                             mHandler.sendMessageDelayed(newmsg, APP_BOOST_TIMEOUT);
   2302                         }
   2303                     }
   2304                 }
   2305             } break;
   2306             case IDLE_UIDS_MSG: {
   2307                 idleUids();
   2308             } break;
   2309             case LOG_STACK_STATE: {
   2310                 synchronized (ActivityManagerService.this) {
   2311                     mStackSupervisor.logStackState();
   2312                 }
   2313             } break;
   2314             case VR_MODE_CHANGE_MSG: {
   2315                 VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
   2316                 final ActivityRecord r = (ActivityRecord) msg.obj;
   2317                 boolean vrMode;
   2318                 ComponentName requestedPackage;
   2319                 ComponentName callingPackage;
   2320                 int userId;
   2321                 synchronized (ActivityManagerService.this) {
   2322                     vrMode = r.requestedVrComponent != null;
   2323                     requestedPackage = r.requestedVrComponent;
   2324                     userId = r.userId;
   2325                     callingPackage = r.info.getComponentName();
   2326                     if (mInVrMode != vrMode) {
   2327                         mInVrMode = vrMode;
   2328                         mShowDialogs = shouldShowDialogs(mConfiguration, mInVrMode);
   2329                         if (r.app != null) {
   2330                             ProcessRecord proc = r.app;
   2331                             if (proc.vrThreadTid > 0) {
   2332                                 if (proc.curSchedGroup == ProcessList.SCHED_GROUP_TOP_APP) {
   2333                                     try {
   2334                                         if (mInVrMode == true) {
   2335                                             Process.setThreadScheduler(proc.vrThreadTid,
   2336                                                 Process.SCHED_FIFO | Process.SCHED_RESET_ON_FORK, 1);
   2337                                         } else {
   2338                                             Process.setThreadScheduler(proc.vrThreadTid,
   2339                                                 Process.SCHED_OTHER, 0);
   2340                                         }
   2341                                     } catch (IllegalArgumentException e) {
   2342                                         Slog.w(TAG, "Failed to set scheduling policy, thread does"
   2343                                                 + " not exist:\n" + e);
   2344                                     }
   2345                                 }
   2346                             }
   2347                         }
   2348                     }
   2349                 }
   2350                 vrService.setVrMode(vrMode, requestedPackage, userId, callingPackage);
   2351             } break;
   2352             case VR_MODE_APPLY_IF_NEEDED_MSG: {
   2353                 final ActivityRecord r = (ActivityRecord) msg.obj;
   2354                 final boolean needsVrMode = r != null && r.requestedVrComponent != null;
   2355                 if (needsVrMode) {
   2356                     applyVrMode(msg.arg1 == 1, r.requestedVrComponent, r.userId,
   2357                             r.info.getComponentName(), false);
   2358                 }
   2359             } break;
   2360             }
   2361         }
   2362     };
   2363 
   2364     static final int COLLECT_PSS_BG_MSG = 1;
   2365 
   2366     final Handler mBgHandler = new Handler(BackgroundThread.getHandler().getLooper()) {
   2367         @Override
   2368         public void handleMessage(Message msg) {
   2369             switch (msg.what) {
   2370             case COLLECT_PSS_BG_MSG: {
   2371                 long start = SystemClock.uptimeMillis();
   2372                 MemInfoReader memInfo = null;
   2373                 synchronized (ActivityManagerService.this) {
   2374                     if (mFullPssPending) {
   2375                         mFullPssPending = false;
   2376                         memInfo = new MemInfoReader();
   2377                     }
   2378                 }
   2379                 if (memInfo != null) {
   2380                     updateCpuStatsNow();
   2381                     long nativeTotalPss = 0;
   2382                     final List<ProcessCpuTracker.Stats> stats;
   2383                     synchronized (mProcessCpuTracker) {
   2384                         stats = mProcessCpuTracker.getStats( (st)-> {
   2385                             return st.vsize > 0 && st.uid < Process.FIRST_APPLICATION_UID;
   2386                         });
   2387                     }
   2388                     final int N = stats.size();
   2389                     for (int j = 0; j < N; j++) {
   2390                         synchronized (mPidsSelfLocked) {
   2391                             if (mPidsSelfLocked.indexOfKey(stats.get(j).pid) >= 0) {
   2392                                 // This is one of our own processes; skip it.
   2393                                 continue;
   2394                             }
   2395                         }
   2396                         nativeTotalPss += Debug.getPss(stats.get(j).pid, null, null);
   2397                     }
   2398                     memInfo.readMemInfo();
   2399                     synchronized (ActivityManagerService.this) {
   2400                         if (DEBUG_PSS) Slog.d(TAG_PSS, "Collected native and kernel memory in "
   2401                                 + (SystemClock.uptimeMillis()-start) + "ms");
   2402                         final long cachedKb = memInfo.getCachedSizeKb();
   2403                         final long freeKb = memInfo.getFreeSizeKb();
   2404                         final long zramKb = memInfo.getZramTotalSizeKb();
   2405                         final long kernelKb = memInfo.getKernelUsedSizeKb();
   2406                         EventLogTags.writeAmMeminfo(cachedKb*1024, freeKb*1024, zramKb*1024,
   2407                                 kernelKb*1024, nativeTotalPss*1024);
   2408                         mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb,
   2409                                 nativeTotalPss);
   2410                     }
   2411                 }
   2412 
   2413                 int num = 0;
   2414                 long[] tmp = new long[2];
   2415                 do {
   2416                     ProcessRecord proc;
   2417                     int procState;
   2418                     int pid;
   2419                     long lastPssTime;
   2420                     synchronized (ActivityManagerService.this) {
   2421                         if (mPendingPssProcesses.size() <= 0) {
   2422                             if (mTestPssMode || DEBUG_PSS) Slog.d(TAG_PSS,
   2423                                     "Collected PSS of " + num + " processes in "
   2424                                     + (SystemClock.uptimeMillis() - start) + "ms");
   2425                             mPendingPssProcesses.clear();
   2426                             return;
   2427                         }
   2428                         proc = mPendingPssProcesses.remove(0);
   2429                         procState = proc.pssProcState;
   2430                         lastPssTime = proc.lastPssTime;
   2431                         if (proc.thread != null && procState == proc.setProcState
   2432                                 && (lastPssTime+ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE)
   2433                                         < SystemClock.uptimeMillis()) {
   2434                             pid = proc.pid;
   2435                         } else {
   2436                             proc = null;
   2437                             pid = 0;
   2438                         }
   2439                     }
   2440                     if (proc != null) {
   2441                         long pss = Debug.getPss(pid, tmp, null);
   2442                         synchronized (ActivityManagerService.this) {
   2443                             if (pss != 0 && proc.thread != null && proc.setProcState == procState
   2444                                     && proc.pid == pid && proc.lastPssTime == lastPssTime) {
   2445                                 num++;
   2446                                 recordPssSampleLocked(proc, procState, pss, tmp[0], tmp[1],
   2447                                         SystemClock.uptimeMillis());
   2448                             }
   2449                         }
   2450                     }
   2451                 } while (true);
   2452             }
   2453             }
   2454         }
   2455     };
   2456 
   2457     public void setSystemProcess() {
   2458         try {
   2459             ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
   2460             ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
   2461             ServiceManager.addService("meminfo", new MemBinder(this));
   2462             ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
   2463             ServiceManager.addService("dbinfo", new DbBinder(this));
   2464             if (MONITOR_CPU_USAGE) {
   2465                 ServiceManager.addService("cpuinfo", new CpuBinder(this));
   2466             }
   2467             ServiceManager.addService("permission", new PermissionController(this));
   2468             ServiceManager.addService("processinfo", new ProcessInfoService(this));
   2469 
   2470             ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
   2471                     "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
   2472             mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
   2473 
   2474             synchronized (this) {
   2475                 ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
   2476                 app.persistent = true;
   2477                 app.pid = MY_PID;
   2478                 app.maxAdj = ProcessList.SYSTEM_ADJ;
   2479                 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
   2480                 synchronized (mPidsSelfLocked) {
   2481                     mPidsSelfLocked.put(app.pid, app);
   2482                 }
   2483                 updateLruProcessLocked(app, false, null);
   2484                 updateOomAdjLocked();
   2485             }
   2486         } catch (PackageManager.NameNotFoundException e) {
   2487             throw new RuntimeException(
   2488                     "Unable to find android system package", e);
   2489         }
   2490     }
   2491 
   2492     public void setWindowManager(WindowManagerService wm) {
   2493         mWindowManager = wm;
   2494         mStackSupervisor.setWindowManager(wm);
   2495         mActivityStarter.setWindowManager(wm);
   2496     }
   2497 
   2498     public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
   2499         mUsageStatsService = usageStatsManager;
   2500     }
   2501 
   2502     public void startObservingNativeCrashes() {
   2503         final NativeCrashListener ncl = new NativeCrashListener(this);
   2504         ncl.start();
   2505     }
   2506 
   2507     public IAppOpsService getAppOpsService() {
   2508         return mAppOpsService;
   2509     }
   2510 
   2511     static class MemBinder extends Binder {
   2512         ActivityManagerService mActivityManagerService;
   2513         MemBinder(ActivityManagerService activityManagerService) {
   2514             mActivityManagerService = activityManagerService;
   2515         }
   2516 
   2517         @Override
   2518         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   2519             if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
   2520                     != PackageManager.PERMISSION_GRANTED) {
   2521                 pw.println("Permission Denial: can't dump meminfo from from pid="
   2522                         + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
   2523                         + " without permission " + android.Manifest.permission.DUMP);
   2524                 return;
   2525             }
   2526 
   2527             mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, "  ", args, false, null);
   2528         }
   2529     }
   2530 
   2531     static class GraphicsBinder extends Binder {
   2532         ActivityManagerService mActivityManagerService;
   2533         GraphicsBinder(ActivityManagerService activityManagerService) {
   2534             mActivityManagerService = activityManagerService;
   2535         }
   2536 
   2537         @Override
   2538         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   2539             if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
   2540                     != PackageManager.PERMISSION_GRANTED) {
   2541                 pw.println("Permission Denial: can't dump gfxinfo from from pid="
   2542                         + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
   2543                         + " without permission " + android.Manifest.permission.DUMP);
   2544                 return;
   2545             }
   2546 
   2547             mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
   2548         }
   2549     }
   2550 
   2551     static class DbBinder extends Binder {
   2552         ActivityManagerService mActivityManagerService;
   2553         DbBinder(ActivityManagerService activityManagerService) {
   2554             mActivityManagerService = activityManagerService;
   2555         }
   2556 
   2557         @Override
   2558         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   2559             if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
   2560                     != PackageManager.PERMISSION_GRANTED) {
   2561                 pw.println("Permission Denial: can't dump dbinfo from from pid="
   2562                         + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
   2563                         + " without permission " + android.Manifest.permission.DUMP);
   2564                 return;
   2565             }
   2566 
   2567             mActivityManagerService.dumpDbInfo(fd, pw, args);
   2568         }
   2569     }
   2570 
   2571     static class CpuBinder extends Binder {
   2572         ActivityManagerService mActivityManagerService;
   2573         CpuBinder(ActivityManagerService activityManagerService) {
   2574             mActivityManagerService = activityManagerService;
   2575         }
   2576 
   2577         @Override
   2578         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   2579             if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
   2580                     != PackageManager.PERMISSION_GRANTED) {
   2581                 pw.println("Permission Denial: can't dump cpuinfo from from pid="
   2582                         + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
   2583                         + " without permission " + android.Manifest.permission.DUMP);
   2584                 return;
   2585             }
   2586 
   2587             synchronized (mActivityManagerService.mProcessCpuTracker) {
   2588                 pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentLoad());
   2589                 pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentState(
   2590                         SystemClock.uptimeMillis()));
   2591             }
   2592         }
   2593     }
   2594 
   2595     public static final class Lifecycle extends SystemService {
   2596         private final ActivityManagerService mService;
   2597 
   2598         public Lifecycle(Context context) {
   2599             super(context);
   2600             mService = new ActivityManagerService(context);
   2601         }
   2602 
   2603         @Override
   2604         public void onStart() {
   2605             mService.start();
   2606         }
   2607 
   2608         public ActivityManagerService getService() {
   2609             return mService;
   2610         }
   2611     }
   2612 
   2613     // Note: This method is invoked on the main thread but may need to attach various
   2614     // handlers to other threads.  So take care to be explicit about the looper.
   2615     public ActivityManagerService(Context systemContext) {
   2616         mContext = systemContext;
   2617         mFactoryTest = FactoryTest.getMode();
   2618         mSystemThread = ActivityThread.currentActivityThread();
   2619 
   2620         Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
   2621 
   2622         mHandlerThread = new ServiceThread(TAG,
   2623                 android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
   2624         mHandlerThread.start();
   2625         mHandler = new MainHandler(mHandlerThread.getLooper());
   2626         mUiHandler = new UiHandler();
   2627 
   2628         /* static; one-time init here */
   2629         if (sKillHandler == null) {
   2630             sKillThread = new ServiceThread(TAG + ":kill",
   2631                     android.os.Process.THREAD_PRIORITY_BACKGROUND, true /* allowIo */);
   2632             sKillThread.start();
   2633             sKillHandler = new KillHandler(sKillThread.getLooper());
   2634         }
   2635 
   2636         mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
   2637                 "foreground", BROADCAST_FG_TIMEOUT, false);
   2638         mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
   2639                 "background", BROADCAST_BG_TIMEOUT, true);
   2640         mBroadcastQueues[0] = mFgBroadcastQueue;
   2641         mBroadcastQueues[1] = mBgBroadcastQueue;
   2642 
   2643         mServices = new ActiveServices(this);
   2644         mProviderMap = new ProviderMap(this);
   2645         mAppErrors = new AppErrors(mContext, this);
   2646 
   2647         // TODO: Move creation of battery stats service outside of activity manager service.
   2648         File dataDir = Environment.getDataDirectory();
   2649         File systemDir = new File(dataDir, "system");
   2650         systemDir.mkdirs();
   2651         mBatteryStatsService = new BatteryStatsService(systemDir, mHandler);
   2652         mBatteryStatsService.getActiveStatistics().readLocked();
   2653         mBatteryStatsService.scheduleWriteToDisk();
   2654         mOnBattery = DEBUG_POWER ? true
   2655                 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
   2656         mBatteryStatsService.getActiveStatistics().setCallback(this);
   2657 
   2658         mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
   2659 
   2660         mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml"), mHandler);
   2661         mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
   2662                 new IAppOpsCallback.Stub() {
   2663                     @Override public void opChanged(int op, int uid, String packageName) {
   2664                         if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
   2665                             if (mAppOpsService.checkOperation(op, uid, packageName)
   2666                                     != AppOpsManager.MODE_ALLOWED) {
   2667                                 runInBackgroundDisabled(uid);
   2668                             }
   2669                         }
   2670                     }
   2671                 });
   2672 
   2673         mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"));
   2674 
   2675         mUserController = new UserController(this);
   2676 
   2677         GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
   2678             ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
   2679 
   2680         if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
   2681             mUseFifoUiScheduling = true;
   2682         }
   2683 
   2684         mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
   2685 
   2686         mConfiguration.setToDefaults();
   2687         mConfiguration.setLocales(LocaleList.getDefault());
   2688 
   2689         mConfigurationSeq = mConfiguration.seq = 1;
   2690         mProcessCpuTracker.init();
   2691 
   2692         mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
   2693         mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
   2694         mStackSupervisor = new ActivityStackSupervisor(this);
   2695         mActivityStarter = new ActivityStarter(this, mStackSupervisor);
   2696         mRecentTasks = new RecentTasks(this, mStackSupervisor);
   2697 
   2698         mProcessCpuThread = new Thread("CpuTracker") {
   2699             @Override
   2700             public void run() {
   2701                 while (true) {
   2702                     try {
   2703                         try {
   2704                             synchronized(this) {
   2705                                 final long now = SystemClock.uptimeMillis();
   2706                                 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
   2707                                 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
   2708                                 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
   2709                                 //        + ", write delay=" + nextWriteDelay);
   2710                                 if (nextWriteDelay < nextCpuDelay) {
   2711                                     nextCpuDelay = nextWriteDelay;
   2712                                 }
   2713                                 if (nextCpuDelay > 0) {
   2714                                     mProcessCpuMutexFree.set(true);
   2715                                     this.wait(nextCpuDelay);
   2716                                 }
   2717                             }
   2718                         } catch (InterruptedException e) {
   2719                         }
   2720                         updateCpuStatsNow();
   2721                     } catch (Exception e) {
   2722                         Slog.e(TAG, "Unexpected exception collecting process stats", e);
   2723                     }
   2724                 }
   2725             }
   2726         };
   2727 
   2728         Watchdog.getInstance().addMonitor(this);
   2729         Watchdog.getInstance().addThread(mHandler);
   2730     }
   2731 
   2732     public void setSystemServiceManager(SystemServiceManager mgr) {
   2733         mSystemServiceManager = mgr;
   2734     }
   2735 
   2736     public void setInstaller(Installer installer) {
   2737         mInstaller = installer;
   2738     }
   2739 
   2740     private void start() {
   2741         Process.removeAllProcessGroups();
   2742         mProcessCpuThread.start();
   2743 
   2744         mBatteryStatsService.publish(mContext);
   2745         mAppOpsService.publish(mContext);
   2746         Slog.d("AppOps", "AppOpsService published");
   2747         LocalServices.addService(ActivityManagerInternal.class, new LocalService());
   2748     }
   2749 
   2750     void onUserStoppedLocked(int userId) {
   2751         mRecentTasks.unloadUserDataFromMemoryLocked(userId);
   2752     }
   2753 
   2754     public void initPowerManagement() {
   2755         mStackSupervisor.initPowerManagement();
   2756         mBatteryStatsService.initPowerManagement();
   2757         mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
   2758         PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
   2759         mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
   2760         mVoiceWakeLock.setReferenceCounted(false);
   2761     }
   2762 
   2763     @Override
   2764     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
   2765             throws RemoteException {
   2766         if (code == SYSPROPS_TRANSACTION) {
   2767             // We need to tell all apps about the system property change.
   2768             ArrayList<IBinder> procs = new ArrayList<IBinder>();
   2769             synchronized(this) {
   2770                 final int NP = mProcessNames.getMap().size();
   2771                 for (int ip=0; ip<NP; ip++) {
   2772                     SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
   2773                     final int NA = apps.size();
   2774                     for (int ia=0; ia<NA; ia++) {
   2775                         ProcessRecord app = apps.valueAt(ia);
   2776                         if (app.thread != null) {
   2777                             procs.add(app.thread.asBinder());
   2778                         }
   2779                     }
   2780                 }
   2781             }
   2782 
   2783             int N = procs.size();
   2784             for (int i=0; i<N; i++) {
   2785                 Parcel data2 = Parcel.obtain();
   2786                 try {
   2787                     procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
   2788                 } catch (RemoteException e) {
   2789                 }
   2790                 data2.recycle();
   2791             }
   2792         }
   2793         try {
   2794             return super.onTransact(code, data, reply, flags);
   2795         } catch (RuntimeException e) {
   2796             // The activity manager only throws security exceptions, so let's
   2797             // log all others.
   2798             if (!(e instanceof SecurityException)) {
   2799                 Slog.wtf(TAG, "Activity Manager Crash", e);
   2800             }
   2801             throw e;
   2802         }
   2803     }
   2804 
   2805     void updateCpuStats() {
   2806         final long now = SystemClock.uptimeMillis();
   2807         if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
   2808             return;
   2809         }
   2810         if (mProcessCpuMutexFree.compareAndSet(true, false)) {
   2811             synchronized (mProcessCpuThread) {
   2812                 mProcessCpuThread.notify();
   2813             }
   2814         }
   2815     }
   2816 
   2817     void updateCpuStatsNow() {
   2818         synchronized (mProcessCpuTracker) {
   2819             mProcessCpuMutexFree.set(false);
   2820             final long now = SystemClock.uptimeMillis();
   2821             boolean haveNewCpuStats = false;
   2822 
   2823             if (MONITOR_CPU_USAGE &&
   2824                     mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
   2825                 mLastCpuTime.set(now);
   2826                 mProcessCpuTracker.update();
   2827                 if (mProcessCpuTracker.hasGoodLastStats()) {
   2828                     haveNewCpuStats = true;
   2829                     //Slog.i(TAG, mProcessCpu.printCurrentState());
   2830                     //Slog.i(TAG, "Total CPU usage: "
   2831                     //        + mProcessCpu.getTotalCpuPercent() + "%");
   2832 
   2833                     // Slog the cpu usage if the property is set.
   2834                     if ("true".equals(SystemProperties.get("events.cpu"))) {
   2835                         int user = mProcessCpuTracker.getLastUserTime();
   2836                         int system = mProcessCpuTracker.getLastSystemTime();
   2837                         int iowait = mProcessCpuTracker.getLastIoWaitTime();
   2838                         int irq = mProcessCpuTracker.getLastIrqTime();
   2839                         int softIrq = mProcessCpuTracker.getLastSoftIrqTime();
   2840                         int idle = mProcessCpuTracker.getLastIdleTime();
   2841 
   2842                         int total = user + system + iowait + irq + softIrq + idle;
   2843                         if (total == 0) total = 1;
   2844 
   2845                         EventLog.writeEvent(EventLogTags.CPU,
   2846                                 ((user+system+iowait+irq+softIrq) * 100) / total,
   2847                                 (user * 100) / total,
   2848                                 (system * 100) / total,
   2849                                 (iowait * 100) / total,
   2850                                 (irq * 100) / total,
   2851                                 (softIrq * 100) / total);
   2852                     }
   2853                 }
   2854             }
   2855 
   2856             final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
   2857             synchronized(bstats) {
   2858                 synchronized(mPidsSelfLocked) {
   2859                     if (haveNewCpuStats) {
   2860                         if (bstats.startAddingCpuLocked()) {
   2861                             int totalUTime = 0;
   2862                             int totalSTime = 0;
   2863                             final int N = mProcessCpuTracker.countStats();
   2864                             for (int i=0; i<N; i++) {
   2865                                 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
   2866                                 if (!st.working) {
   2867                                     continue;
   2868                                 }
   2869                                 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
   2870                                 totalUTime += st.rel_utime;
   2871                                 totalSTime += st.rel_stime;
   2872                                 if (pr != null) {
   2873                                     BatteryStatsImpl.Uid.Proc ps = pr.curProcBatteryStats;
   2874                                     if (ps == null || !ps.isActive()) {
   2875                                         pr.curProcBatteryStats = ps = bstats.getProcessStatsLocked(
   2876                                                 pr.info.uid, pr.processName);
   2877                                     }
   2878                                     ps.addCpuTimeLocked(st.rel_utime, st.rel_stime);
   2879                                     pr.curCpuTime += st.rel_utime + st.rel_stime;
   2880                                 } else {
   2881                                     BatteryStatsImpl.Uid.Proc ps = st.batteryStats;
   2882                                     if (ps == null || !ps.isActive()) {
   2883                                         st.batteryStats = ps = bstats.getProcessStatsLocked(
   2884                                                 bstats.mapUid(st.uid), st.name);
   2885                                     }
   2886                                     ps.addCpuTimeLocked(st.rel_utime, st.rel_stime);
   2887                                 }
   2888                             }
   2889                             final int userTime = mProcessCpuTracker.getLastUserTime();
   2890                             final int systemTime = mProcessCpuTracker.getLastSystemTime();
   2891                             final int iowaitTime = mProcessCpuTracker.getLastIoWaitTime();
   2892                             final int irqTime = mProcessCpuTracker.getLastIrqTime();
   2893                             final int softIrqTime = mProcessCpuTracker.getLastSoftIrqTime();
   2894                             final int idleTime = mProcessCpuTracker.getLastIdleTime();
   2895                             bstats.finishAddingCpuLocked(totalUTime, totalSTime, userTime,
   2896                                     systemTime, iowaitTime, irqTime, softIrqTime, idleTime);
   2897                         }
   2898                     }
   2899                 }
   2900 
   2901                 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
   2902                     mLastWriteTime = now;
   2903                     mBatteryStatsService.scheduleWriteToDisk();
   2904                 }
   2905             }
   2906         }
   2907     }
   2908 
   2909     @Override
   2910     public void batteryNeedsCpuUpdate() {
   2911         updateCpuStatsNow();
   2912     }
   2913 
   2914     @Override
   2915     public void batteryPowerChanged(boolean onBattery) {
   2916         // When plugging in, update the CPU stats first before changing
   2917         // the plug state.
   2918         updateCpuStatsNow();
   2919         synchronized (this) {
   2920             synchronized(mPidsSelfLocked) {
   2921                 mOnBattery = DEBUG_POWER ? true : onBattery;
   2922             }
   2923         }
   2924     }
   2925 
   2926     @Override
   2927     public void batterySendBroadcast(Intent intent) {
   2928         broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
   2929                 AppOpsManager.OP_NONE, null, false, false,
   2930                 -1, Process.SYSTEM_UID, UserHandle.USER_ALL);
   2931     }
   2932 
   2933     /**
   2934      * Initialize the application bind args. These are passed to each
   2935      * process when the bindApplication() IPC is sent to the process. They're
   2936      * lazily setup to make sure the services are running when they're asked for.
   2937      */
   2938     private HashMap<String, IBinder> getCommonServicesLocked(boolean isolated) {
   2939         // Isolated processes won't get this optimization, so that we don't
   2940         // violate the rules about which services they have access to.
   2941         if (isolated) {
   2942             if (mIsolatedAppBindArgs == null) {
   2943                 mIsolatedAppBindArgs = new HashMap<>();
   2944                 mIsolatedAppBindArgs.put("package", ServiceManager.getService("package"));
   2945             }
   2946             return mIsolatedAppBindArgs;
   2947         }
   2948 
   2949         if (mAppBindArgs == null) {
   2950             mAppBindArgs = new HashMap<>();
   2951 
   2952             // Setup the application init args
   2953             mAppBindArgs.put("package", ServiceManager.getService("package"));
   2954             mAppBindArgs.put("window", ServiceManager.getService("window"));
   2955             mAppBindArgs.put(Context.ALARM_SERVICE,
   2956                     ServiceManager.getService(Context.ALARM_SERVICE));
   2957         }
   2958         return mAppBindArgs;
   2959     }
   2960 
   2961     boolean setFocusedActivityLocked(ActivityRecord r, String reason) {
   2962         if (r == null || mFocusedActivity == r) {
   2963             return false;
   2964         }
   2965 
   2966         if (!r.isFocusable()) {
   2967             if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedActivityLocked: unfocusable r=" + r);
   2968             return false;
   2969         }
   2970 
   2971         if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedActivityLocked: r=" + r);
   2972 
   2973         final boolean wasDoingSetFocusedActivity = mDoingSetFocusedActivity;
   2974         if (wasDoingSetFocusedActivity) Slog.w(TAG,
   2975                 "setFocusedActivityLocked: called recursively, r=" + r + ", reason=" + reason);
   2976         mDoingSetFocusedActivity = true;
   2977 
   2978         final ActivityRecord last = mFocusedActivity;
   2979         mFocusedActivity = r;
   2980         if (r.task.isApplicationTask()) {
   2981             if (mCurAppTimeTracker != r.appTimeTracker) {
   2982                 // We are switching app tracking.  Complete the current one.
   2983                 if (mCurAppTimeTracker != null) {
   2984                     mCurAppTimeTracker.stop();
   2985                     mHandler.obtainMessage(
   2986                             REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
   2987                     mStackSupervisor.clearOtherAppTimeTrackers(r.appTimeTracker);
   2988                     mCurAppTimeTracker = null;
   2989                 }
   2990                 if (r.appTimeTracker != null) {
   2991                     mCurAppTimeTracker = r.appTimeTracker;
   2992                     startTimeTrackingFocusedActivityLocked();
   2993                 }
   2994             } else {
   2995                 startTimeTrackingFocusedActivityLocked();
   2996             }
   2997         } else {
   2998             r.appTimeTracker = null;
   2999         }
   3000         // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
   3001         // TODO: Probably not, because we don't want to resume voice on switching
   3002         // back to this activity
   3003         if (r.task.voiceInteractor != null) {
   3004             startRunningVoiceLocked(r.task.voiceSession, r.info.applicationInfo.uid);
   3005         } else {
   3006             finishRunningVoiceLocked();
   3007             IVoiceInteractionSession session;
   3008             if (last != null && ((session = last.task.voiceSession) != null
   3009                     || (session = last.voiceSession) != null)) {
   3010                 // We had been in a voice interaction session, but now focused has
   3011                 // move to something different.  Just finish the session, we can't
   3012                 // return to it and retain the proper state and synchronization with
   3013                 // the voice interaction service.
   3014                 finishVoiceTask(session);
   3015             }
   3016         }
   3017         if (mStackSupervisor.moveActivityStackToFront(r, reason + " setFocusedActivity")) {
   3018             mWindowManager.setFocusedApp(r.appToken, true);
   3019         }
   3020         applyUpdateLockStateLocked(r);
   3021         applyUpdateVrModeLocked(r);
   3022         if (mFocusedActivity.userId != mLastFocusedUserId) {
   3023             mHandler.removeMessages(FOREGROUND_PROFILE_CHANGED_MSG);
   3024             mHandler.obtainMessage(
   3025                     FOREGROUND_PROFILE_CHANGED_MSG, mFocusedActivity.userId, 0).sendToTarget();
   3026             mLastFocusedUserId = mFocusedActivity.userId;
   3027         }
   3028 
   3029         // Log a warning if the focused app is changed during the process. This could
   3030         // indicate a problem of the focus setting logic!
   3031         if (mFocusedActivity != r) Slog.w(TAG,
   3032                 "setFocusedActivityLocked: r=" + r + " but focused to " + mFocusedActivity);
   3033         mDoingSetFocusedActivity = wasDoingSetFocusedActivity;
   3034 
   3035         EventLogTags.writeAmFocusedActivity(
   3036                 mFocusedActivity == null ? -1 : mFocusedActivity.userId,
   3037                 mFocusedActivity == null ? "NULL" : mFocusedActivity.shortComponentName,
   3038                 reason);
   3039         return true;
   3040     }
   3041 
   3042     final void resetFocusedActivityIfNeededLocked(ActivityRecord goingAway) {
   3043         if (mFocusedActivity != goingAway) {
   3044             return;
   3045         }
   3046 
   3047         final ActivityStack focusedStack = mStackSupervisor.getFocusedStack();
   3048         if (focusedStack != null) {
   3049             final ActivityRecord top = focusedStack.topActivity();
   3050             if (top != null && top.userId != mLastFocusedUserId) {
   3051                 mHandler.removeMessages(FOREGROUND_PROFILE_CHANGED_MSG);
   3052                 mHandler.sendMessage(
   3053                         mHandler.obtainMessage(FOREGROUND_PROFILE_CHANGED_MSG, top.userId, 0));
   3054                 mLastFocusedUserId = top.userId;
   3055             }
   3056         }
   3057 
   3058         // Try to move focus to another activity if possible.
   3059         if (setFocusedActivityLocked(
   3060                 focusedStack.topRunningActivityLocked(), "resetFocusedActivityIfNeeded")) {
   3061             return;
   3062         }
   3063 
   3064         if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "resetFocusedActivityIfNeeded: Setting focus to NULL "
   3065                 + "prev mFocusedActivity=" + mFocusedActivity + " goingAway=" + goingAway);
   3066         mFocusedActivity = null;
   3067         EventLogTags.writeAmFocusedActivity(-1, "NULL", "resetFocusedActivityIfNeeded");
   3068     }
   3069 
   3070     @Override
   3071     public void setFocusedStack(int stackId) {
   3072         enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
   3073         if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
   3074         final long callingId = Binder.clearCallingIdentity();
   3075         try {
   3076             synchronized (this) {
   3077                 final ActivityStack stack = mStackSupervisor.getStack(stackId);
   3078                 if (stack == null) {
   3079                     return;
   3080                 }
   3081                 final ActivityRecord r = stack.topRunningActivityLocked();
   3082                 if (setFocusedActivityLocked(r, "setFocusedStack")) {
   3083                     mStackSupervisor.resumeFocusedStackTopActivityLocked();
   3084                 }
   3085             }
   3086         } finally {
   3087             Binder.restoreCallingIdentity(callingId);
   3088         }
   3089     }
   3090 
   3091     @Override
   3092     public void setFocusedTask(int taskId) {
   3093         enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
   3094         if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
   3095         final long callingId = Binder.clearCallingIdentity();
   3096         try {
   3097             synchronized (this) {
   3098                 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
   3099                 if (task == null) {
   3100                     return;
   3101                 }
   3102                 if (mUserController.shouldConfirmCredentials(task.userId)) {
   3103                     mActivityStarter.showConfirmDeviceCredential(task.userId);
   3104                     if (task.stack != null && task.stack.mStackId == FREEFORM_WORKSPACE_STACK_ID) {
   3105                         mStackSupervisor.moveTaskToStackLocked(task.taskId,
   3106                                 FULLSCREEN_WORKSPACE_STACK_ID, !ON_TOP, !FORCE_FOCUS,
   3107                                 "setFocusedTask", ANIMATE);
   3108                     }
   3109                     return;
   3110                 }
   3111                 final ActivityRecord r = task.topRunningActivityLocked();
   3112                 if (setFocusedActivityLocked(r, "setFocusedTask")) {
   3113                     mStackSupervisor.resumeFocusedStackTopActivityLocked();
   3114                 }
   3115             }
   3116         } finally {
   3117             Binder.restoreCallingIdentity(callingId);
   3118         }
   3119     }
   3120 
   3121     /** Sets the task stack listener that gets callbacks when a task stack changes. */
   3122     @Override
   3123     public void registerTaskStackListener(ITaskStackListener listener) throws RemoteException {
   3124         enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "registerTaskStackListener()");
   3125         synchronized (this) {
   3126             if (listener != null) {
   3127                 mTaskStackListeners.register(listener);
   3128             }
   3129         }
   3130     }
   3131 
   3132     @Override
   3133     public void notifyActivityDrawn(IBinder token) {
   3134         if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
   3135         synchronized (this) {
   3136             ActivityRecord r = mStackSupervisor.isInAnyStackLocked(token);
   3137             if (r != null) {
   3138                 r.task.stack.notifyActivityDrawnLocked(r);
   3139             }
   3140         }
   3141     }
   3142 
   3143     final void applyUpdateLockStateLocked(ActivityRecord r) {
   3144         // Modifications to the UpdateLock state are done on our handler, outside
   3145         // the activity manager's locks.  The new state is determined based on the
   3146         // state *now* of the relevant activity record.  The object is passed to
   3147         // the handler solely for logging detail, not to be consulted/modified.
   3148         final boolean nextState = r != null && r.immersive;
   3149         mHandler.sendMessage(
   3150                 mHandler.obtainMessage(IMMERSIVE_MODE_LOCK_MSG, (nextState) ? 1 : 0, 0, r));
   3151     }
   3152 
   3153     final void applyUpdateVrModeLocked(ActivityRecord r) {
   3154         mHandler.sendMessage(
   3155                 mHandler.obtainMessage(VR_MODE_CHANGE_MSG, 0, 0, r));
   3156     }
   3157 
   3158     private void applyVrModeIfNeededLocked(ActivityRecord r, boolean enable) {
   3159         mHandler.sendMessage(
   3160                 mHandler.obtainMessage(VR_MODE_APPLY_IF_NEEDED_MSG, enable ? 1 : 0, 0, r));
   3161     }
   3162 
   3163     private void applyVrMode(boolean enabled, ComponentName packageName, int userId,
   3164             ComponentName callingPackage, boolean immediate) {
   3165         VrManagerInternal vrService =
   3166                 LocalServices.getService(VrManagerInternal.class);
   3167         if (immediate) {
   3168             vrService.setVrModeImmediate(enabled, packageName, userId, callingPackage);
   3169         } else {
   3170             vrService.setVrMode(enabled, packageName, userId, callingPackage);
   3171         }
   3172     }
   3173 
   3174     final void showAskCompatModeDialogLocked(ActivityRecord r) {
   3175         Message msg = Message.obtain();
   3176         msg.what = SHOW_COMPAT_MODE_DIALOG_UI_MSG;
   3177         msg.obj = r.task.askedCompatMode ? null : r;
   3178         mUiHandler.sendMessage(msg);
   3179     }
   3180 
   3181     final void showUnsupportedZoomDialogIfNeededLocked(ActivityRecord r) {
   3182         if (mConfiguration.densityDpi != DisplayMetrics.DENSITY_DEVICE_STABLE
   3183                 && r.appInfo.requiresSmallestWidthDp > mConfiguration.smallestScreenWidthDp) {
   3184             final Message msg = Message.obtain();
   3185             msg.what = SHOW_UNSUPPORTED_DISPLAY_SIZE_DIALOG_MSG;
   3186             msg.obj = r;
   3187             mUiHandler.sendMessage(msg);
   3188         }
   3189     }
   3190 
   3191     private int updateLruProcessInternalLocked(ProcessRecord app, long now, int index,
   3192             String what, Object obj, ProcessRecord srcApp) {
   3193         app.lastActivityTime = now;
   3194 
   3195         if (app.activities.size() > 0) {
   3196             // Don't want to touch dependent processes that are hosting activities.
   3197             return index;
   3198         }
   3199 
   3200         int lrui = mLruProcesses.lastIndexOf(app);
   3201         if (lrui < 0) {
   3202             Slog.wtf(TAG, "Adding dependent process " + app + " not on LRU list: "
   3203                     + what + " " + obj + " from " + srcApp);
   3204             return index;
   3205         }
   3206 
   3207         if (lrui >= index) {
   3208             // Don't want to cause this to move dependent processes *back* in the
   3209             // list as if they were less frequently used.
   3210             return index;
   3211         }
   3212 
   3213         if (lrui >= mLruProcessActivityStart) {
   3214             // Don't want to touch dependent processes that are hosting activities.
   3215             return index;
   3216         }
   3217 
   3218         mLruProcesses.remove(lrui);
   3219         if (index > 0) {
   3220             index--;
   3221         }
   3222         if (DEBUG_LRU) Slog.d(TAG_LRU, "Moving dep from " + lrui + " to " + index
   3223                 + " in LRU list: " + app);
   3224         mLruProcesses.add(index, app);
   3225         return index;
   3226     }
   3227 
   3228     static void killProcessGroup(int uid, int pid) {
   3229         if (sKillHandler != null) {
   3230             sKillHandler.sendMessage(
   3231                     sKillHandler.obtainMessage(KillHandler.KILL_PROCESS_GROUP_MSG, uid, pid));
   3232         } else {
   3233             Slog.w(TAG, "Asked to kill process group before system bringup!");
   3234             Process.killProcessGroup(uid, pid);
   3235         }
   3236     }
   3237 
   3238     final void removeLruProcessLocked(ProcessRecord app) {
   3239         int lrui = mLruProcesses.lastIndexOf(app);
   3240         if (lrui >= 0) {
   3241             if (!app.killed) {
   3242                 Slog.wtfStack(TAG, "Removing process that hasn't been killed: " + app);
   3243                 Process.killProcessQuiet(app.pid);
   3244                 killProcessGroup(app.uid, app.pid);
   3245             }
   3246             if (lrui <= mLruProcessActivityStart) {
   3247                 mLruProcessActivityStart--;
   3248             }
   3249             if (lrui <= mLruProcessServiceStart) {
   3250                 mLruProcessServiceStart--;
   3251             }
   3252             mLruProcesses.remove(lrui);
   3253         }
   3254     }
   3255 
   3256     final void updateLruProcessLocked(ProcessRecord app, boolean activityChange,
   3257             ProcessRecord client) {
   3258         final boolean hasActivity = app.activities.size() > 0 || app.hasClientActivities
   3259                 || app.treatLikeActivity;
   3260         final boolean hasService = false; // not impl yet. app.services.size() > 0;
   3261         if (!activityChange && hasActivity) {
   3262             // The process has activities, so we are only allowing activity-based adjustments
   3263             // to move it.  It should be kept in the front of the list with other
   3264             // processes that have activities, and we don't want those to change their
   3265             // order except due to activity operations.
   3266             return;
   3267         }
   3268 
   3269         mLruSeq++;
   3270         final long now = SystemClock.uptimeMillis();
   3271         app.lastActivityTime = now;
   3272 
   3273         // First a quick reject: if the app is already at the position we will
   3274         // put it, then there is nothing to do.
   3275         if (hasActivity) {
   3276             final int N = mLruProcesses.size();
   3277             if (N > 0 && mLruProcesses.get(N-1) == app) {
   3278                 if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, already top activity: " + app);
   3279                 return;
   3280             }
   3281         } else {
   3282             if (mLruProcessServiceStart > 0
   3283                     && mLruProcesses.get(mLruProcessServiceStart-1) == app) {
   3284                 if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, already top other: " + app);
   3285                 return;
   3286             }
   3287         }
   3288 
   3289         int lrui = mLruProcesses.lastIndexOf(app);
   3290 
   3291         if (app.persistent && lrui >= 0) {
   3292             // We don't care about the position of persistent processes, as long as
   3293             // they are in the list.
   3294             if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, persistent: " + app);
   3295             return;
   3296         }
   3297 
   3298         /* In progress: compute new position first, so we can avoid doing work
   3299            if the process is not actually going to move.  Not yet working.
   3300         int addIndex;
   3301         int nextIndex;
   3302         boolean inActivity = false, inService = false;
   3303         if (hasActivity) {
   3304             // Process has activities, put it at the very tipsy-top.
   3305             addIndex = mLruProcesses.size();
   3306             nextIndex = mLruProcessServiceStart;
   3307             inActivity = true;
   3308         } else if (hasService) {
   3309             // Process has services, put it at the top of the service list.
   3310             addIndex = mLruProcessActivityStart;
   3311             nextIndex = mLruProcessServiceStart;
   3312             inActivity = true;
   3313             inService = true;
   3314         } else  {
   3315             // Process not otherwise of interest, it goes to the top of the non-service area.
   3316             addIndex = mLruProcessServiceStart;
   3317             if (client != null) {
   3318                 int clientIndex = mLruProcesses.lastIndexOf(client);
   3319                 if (clientIndex < 0) Slog.d(TAG, "Unknown client " + client + " when updating "
   3320                         + app);
   3321                 if (clientIndex >= 0 && addIndex > clientIndex) {
   3322                     addIndex = clientIndex;
   3323                 }
   3324             }
   3325             nextIndex = addIndex > 0 ? addIndex-1 : addIndex;
   3326         }
   3327 
   3328         Slog.d(TAG, "Update LRU at " + lrui + " to " + addIndex + " (act="
   3329                 + mLruProcessActivityStart + "): " + app);
   3330         */
   3331 
   3332         if (lrui >= 0) {
   3333             if (lrui < mLruProcessActivityStart) {
   3334                 mLruProcessActivityStart--;
   3335             }
   3336             if (lrui < mLruProcessServiceStart) {
   3337                 mLruProcessServiceStart--;
   3338             }
   3339             /*
   3340             if (addIndex > lrui) {
   3341                 addIndex--;
   3342             }
   3343             if (nextIndex > lrui) {
   3344                 nextIndex--;
   3345             }
   3346             */
   3347             mLruProcesses.remove(lrui);
   3348         }
   3349 
   3350         /*
   3351         mLruProcesses.add(addIndex, app);
   3352         if (inActivity) {
   3353             mLruProcessActivityStart++;
   3354         }
   3355         if (inService) {
   3356             mLruProcessActivityStart++;
   3357         }
   3358         */
   3359 
   3360         int nextIndex;
   3361         if (hasActivity) {
   3362             final int N = mLruProcesses.size();
   3363             if (app.activities.size() == 0 && mLruProcessActivityStart < (N - 1)) {
   3364                 // Process doesn't have activities, but has clients with
   3365                 // activities...  move it up, but one below the top (the top
   3366                 // should always have a real activity).
   3367                 if (DEBUG_LRU) Slog.d(TAG_LRU,
   3368                         "Adding to second-top of LRU activity list: " + app);
   3369                 mLruProcesses.add(N - 1, app);
   3370                 // To keep it from spamming the LRU list (by making a bunch of clients),
   3371                 // we will push down any other entries owned by the app.
   3372                 final int uid = app.info.uid;
   3373                 for (int i = N - 2; i > mLruProcessActivityStart; i--) {
   3374                     ProcessRecord subProc = mLruProcesses.get(i);
   3375                     if (subProc.info.uid == uid) {
   3376                         // We want to push this one down the list.  If the process after
   3377                         // it is for the same uid, however, don't do so, because we don't
   3378                         // want them internally to be re-ordered.
   3379                         if (mLruProcesses.get(i - 1).info.uid != uid) {
   3380                             if (DEBUG_LRU) Slog.d(TAG_LRU,
   3381                                     "Pushing uid " + uid + " swapping at " + i + ": "
   3382                                     + mLruProcesses.get(i) + " : " + mLruProcesses.get(i - 1));
   3383                             ProcessRecord tmp = mLruProcesses.get(i);
   3384                             mLruProcesses.set(i, mLruProcesses.get(i - 1));
   3385                             mLruProcesses.set(i - 1, tmp);
   3386                             i--;
   3387                         }
   3388                     } else {
   3389                         // A gap, we can stop here.
   3390                         break;
   3391                     }
   3392                 }
   3393             } else {
   3394                 // Process has activities, put it at the very tipsy-top.
   3395                 if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding to top of LRU activity list: " + app);
   3396                 mLruProcesses.add(app);
   3397             }
   3398             nextIndex = mLruProcessServiceStart;
   3399         } else if (hasService) {
   3400             // Process has services, put it at the top of the service list.
   3401             if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding to top of LRU service list: " + app);
   3402             mLruProcesses.add(mLruProcessActivityStart, app);
   3403             nextIndex = mLruProcessServiceStart;
   3404             mLruProcessActivityStart++;
   3405         } else  {
   3406             // Process not otherwise of interest, it goes to the top of the non-service area.
   3407             int index = mLruProcessServiceStart;
   3408             if (client != null) {
   3409                 // If there is a client, don't allow the process to be moved up higher
   3410                 // in the list than that client.
   3411                 int clientIndex = mLruProcesses.lastIndexOf(client);
   3412                 if (DEBUG_LRU && clientIndex < 0) Slog.d(TAG_LRU, "Unknown client " + client
   3413                         + " when updating " + app);
   3414                 if (clientIndex <= lrui) {
   3415                     // Don't allow the client index restriction to push it down farther in the
   3416                     // list than it already is.
   3417                     clientIndex = lrui;
   3418                 }
   3419                 if (clientIndex >= 0 && index > clientIndex) {
   3420                     index = clientIndex;
   3421                 }
   3422             }
   3423             if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding at " + index + " of LRU list: " + app);
   3424             mLruProcesses.add(index, app);
   3425             nextIndex = index-1;
   3426             mLruProcessActivityStart++;
   3427             mLruProcessServiceStart++;
   3428         }
   3429 
   3430         // If the app is currently using a content provider or service,
   3431         // bump those processes as well.
   3432         for (int j=app.connections.size()-1; j>=0; j--) {
   3433             ConnectionRecord cr = app.connections.valueAt(j);
   3434             if (cr.binding != null && !cr.serviceDead && cr.binding.service != null
   3435                     && cr.binding.service.app != null
   3436                     && cr.binding.service.app.lruSeq != mLruSeq
   3437                     && !cr.binding.service.app.persistent) {
   3438                 nextIndex = updateLruProcessInternalLocked(cr.binding.service.app, now, nextIndex,
   3439                         "service connection", cr, app);
   3440             }
   3441         }
   3442         for (int j=app.conProviders.size()-1; j>=0; j--) {
   3443             ContentProviderRecord cpr = app.conProviders.get(j).provider;
   3444             if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq && !cpr.proc.persistent) {
   3445                 nextIndex = updateLruProcessInternalLocked(cpr.proc, now, nextIndex,
   3446                         "provider reference", cpr, app);
   3447             }
   3448         }
   3449     }
   3450 
   3451     final ProcessRecord getProcessRecordLocked(String processName, int uid, boolean keepIfLarge) {
   3452         if (uid == Process.SYSTEM_UID) {
   3453             // The system gets to run in any process.  If there are multiple
   3454             // processes with the same uid, just pick the first (this
   3455             // should never happen).
   3456             SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(processName);
   3457             if (procs == null) return null;
   3458             final int procCount = procs.size();
   3459             for (int i = 0; i < procCount; i++) {
   3460                 final int procUid = procs.keyAt(i);
   3461                 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
   3462                     // Don't use an app process or different user process for system component.
   3463                     continue;
   3464                 }
   3465                 return procs.valueAt(i);
   3466             }
   3467         }
   3468         ProcessRecord proc = mProcessNames.get(processName, uid);
   3469         if (false && proc != null && !keepIfLarge
   3470                 && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY
   3471                 && proc.lastCachedPss >= 4000) {
   3472             // Turn this condition on to cause killing to happen regularly, for testing.
   3473             if (proc.baseProcessTracker != null) {
   3474                 proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss);
   3475             }
   3476             proc.kill(Long.toString(proc.lastCachedPss) + "k from cached", true);
   3477         } else if (proc != null && !keepIfLarge
   3478                 && mLastMemoryLevel > ProcessStats.ADJ_MEM_FACTOR_NORMAL
   3479                 && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
   3480             if (DEBUG_PSS) Slog.d(TAG_PSS, "May not keep " + proc + ": pss=" + proc.lastCachedPss);
   3481             if (proc.lastCachedPss >= mProcessList.getCachedRestoreThresholdKb()) {
   3482                 if (proc.baseProcessTracker != null) {
   3483                     proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss);
   3484                 }
   3485                 proc.kill(Long.toString(proc.lastCachedPss) + "k from cached", true);
   3486             }
   3487         }
   3488         return proc;
   3489     }
   3490 
   3491     void notifyPackageUse(String packageName, int reason) {
   3492         IPackageManager pm = AppGlobals.getPackageManager();
   3493         try {
   3494             pm.notifyPackageUse(packageName, reason);
   3495         } catch (RemoteException e) {
   3496         }
   3497     }
   3498 
   3499     boolean isNextTransitionForward() {
   3500         int transit = mWindowManager.getPendingAppTransition();
   3501         return transit == TRANSIT_ACTIVITY_OPEN
   3502                 || transit == TRANSIT_TASK_OPEN
   3503                 || transit == TRANSIT_TASK_TO_FRONT;
   3504     }
   3505 
   3506     int startIsolatedProcess(String entryPoint, String[] entryPointArgs,
   3507             String processName, String abiOverride, int uid, Runnable crashHandler) {
   3508         synchronized(this) {
   3509             ApplicationInfo info = new ApplicationInfo();
   3510             // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid.
   3511             // For isolated processes, the former contains the parent's uid and the latter the
   3512             // actual uid of the isolated process.
   3513             // In the special case introduced by this method (which is, starting an isolated
   3514             // process directly from the SystemServer without an actual parent app process) the
   3515             // closest thing to a parent's uid is SYSTEM_UID.
   3516             // The only important thing here is to keep AI.uid != PR.uid, in order to trigger
   3517             // the |isolated| logic in the ProcessRecord constructor.
   3518             info.uid = Process.SYSTEM_UID;
   3519             info.processName = processName;
   3520             info.className = entryPoint;
   3521             info.packageName = "android";
   3522             ProcessRecord proc = startProcessLocked(processName, info /* info */,
   3523                     false /* knownToBeDead */, 0 /* intentFlags */, ""  /* hostingType */,
   3524                     null /* hostingName */, true /* allowWhileBooting */, true /* isolated */,
   3525                     uid, true /* keepIfLarge */, abiOverride, entryPoint, entryPointArgs,
   3526                     crashHandler);
   3527             return proc != null ? proc.pid : 0;
   3528         }
   3529     }
   3530 
   3531     final ProcessRecord startProcessLocked(String processName,
   3532             ApplicationInfo info, boolean knownToBeDead, int intentFlags,
   3533             String hostingType, ComponentName hostingName, boolean allowWhileBooting,
   3534             boolean isolated, boolean keepIfLarge) {
   3535         return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,
   3536                 hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
   3537                 null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
   3538                 null /* crashHandler */);
   3539     }
   3540 
   3541     final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
   3542             boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
   3543             boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
   3544             String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
   3545         long startTime = SystemClock.elapsedRealtime();
   3546         ProcessRecord app;
   3547         if (!isolated) {
   3548             app = getProcessRecordLocked(processName, info.uid, keepIfLarge);
   3549             checkTime(startTime, "startProcess: after getProcessRecord");
   3550 
   3551             if ((intentFlags & Intent.FLAG_FROM_BACKGROUND) != 0) {
   3552                 // If we are in the background, then check to see if this process
   3553                 // is bad.  If so, we will just silently fail.
   3554                 if (mAppErrors.isBadProcessLocked(info)) {
   3555                     if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
   3556                             + "/" + info.processName);
   3557                     return null;
   3558                 }
   3559             } else {
   3560                 // When the user is explicitly starting a process, then clear its
   3561                 // crash count so that we won't make it bad until they see at
   3562                 // least one crash dialog again, and make the process good again
   3563                 // if it had been bad.
   3564                 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
   3565                         + "/" + info.processName);
   3566                 mAppErrors.resetProcessCrashTimeLocked(info);
   3567                 if (mAppErrors.isBadProcessLocked(info)) {
   3568                     EventLog.writeEvent(EventLogTags.AM_PROC_GOOD,
   3569                             UserHandle.getUserId(info.uid), info.uid,
   3570                             info.processName);
   3571                     mAppErrors.clearBadProcessLocked(info);
   3572                     if (app != null) {
   3573                         app.bad = false;
   3574                     }
   3575                 }
   3576             }
   3577         } else {
   3578             // If this is an isolated process, it can't re-use an existing process.
   3579             app = null;
   3580         }
   3581 
   3582         // app launch boost for big.little configurations
   3583         // use cpusets to migrate freshly launched tasks to big cores
   3584         nativeMigrateToBoost();
   3585         mIsBoosted = true;
   3586         mBoostStartTime = SystemClock.uptimeMillis();
   3587         Message msg = mHandler.obtainMessage(APP_BOOST_DEACTIVATE_MSG);
   3588         mHandler.sendMessageDelayed(msg, APP_BOOST_MESSAGE_DELAY);
   3589 
   3590         // We don't have to do anything more if:
   3591         // (1) There is an existing application record; and
   3592         // (2) The caller doesn't think it is dead, OR there is no thread
   3593         //     object attached to it so we know it couldn't have crashed; and
   3594         // (3) There is a pid assigned to it, so it is either starting or
   3595         //     already running.
   3596         if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "startProcess: name=" + processName
   3597                 + " app=" + app + " knownToBeDead=" + knownToBeDead
   3598                 + " thread=" + (app != null ? app.thread : null)
   3599                 + " pid=" + (app != null ? app.pid : -1));
   3600         if (app != null && app.pid > 0) {
   3601             if ((!knownToBeDead && !app.killed) || app.thread == null) {
   3602                 // We already have the app running, or are waiting for it to
   3603                 // come up (we have a pid but not yet its thread), so keep it.
   3604                 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "App already running: " + app);
   3605                 // If this is a new package in the process, add the package to the list
   3606                 app.addPackage(info.packageName, info.versionCode, mProcessStats);
   3607                 checkTime(startTime, "startProcess: done, added package to proc");
   3608                 return app;
   3609             }
   3610 
   3611             // An application record is attached to a previous process,
   3612             // clean it up now.
   3613             if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG_PROCESSES, "App died: " + app);
   3614             checkTime(startTime, "startProcess: bad proc running, killing");
   3615             killProcessGroup(app.uid, app.pid);
   3616             handleAppDiedLocked(app, true, true);
   3617             checkTime(startTime, "startProcess: done killing old proc");
   3618         }
   3619 
   3620         String hostingNameStr = hostingName != null
   3621                 ? hostingName.flattenToShortString() : null;
   3622 
   3623         if (app == null) {
   3624             checkTime(startTime, "startProcess: creating new process record");
   3625             app = newProcessRecordLocked(info, processName, isolated, isolatedUid);
   3626             if (app == null) {
   3627                 Slog.w(TAG, "Failed making new process record for "
   3628                         + processName + "/" + info.uid + " isolated=" + isolated);
   3629                 return null;
   3630             }
   3631             app.crashHandler = crashHandler;
   3632             checkTime(startTime, "startProcess: done creating new process record");
   3633         } else {
   3634             // If this is a new package in the process, add the package to the list
   3635             app.addPackage(info.packageName, info.versionCode, mProcessStats);
   3636             checkTime(startTime, "startProcess: added package to existing proc");
   3637         }
   3638 
   3639         // If the system is not ready yet, then hold off on starting this
   3640         // process until it is.
   3641         if (!mProcessesReady
   3642                 && !isAllowedWhileBooting(info)
   3643                 && !allowWhileBooting) {
   3644             if (!mProcessesOnHold.contains(app)) {
   3645                 mProcessesOnHold.add(app);
   3646             }
   3647             if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES,
   3648                     "System not ready, putting on hold: " + app);
   3649             checkTime(startTime, "startProcess: returning with proc on hold");
   3650             return app;
   3651         }
   3652 
   3653         checkTime(startTime, "startProcess: stepping in to startProcess");
   3654         startProcessLocked(
   3655                 app, hostingType, hostingNameStr, abiOverride, entryPoint, entryPointArgs);
   3656         checkTime(startTime, "startProcess: done starting proc!");
   3657         return (app.pid != 0) ? app : null;
   3658     }
   3659 
   3660     boolean isAllowedWhileBooting(ApplicationInfo ai) {
   3661         return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
   3662     }
   3663 
   3664     private final void startProcessLocked(ProcessRecord app,
   3665             String hostingType, String hostingNameStr) {
   3666         startProcessLocked(app, hostingType, hostingNameStr, null /* abiOverride */,
   3667                 null /* entryPoint */, null /* entryPointArgs */);
   3668     }
   3669 
   3670     private final void startProcessLocked(ProcessRecord app, String hostingType,
   3671             String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {
   3672         long startTime = SystemClock.elapsedRealtime();
   3673         if (app.pid > 0 && app.pid != MY_PID) {
   3674             checkTime(startTime, "startProcess: removing from pids map");
   3675             synchronized (mPidsSelfLocked) {
   3676                 mPidsSelfLocked.remove(app.pid);
   3677                 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
   3678             }
   3679             checkTime(startTime, "startProcess: done removing from pids map");
   3680             app.setPid(0);
   3681         }
   3682 
   3683         if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG_PROCESSES,
   3684                 "startProcessLocked removing on hold: " + app);
   3685         mProcessesOnHold.remove(app);
   3686 
   3687         checkTime(startTime, "startProcess: starting to update cpu stats");
   3688         updateCpuStats();
   3689         checkTime(startTime, "startProcess: done updating cpu stats");
   3690 
   3691         try {
   3692             try {
   3693                 final int userId = UserHandle.getUserId(app.uid);
   3694                 AppGlobals.getPackageManager().checkPackageStartable(app.info.packageName, userId);
   3695             } catch (RemoteException e) {
   3696                 throw e.rethrowAsRuntimeException();
   3697             }
   3698 
   3699             int uid = app.uid;
   3700             int[] gids = null;
   3701             int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
   3702             if (!app.isolated) {
   3703                 int[] permGids = null;
   3704                 try {
   3705                     checkTime(startTime, "startProcess: getting gids from package manager");
   3706                     final IPackageManager pm = AppGlobals.getPackageManager();
   3707                     permGids = pm.getPackageGids(app.info.packageName,
   3708                             MATCH_DEBUG_TRIAGED_MISSING, app.userId);
   3709                     MountServiceInternal mountServiceInternal = LocalServices.getService(
   3710                             MountServiceInternal.class);
   3711                     mountExternal = mountServiceInternal.getExternalStorageMountMode(uid,
   3712                             app.info.packageName);
   3713                 } catch (RemoteException e) {
   3714                     throw e.rethrowAsRuntimeException();
   3715                 }
   3716 
   3717                 /*
   3718                  * Add shared application and profile GIDs so applications can share some
   3719                  * resources like shared libraries and access user-wide resources
   3720                  */
   3721                 if (ArrayUtils.isEmpty(permGids)) {
   3722                     gids = new int[2];
   3723                 } else {
   3724                     gids = new int[permGids.length + 2];
   3725                     System.arraycopy(permGids, 0, gids, 2, permGids.length);
   3726                 }
   3727                 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
   3728                 gids[1] = UserHandle.getUserGid(UserHandle.getUserId(uid));
   3729             }
   3730             checkTime(startTime, "startProcess: building args");
   3731             if (mFactoryTest != FactoryTest.FACTORY_TEST_OFF) {
   3732                 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
   3733                         && mTopComponent != null
   3734                         && app.processName.equals(mTopComponent.getPackageName())) {
   3735                     uid = 0;
   3736                 }
   3737                 if (mFactoryTest == FactoryTest.FACTORY_TEST_HIGH_LEVEL
   3738                         && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
   3739                     uid = 0;
   3740                 }
   3741             }
   3742             int debugFlags = 0;
   3743             if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
   3744                 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
   3745                 // Also turn on CheckJNI for debuggable apps. It's quite
   3746                 // awkward to turn on otherwise.
   3747                 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
   3748             }
   3749             // Run the app in safe mode if its manifest requests so or the
   3750             // system is booted in safe mode.
   3751             if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
   3752                 mSafeMode == true) {
   3753                 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
   3754             }
   3755             if ("1".equals(SystemProperties.get("debug.checkjni"))) {
   3756                 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
   3757             }
   3758             String genDebugInfoProperty = SystemProperties.get("debug.generate-debug-info");
   3759             if ("true".equals(genDebugInfoProperty)) {
   3760                 debugFlags |= Zygote.DEBUG_GENERATE_DEBUG_INFO;
   3761             }
   3762             if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
   3763                 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
   3764             }
   3765             if ("1".equals(SystemProperties.get("debug.assert"))) {
   3766                 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
   3767             }
   3768             if (mNativeDebuggingApp != null && mNativeDebuggingApp.equals(app.processName)) {
   3769                 // Enable all debug flags required by the native debugger.
   3770                 debugFlags |= Zygote.DEBUG_ALWAYS_JIT;          // Don't interpret anything
   3771                 debugFlags |= Zygote.DEBUG_GENERATE_DEBUG_INFO; // Generate debug info
   3772                 debugFlags |= Zygote.DEBUG_NATIVE_DEBUGGABLE;   // Disbale optimizations
   3773                 mNativeDebuggingApp = null;
   3774             }
   3775 
   3776             String requiredAbi = (abiOverride != null) ? abiOverride : app.info.primaryCpuAbi;
   3777             if (requiredAbi == null) {
   3778                 requiredAbi = Build.SUPPORTED_ABIS[0];
   3779             }
   3780 
   3781             String instructionSet = null;
   3782             if (app.info.primaryCpuAbi != null) {
   3783                 instructionSet = VMRuntime.getInstructionSet(app.info.primaryCpuAbi);
   3784             }
   3785 
   3786             app.gids = gids;
   3787             app.requiredAbi = requiredAbi;
   3788             app.instructionSet = instructionSet;
   3789 
   3790             // Start the process.  It will either succeed and return a result containing
   3791             // the PID of the new process, or else throw a RuntimeException.
   3792             boolean isActivityProcess = (entryPoint == null);
   3793             if (entryPoint == null) entryPoint = "android.app.ActivityThread";
   3794             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " +
   3795                     app.processName);
   3796             checkTime(startTime, "startProcess: asking zygote to start proc");
   3797             Process.ProcessStartResult startResult = Process.start(entryPoint,
   3798                     app.processName, uid, uid, gids, debugFlags, mountExternal,
   3799                     app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet,
   3800                     app.info.dataDir, entryPointArgs);
   3801             checkTime(startTime, "startProcess: returned from zygote!");
   3802             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
   3803 
   3804             mBatteryStatsService.noteProcessStart(app.processName, app.info.uid);
   3805             checkTime(startTime, "startProcess: done updating battery stats");
   3806 
   3807             EventLog.writeEvent(EventLogTags.AM_PROC_START,
   3808                     UserHandle.getUserId(uid), startResult.pid, uid,
   3809                     app.processName, hostingType,
   3810                     hostingNameStr != null ? hostingNameStr : "");
   3811 
   3812             try {
   3813                 AppGlobals.getPackageManager().logAppProcessStartIfNeeded(app.processName, app.uid,
   3814                         app.info.seinfo, app.info.sourceDir, startResult.pid);
   3815             } catch (RemoteException ex) {
   3816                 // Ignore
   3817             }
   3818 
   3819             if (app.persistent) {
   3820                 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
   3821             }
   3822 
   3823             checkTime(startTime, "startProcess: building log message");
   3824             StringBuilder buf = mStringBuilder;
   3825             buf.setLength(0);
   3826             buf.append("Start proc ");
   3827             buf.append(startResult.pid);
   3828             buf.append(':');
   3829             buf.append(app.processName);
   3830             buf.append('/');
   3831             UserHandle.formatUid(buf, uid);
   3832             if (!isActivityProcess) {
   3833                 buf.append(" [");
   3834                 buf.append(entryPoint);
   3835                 buf.append("]");
   3836             }
   3837             buf.append(" for ");
   3838             buf.append(hostingType);
   3839             if (hostingNameStr != null) {
   3840                 buf.append(" ");
   3841                 buf.append(hostingNameStr);
   3842             }
   3843             Slog.i(TAG, buf.toString());
   3844             app.setPid(startResult.pid);
   3845             app.usingWrapper = startResult.usingWrapper;
   3846             app.removed = false;
   3847             app.killed = false;
   3848             app.killedByAm = false;
   3849             checkTime(startTime, "startProcess: starting to update pids map");
   3850             ProcessRecord oldApp;
   3851             synchronized (mPidsSelfLocked) {
   3852                 oldApp = mPidsSelfLocked.get(startResult.pid);
   3853             }
   3854             // If there is already an app occupying that pid that hasn't been cleaned up
   3855             if (oldApp != null && !app.isolated) {
   3856                 // Clean up anything relating to this pid first
   3857                 Slog.w(TAG, "Reusing pid " + startResult.pid
   3858                         + " while app is still mapped to it");
   3859                 cleanUpApplicationRecordLocked(oldApp, false, false, -1,
   3860                         true /*replacingPid*/);
   3861             }
   3862             synchronized (mPidsSelfLocked) {
   3863                 this.mPidsSelfLocked.put(startResult.pid, app);
   3864                 if (isActivityProcess) {
   3865                     Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
   3866                     msg.obj = app;
   3867                     mHandler.sendMessageDelayed(msg, startResult.usingWrapper
   3868                             ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
   3869                 }
   3870             }
   3871             checkTime(startTime, "startProcess: done updating pids map");
   3872         } catch (RuntimeException e) {
   3873             Slog.e(TAG, "Failure starting process " + app.processName, e);
   3874 
   3875             // Something went very wrong while trying to start this process; one
   3876             // common case is when the package is frozen due to an active
   3877             // upgrade. To recover, clean up any active bookkeeping related to
   3878             // starting this process. (We already invoked this method once when
   3879             // the package was initially frozen through KILL_APPLICATION_MSG, so
   3880             // it doesn't hurt to use it again.)
   3881             forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid), false,
   3882                     false, true, false, false, UserHandle.getUserId(app.userId), "start failure");
   3883         }
   3884     }
   3885 
   3886     void updateUsageStats(ActivityRecord component, boolean resumed) {
   3887         if (DEBUG_SWITCH) Slog.d(TAG_SWITCH,
   3888                 "updateUsageStats: comp=" + component + "res=" + resumed);
   3889         final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
   3890         if (resumed) {
   3891             if (mUsageStatsService != null) {
   3892                 mUsageStatsService.reportEvent(component.realActivity, component.userId,
   3893                         UsageEvents.Event.MOVE_TO_FOREGROUND);
   3894             }
   3895             synchronized (stats) {
   3896                 stats.noteActivityResumedLocked(component.app.uid);
   3897             }
   3898         } else {
   3899             if (mUsageStatsService != null) {
   3900                 mUsageStatsService.reportEvent(component.realActivity, component.userId,
   3901                         UsageEvents.Event.MOVE_TO_BACKGROUND);
   3902             }
   3903             synchronized (stats) {
   3904                 stats.noteActivityPausedLocked(component.app.uid);
   3905             }
   3906         }
   3907     }
   3908 
   3909     Intent getHomeIntent() {
   3910         Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
   3911         intent.setComponent(mTopComponent);
   3912         intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
   3913         if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
   3914             intent.addCategory(Intent.CATEGORY_HOME);
   3915         }
   3916         return intent;
   3917     }
   3918 
   3919     boolean startHomeActivityLocked(int userId, String reason) {
   3920         if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
   3921                 && mTopAction == null) {
   3922             // We are running in factory test mode, but unable to find
   3923             // the factory test app, so just sit around displaying the
   3924             // error message and don't try to start anything.
   3925             return false;
   3926         }
   3927         Intent intent = getHomeIntent();
   3928         ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
   3929         if (aInfo != null) {
   3930             intent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
   3931             // Don't do this if the home app is currently being
   3932             // instrumented.
   3933             aInfo = new ActivityInfo(aInfo);
   3934             aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
   3935             ProcessRecord app = getProcessRecordLocked(aInfo.processName,
   3936                     aInfo.applicationInfo.uid, true);
   3937             if (app == null || app.instrumentationClass == null) {
   3938                 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
   3939                 mActivityStarter.startHomeActivityLocked(intent, aInfo, reason);
   3940             }
   3941         } else {
   3942             Slog.wtf(TAG, "No home screen found for " + intent, new Throwable());
   3943         }
   3944 
   3945         return true;
   3946     }
   3947 
   3948     private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
   3949         ActivityInfo ai = null;
   3950         ComponentName comp = intent.getComponent();
   3951         try {
   3952             if (comp != null) {
   3953                 // Factory test.
   3954                 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
   3955             } else {
   3956                 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
   3957                         intent,
   3958                         intent.resolveTypeIfNeeded(mContext.getContentResolver()),
   3959                         flags, userId);
   3960 
   3961                 if (info != null) {
   3962                     ai = info.activityInfo;
   3963                 }
   3964             }
   3965         } catch (RemoteException e) {
   3966             // ignore
   3967         }
   3968 
   3969         return ai;
   3970     }
   3971 
   3972     /**
   3973      * Starts the "new version setup screen" if appropriate.
   3974      */
   3975     void startSetupActivityLocked() {
   3976         // Only do this once per boot.
   3977         if (mCheckedForSetup) {
   3978             return;
   3979         }
   3980 
   3981         // We will show this screen if the current one is a different
   3982         // version than the last one shown, and we are not running in
   3983         // low-level factory test mode.
   3984         final ContentResolver resolver = mContext.getContentResolver();
   3985         if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL &&
   3986                 Settings.Global.getInt(resolver,
   3987                         Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
   3988             mCheckedForSetup = true;
   3989 
   3990             // See if we should be showing the platform update setup UI.
   3991             final Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
   3992             final List<ResolveInfo> ris = mContext.getPackageManager().queryIntentActivities(intent,
   3993                     PackageManager.MATCH_SYSTEM_ONLY | PackageManager.GET_META_DATA);
   3994             if (!ris.isEmpty()) {
   3995                 final ResolveInfo ri = ris.get(0);
   3996                 String vers = ri.activityInfo.metaData != null
   3997                         ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
   3998                         : null;
   3999                 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
   4000                     vers = ri.activityInfo.applicationInfo.metaData.getString(
   4001                             Intent.METADATA_SETUP_VERSION);
   4002                 }
   4003                 String lastVers = Settings.Secure.getString(
   4004                         resolver, Settings.Secure.LAST_SETUP_SHOWN);
   4005                 if (vers != null && !vers.equals(lastVers)) {
   4006                     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   4007                     intent.setComponent(new ComponentName(
   4008                             ri.activityInfo.packageName, ri.activityInfo.name));
   4009                     mActivityStarter.startActivityLocked(null, intent, null /*ephemeralIntent*/,
   4010                             null, ri.activityInfo, null /*rInfo*/, null, null, null, null, 0, 0, 0,
   4011                             null, 0, 0, 0, null, false, false, null, null, null);
   4012                 }
   4013             }
   4014         }
   4015     }
   4016 
   4017     CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
   4018         return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
   4019     }
   4020 
   4021     void enforceNotIsolatedCaller(String caller) {
   4022         if (UserHandle.isIsolated(Binder.getCallingUid())) {
   4023             throw new SecurityException("Isolated process not allowed to call " + caller);
   4024         }
   4025     }
   4026 
   4027     void enforceShellRestriction(String restriction, int userHandle) {
   4028         if (Binder.getCallingUid() == Process.SHELL_UID) {
   4029             if (userHandle < 0 || mUserController.hasUserRestriction(restriction, userHandle)) {
   4030                 throw new SecurityException("Shell does not have permission to access user "
   4031                         + userHandle);
   4032             }
   4033         }
   4034     }
   4035 
   4036     @Override
   4037     public int getFrontActivityScreenCompatMode() {
   4038         enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
   4039         synchronized (this) {
   4040             return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
   4041         }
   4042     }
   4043 
   4044     @Override
   4045     public void setFrontActivityScreenCompatMode(int mode) {
   4046         enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
   4047                 "setFrontActivityScreenCompatMode");
   4048         synchronized (this) {
   4049             mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
   4050         }
   4051     }
   4052 
   4053     @Override
   4054     public int getPackageScreenCompatMode(String packageName) {
   4055         enforceNotIsolatedCaller("getPackageScreenCompatMode");
   4056         synchronized (this) {
   4057             return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
   4058         }
   4059     }
   4060 
   4061     @Override
   4062     public void setPackageScreenCompatMode(String packageName, int mode) {
   4063         enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
   4064                 "setPackageScreenCompatMode");
   4065         synchronized (this) {
   4066             mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
   4067         }
   4068     }
   4069 
   4070     @Override
   4071     public boolean getPackageAskScreenCompat(String packageName) {
   4072         enforceNotIsolatedCaller("getPackageAskScreenCompat");
   4073         synchronized (this) {
   4074             return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
   4075         }
   4076     }
   4077 
   4078     @Override
   4079     public void setPackageAskScreenCompat(String packageName, boolean ask) {
   4080         enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
   4081                 "setPackageAskScreenCompat");
   4082         synchronized (this) {
   4083             mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
   4084         }
   4085     }
   4086 
   4087     private boolean hasUsageStatsPermission(String callingPackage) {
   4088         final int mode = mAppOpsService.checkOperation(AppOpsManager.OP_GET_USAGE_STATS,
   4089                 Binder.getCallingUid(), callingPackage);
   4090         if (mode == AppOpsManager.MODE_DEFAULT) {
   4091             return checkCallingPermission(Manifest.permission.PACKAGE_USAGE_STATS)
   4092                     == PackageManager.PERMISSION_GRANTED;
   4093         }
   4094         return mode == AppOpsManager.MODE_ALLOWED;
   4095     }
   4096 
   4097     @Override
   4098     public int getPackageProcessState(String packageName, String callingPackage) {
   4099         if (!hasUsageStatsPermission(callingPackage)) {
   4100             enforceCallingPermission(android.Manifest.permission.GET_PACKAGE_IMPORTANCE,
   4101                     "getPackageProcessState");
   4102         }
   4103 
   4104         int procState = ActivityManager.PROCESS_STATE_NONEXISTENT;
   4105         synchronized (this) {
   4106             for (int i=mLruProcesses.size()-1; i>=0; i--) {
   4107                 final ProcessRecord proc = mLruProcesses.get(i);
   4108                 if (procState == ActivityManager.PROCESS_STATE_NONEXISTENT
   4109                         || procState > proc.setProcState) {
   4110                     boolean found = false;
   4111                     for (int j=proc.pkgList.size()-1; j>=0 && !found; j--) {
   4112                         if (proc.pkgList.keyAt(j).equals(packageName)) {
   4113                             procState = proc.setProcState;
   4114                             found = true;
   4115                         }
   4116                     }
   4117                     if (proc.pkgDeps != null && !found) {
   4118                         for (int j=proc.pkgDeps.size()-1; j>=0; j--) {
   4119                             if (proc.pkgDeps.valueAt(j).equals(packageName)) {
   4120                                 procState = proc.setProcState;
   4121                                 break;
   4122                             }
   4123                         }
   4124                     }
   4125                 }
   4126             }
   4127         }
   4128         return procState;
   4129     }
   4130 
   4131     @Override
   4132     public boolean setProcessMemoryTrimLevel(String process, int userId, int level) {
   4133         synchronized (this) {
   4134             final ProcessRecord app = findProcessLocked(process, userId, "setProcessMemoryTrimLevel");
   4135             if (app == null) {
   4136                 return false;
   4137             }
   4138             if (app.trimMemoryLevel < level && app.thread != null &&
   4139                     (level < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN ||
   4140                             app.curProcState >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND)) {
   4141                 try {
   4142                     app.thread.scheduleTrimMemory(level);
   4143                     app.trimMemoryLevel = level;
   4144                     return true;
   4145                 } catch (RemoteException e) {
   4146                     // Fallthrough to failure case.
   4147                 }
   4148             }
   4149         }
   4150         return false;
   4151     }
   4152 
   4153     private void dispatchProcessesChanged() {
   4154         int N;
   4155         synchronized (this) {
   4156             N = mPendingProcessChanges.size();
   4157             if (mActiveProcessChanges.length < N) {
   4158                 mActiveProcessChanges = new ProcessChangeItem[N];
   4159             }
   4160             mPendingProcessChanges.toArray(mActiveProcessChanges);
   4161             mPendingProcessChanges.clear();
   4162             if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
   4163                     "*** Delivering " + N + " process changes");
   4164         }
   4165 
   4166         int i = mProcessObservers.beginBroadcast();
   4167         while (i > 0) {
   4168             i--;
   4169             final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
   4170             if (observer != null) {
   4171                 try {
   4172                     for (int j=0; j<N; j++) {
   4173                         ProcessChangeItem item = mActiveProcessChanges[j];
   4174                         if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
   4175                             if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
   4176                                     "ACTIVITIES CHANGED pid=" + item.pid + " uid="
   4177                                     + item.uid + ": " + item.foregroundActivities);
   4178                             observer.onForegroundActivitiesChanged(item.pid, item.uid,
   4179                                     item.foregroundActivities);
   4180                         }
   4181                         if ((item.changes&ProcessChangeItem.CHANGE_PROCESS_STATE) != 0) {
   4182                             if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
   4183                                     "PROCSTATE CHANGED pid=" + item.pid + " uid=" + item.uid
   4184                                     + ": " + item.processState);
   4185                             observer.onProcessStateChanged(item.pid, item.uid, item.processState);
   4186                         }
   4187                     }
   4188                 } catch (RemoteException e) {
   4189                 }
   4190             }
   4191         }
   4192         mProcessObservers.finishBroadcast();
   4193 
   4194         synchronized (this) {
   4195             for (int j=0; j<N; j++) {
   4196                 mAvailProcessChanges.add(mActiveProcessChanges[j]);
   4197             }
   4198         }
   4199     }
   4200 
   4201     private void dispatchProcessDied(int pid, int uid) {
   4202         int i = mProcessObservers.beginBroadcast();
   4203         while (i > 0) {
   4204             i--;
   4205             final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
   4206             if (observer != null) {
   4207                 try {
   4208                     observer.onProcessDied(pid, uid);
   4209                 } catch (RemoteException e) {
   4210                 }
   4211             }
   4212         }
   4213         mProcessObservers.finishBroadcast();
   4214     }
   4215 
   4216     private void dispatchUidsChanged() {
   4217         int N;
   4218         synchronized (this) {
   4219             N = mPendingUidChanges.size();
   4220             if (mActiveUidChanges.length < N) {
   4221                 mActiveUidChanges = new UidRecord.ChangeItem[N];
   4222             }
   4223             for (int i=0; i<N; i++) {
   4224                 final UidRecord.ChangeItem change = mPendingUidChanges.get(i);
   4225                 mActiveUidChanges[i] = change;
   4226                 if (change.uidRecord != null) {
   4227                     change.uidRecord.pendingChange = null;
   4228                     change.uidRecord = null;
   4229                 }
   4230             }
   4231             mPendingUidChanges.clear();
   4232             if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
   4233                     "*** Delivering " + N + " uid changes");
   4234         }
   4235 
   4236         if (mLocalPowerManager != null) {
   4237             for (int j=0; j<N; j++) {
   4238                 UidRecord.ChangeItem item = mActiveUidChanges[j];
   4239                 if (item.change == UidRecord.CHANGE_GONE
   4240                         || item.change == UidRecord.CHANGE_GONE_IDLE) {
   4241                     mLocalPowerManager.uidGone(item.uid);
   4242                 } else {
   4243                     mLocalPowerManager.updateUidProcState(item.uid, item.processState);
   4244                 }
   4245             }
   4246         }
   4247 
   4248         int i = mUidObservers.beginBroadcast();
   4249         while (i > 0) {
   4250             i--;
   4251             final IUidObserver observer = mUidObservers.getBroadcastItem(i);
   4252             final int which = (Integer)mUidObservers.getBroadcastCookie(i);
   4253             if (observer != null) {
   4254                 try {
   4255                     for (int j=0; j<N; j++) {
   4256                         UidRecord.ChangeItem item = mActiveUidChanges[j];
   4257                         final int change = item.change;
   4258                         UidRecord validateUid = null;
   4259                         if (VALIDATE_UID_STATES && i == 0) {
   4260                             validateUid = mValidateUids.get(item.uid);
   4261                             if (validateUid == null && change != UidRecord.CHANGE_GONE
   4262                                     && change != UidRecord.CHANGE_GONE_IDLE) {
   4263                                 validateUid = new UidRecord(item.uid);
   4264                                 mValidateUids.put(item.uid, validateUid);
   4265                             }
   4266                         }
   4267                         if (change == UidRecord.CHANGE_IDLE
   4268                                 || change == UidRecord.CHANGE_GONE_IDLE) {
   4269                             if ((which & ActivityManager.UID_OBSERVER_IDLE) != 0) {
   4270                                 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
   4271                                         "UID idle uid=" + item.uid);
   4272                                 observer.onUidIdle(item.uid);
   4273                             }
   4274                             if (VALIDATE_UID_STATES && i == 0) {
   4275                                 if (validateUid != null) {
   4276                                     validateUid.idle = true;
   4277                                 }
   4278                             }
   4279                         } else if (change == UidRecord.CHANGE_ACTIVE) {
   4280                             if ((which & ActivityManager.UID_OBSERVER_ACTIVE) != 0) {
   4281                                 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
   4282                                         "UID active uid=" + item.uid);
   4283                                 observer.onUidActive(item.uid);
   4284                             }
   4285                             if (VALIDATE_UID_STATES && i == 0) {
   4286                                 validateUid.idle = false;
   4287                             }
   4288                         }
   4289                         if (change == UidRecord.CHANGE_GONE
   4290                                 || change == UidRecord.CHANGE_GONE_IDLE) {
   4291                             if ((which & ActivityManager.UID_OBSERVER_GONE) != 0) {
   4292                                 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
   4293                                         "UID gone uid=" + item.uid);
   4294                                 observer.onUidGone(item.uid);
   4295                             }
   4296                             if (VALIDATE_UID_STATES && i == 0) {
   4297                                 if (validateUid != null) {
   4298                                     mValidateUids.remove(item.uid);
   4299                                 }
   4300                             }
   4301                         } else {
   4302                             if ((which & ActivityManager.UID_OBSERVER_PROCSTATE) != 0) {
   4303                                 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
   4304                                         "UID CHANGED uid=" + item.uid
   4305                                                 + ": " + item.processState);
   4306                                 observer.onUidStateChanged(item.uid, item.processState);
   4307                             }
   4308                             if (VALIDATE_UID_STATES && i == 0) {
   4309                                 validateUid.curProcState = validateUid.setProcState
   4310                                         = item.processState;
   4311                             }
   4312                         }
   4313                     }
   4314                 } catch (RemoteException e) {
   4315                 }
   4316             }
   4317         }
   4318         mUidObservers.finishBroadcast();
   4319 
   4320         synchronized (this) {
   4321             for (int j=0; j<N; j++) {
   4322                 mAvailUidChanges.add(mActiveUidChanges[j]);
   4323             }
   4324         }
   4325     }
   4326 
   4327     @Override
   4328     public final int startActivity(IApplicationThread caller, String callingPackage,
   4329             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
   4330             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
   4331         return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
   4332                 resultWho, requestCode, startFlags, profilerInfo, bOptions,
   4333                 UserHandle.getCallingUserId());
   4334     }
   4335 
   4336     final int startActivity(Intent intent, ActivityStackSupervisor.ActivityContainer container) {
   4337         enforceNotIsolatedCaller("ActivityContainer.startActivity");
   4338         final int userId = mUserController.handleIncomingUser(Binder.getCallingPid(),
   4339                 Binder.getCallingUid(), mStackSupervisor.mCurrentUser, false,
   4340                 ActivityManagerService.ALLOW_FULL_ONLY, "ActivityContainer", null);
   4341 
   4342         // TODO: Switch to user app stacks here.
   4343         String mimeType = intent.getType();
   4344         final Uri data = intent.getData();
   4345         if (mimeType == null && data != null && "content".equals(data.getScheme())) {
   4346             mimeType = getProviderMimeType(data, userId);
   4347         }
   4348         container.checkEmbeddedAllowedInner(userId, intent, mimeType);
   4349 
   4350         intent.addFlags(FORCE_NEW_TASK_FLAGS);
   4351         return mActivityStarter.startActivityMayWait(null, -1, null, intent, mimeType, null, null, null,
   4352                 null, 0, 0, null, null, null, null, false, userId, container, null);
   4353     }
   4354 
   4355     @Override
   4356     public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
   4357             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
   4358             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
   4359         enforceNotIsolatedCaller("startActivity");
   4360         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
   4361                 userId, false, ALLOW_FULL_ONLY, "startActivity", null);
   4362         // TODO: Switch to user app stacks here.
   4363         return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
   4364                 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
   4365                 profilerInfo, null, null, bOptions, false, userId, null, null);
   4366     }
   4367 
   4368     @Override
   4369     public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
   4370             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
   4371             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, boolean ignoreTargetSecurity,
   4372             int userId) {
   4373 
   4374         // This is very dangerous -- it allows you to perform a start activity (including
   4375         // permission grants) as any app that may launch one of your own activities.  So
   4376         // we will only allow this to be done from activities that are part of the core framework,
   4377         // and then only when they are running as the system.
   4378         final ActivityRecord sourceRecord;
   4379         final int targetUid;
   4380         final String targetPackage;
   4381         synchronized (this) {
   4382             if (resultTo == null) {
   4383                 throw new SecurityException("Must be called from an activity");
   4384             }
   4385             sourceRecord = mStackSupervisor.isInAnyStackLocked(resultTo);
   4386             if (sourceRecord == null) {
   4387                 throw new SecurityException("Called with bad activity token: " + resultTo);
   4388             }
   4389             if (!sourceRecord.info.packageName.equals("android")) {
   4390                 throw new SecurityException(
   4391                         "Must be called from an activity that is declared in the android package");
   4392             }
   4393             if (sourceRecord.app == null) {
   4394                 throw new SecurityException("Called without a process attached to activity");
   4395             }
   4396             if (UserHandle.getAppId(sourceRecord.app.uid) != Process.SYSTEM_UID) {
   4397                 // This is still okay, as long as this activity is running under the
   4398                 // uid of the original calling activity.
   4399                 if (sourceRecord.app.uid != sourceRecord.launchedFromUid) {
   4400                     throw new SecurityException(
   4401                             "Calling activity in uid " + sourceRecord.app.uid
   4402                                     + " must be system uid or original calling uid "
   4403                                     + sourceRecord.launchedFromUid);
   4404                 }
   4405             }
   4406             if (ignoreTargetSecurity) {
   4407                 if (intent.getComponent() == null) {
   4408                     throw new SecurityException(
   4409                             "Component must be specified with ignoreTargetSecurity");
   4410                 }
   4411                 if (intent.getSelector() != null) {
   4412                     throw new SecurityException(
   4413                             "Selector not allowed with ignoreTargetSecurity");
   4414                 }
   4415             }
   4416             targetUid = sourceRecord.launchedFromUid;
   4417             targetPackage = sourceRecord.launchedFromPackage;
   4418         }
   4419 
   4420         if (userId == UserHandle.USER_NULL) {
   4421             userId = UserHandle.getUserId(sourceRecord.app.uid);
   4422         }
   4423 
   4424         // TODO: Switch to user app stacks here.
   4425         try {
   4426             int ret = mActivityStarter.startActivityMayWait(null, targetUid, targetPackage, intent,
   4427                     resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, null,
   4428                     null, null, bOptions, ignoreTargetSecurity, userId, null, null);
   4429             return ret;
   4430         } catch (SecurityException e) {
   4431             // XXX need to figure out how to propagate to original app.
   4432             // A SecurityException here is generally actually a fault of the original
   4433             // calling activity (such as a fairly granting permissions), so propagate it
   4434             // back to them.
   4435             /*
   4436             StringBuilder msg = new StringBuilder();
   4437             msg.append("While launching");
   4438             msg.append(intent.toString());
   4439             msg.append(": ");
   4440             msg.append(e.getMessage());
   4441             */
   4442             throw e;
   4443         }
   4444     }
   4445 
   4446     @Override
   4447     public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
   4448             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
   4449             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
   4450         enforceNotIsolatedCaller("startActivityAndWait");
   4451         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
   4452                 userId, false, ALLOW_FULL_ONLY, "startActivityAndWait", null);
   4453         WaitResult res = new WaitResult();
   4454         // TODO: Switch to user app stacks here.
   4455         mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
   4456                 null, null, resultTo, resultWho, requestCode, startFlags, profilerInfo, res, null,
   4457                 bOptions, false, userId, null, null);
   4458         return res;
   4459     }
   4460 
   4461     @Override
   4462     public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
   4463             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
   4464             int startFlags, Configuration config, Bundle bOptions, int userId) {
   4465         enforceNotIsolatedCaller("startActivityWithConfig");
   4466         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
   4467                 userId, false, ALLOW_FULL_ONLY, "startActivityWithConfig", null);
   4468         // TODO: Switch to user app stacks here.
   4469         int ret = mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
   4470                 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
   4471                 null, null, config, bOptions, false, userId, null, null);
   4472         return ret;
   4473     }
   4474 
   4475     @Override
   4476     public int startActivityIntentSender(IApplicationThread caller, IntentSender intent,
   4477             Intent fillInIntent, String resolvedType, IBinder resultTo, String resultWho,
   4478             int requestCode, int flagsMask, int flagsValues, Bundle bOptions)
   4479             throws TransactionTooLargeException {
   4480         enforceNotIsolatedCaller("startActivityIntentSender");
   4481         // Refuse possible leaked file descriptors
   4482         if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
   4483             throw new IllegalArgumentException("File descriptors passed in Intent");
   4484         }
   4485 
   4486         IIntentSender sender = intent.getTarget();
   4487         if (!(sender instanceof PendingIntentRecord)) {
   4488             throw new IllegalArgumentException("Bad PendingIntent object");
   4489         }
   4490 
   4491         PendingIntentRecord pir = (PendingIntentRecord)sender;
   4492 
   4493         synchronized (this) {
   4494             // If this is coming from the currently resumed activity, it is
   4495             // effectively saying that app switches are allowed at this point.
   4496             final ActivityStack stack = getFocusedStack();
   4497             if (stack.mResumedActivity != null &&
   4498                     stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
   4499                 mAppSwitchesAllowedTime = 0;
   4500             }
   4501         }
   4502         int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
   4503                 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions, null);
   4504         return ret;
   4505     }
   4506 
   4507     @Override
   4508     public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
   4509             Intent intent, String resolvedType, IVoiceInteractionSession session,
   4510             IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
   4511             Bundle bOptions, int userId) {
   4512         if (checkCallingPermission(Manifest.permission.BIND_VOICE_INTERACTION)
   4513                 != PackageManager.PERMISSION_GRANTED) {
   4514             String msg = "Permission Denial: startVoiceActivity() from pid="
   4515                     + Binder.getCallingPid()
   4516                     + ", uid=" + Binder.getCallingUid()
   4517                     + " requires " + android.Manifest.permission.BIND_VOICE_INTERACTION;
   4518             Slog.w(TAG, msg);
   4519             throw new SecurityException(msg);
   4520         }
   4521         if (session == null || interactor == null) {
   4522             throw new NullPointerException("null session or interactor");
   4523         }
   4524         userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
   4525                 ALLOW_FULL_ONLY, "startVoiceActivity", null);
   4526         // TODO: Switch to user app stacks here.
   4527         return mActivityStarter.startActivityMayWait(null, callingUid, callingPackage, intent,
   4528                 resolvedType, session, interactor, null, null, 0, startFlags, profilerInfo, null,
   4529                 null, bOptions, false, userId, null, null);
   4530     }
   4531 
   4532     @Override
   4533     public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options)
   4534             throws RemoteException {
   4535         Slog.i(TAG, "Activity tried to startVoiceInteraction");
   4536         synchronized (this) {
   4537             ActivityRecord activity = getFocusedStack().topActivity();
   4538             if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
   4539                 throw new SecurityException("Only focused activity can call startVoiceInteraction");
   4540             }
   4541             if (mRunningVoice != null || activity.task.voiceSession != null
   4542                     || activity.voiceSession != null) {
   4543                 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
   4544                 return;
   4545             }
   4546             if (activity.pendingVoiceInteractionStart) {
   4547                 Slog.w(TAG, "Pending start of voice interaction already.");
   4548                 return;
   4549             }
   4550             activity.pendingVoiceInteractionStart = true;
   4551         }
   4552         LocalServices.getService(VoiceInteractionManagerInternal.class)
   4553                 .startLocalVoiceInteraction(callingActivity, options);
   4554     }
   4555 
   4556     @Override
   4557     public void stopLocalVoiceInteraction(IBinder callingActivity) throws RemoteException {
   4558         LocalServices.getService(VoiceInteractionManagerInternal.class)
   4559                 .stopLocalVoiceInteraction(callingActivity);
   4560     }
   4561 
   4562     @Override
   4563     public boolean supportsLocalVoiceInteraction() throws RemoteException {
   4564         return LocalServices.getService(VoiceInteractionManagerInternal.class)
   4565                 .supportsLocalVoiceInteraction();
   4566     }
   4567 
   4568     void onLocalVoiceInteractionStartedLocked(IBinder activity,
   4569             IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
   4570         ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
   4571         if (activityToCallback == null) return;
   4572         activityToCallback.setVoiceSessionLocked(voiceSession);
   4573 
   4574         // Inform the activity
   4575         try {
   4576             activityToCallback.app.thread.scheduleLocalVoiceInteractionStarted(activity,
   4577                     voiceInteractor);
   4578             long token = Binder.clearCallingIdentity();
   4579             try {
   4580                 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
   4581             } finally {
   4582                 Binder.restoreCallingIdentity(token);
   4583             }
   4584             // TODO: VI Should we cache the activity so that it's easier to find later
   4585             // rather than scan through all the stacks and activities?
   4586         } catch (RemoteException re) {
   4587             activityToCallback.clearVoiceSessionLocked();
   4588             // TODO: VI Should this terminate the voice session?
   4589         }
   4590     }
   4591 
   4592     @Override
   4593     public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
   4594         synchronized (this) {
   4595             if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
   4596                 if (keepAwake) {
   4597                     mVoiceWakeLock.acquire();
   4598                 } else {
   4599                     mVoiceWakeLock.release();
   4600                 }
   4601             }
   4602         }
   4603     }
   4604 
   4605     @Override
   4606     public boolean startNextMatchingActivity(IBinder callingActivity,
   4607             Intent intent, Bundle bOptions) {
   4608         // Refuse possible leaked file descriptors
   4609         if (intent != null && intent.hasFileDescriptors() == true) {
   4610             throw new IllegalArgumentException("File descriptors passed in Intent");
   4611         }
   4612         ActivityOptions options = ActivityOptions.fromBundle(bOptions);
   4613 
   4614         synchronized (this) {
   4615             final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
   4616             if (r == null) {
   4617                 ActivityOptions.abort(options);
   4618                 return false;
   4619             }
   4620             if (r.app == null || r.app.thread == null) {
   4621                 // The caller is not running...  d'oh!
   4622                 ActivityOptions.abort(options);
   4623                 return false;
   4624             }
   4625             intent = new Intent(intent);
   4626             // The caller is not allowed to change the data.
   4627             intent.setDataAndType(r.intent.getData(), r.intent.getType());
   4628             // And we are resetting to find the next component...
   4629             intent.setComponent(null);
   4630 
   4631             final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
   4632 
   4633             ActivityInfo aInfo = null;
   4634             try {
   4635                 List<ResolveInfo> resolves =
   4636                     AppGlobals.getPackageManager().queryIntentActivities(
   4637                             intent, r.resolvedType,
   4638                             PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
   4639                             UserHandle.getCallingUserId()).getList();
   4640 
   4641                 // Look for the original activity in the list...
   4642                 final int N = resolves != null ? resolves.size() : 0;
   4643                 for (int i=0; i<N; i++) {
   4644                     ResolveInfo rInfo = resolves.get(i);
   4645                     if (rInfo.activityInfo.packageName.equals(r.packageName)
   4646                             && rInfo.activityInfo.name.equals(r.info.name)) {
   4647                         // We found the current one...  the next matching is
   4648                         // after it.
   4649                         i++;
   4650                         if (i<N) {
   4651                             aInfo = resolves.get(i).activityInfo;
   4652                         }
   4653                         if (debug) {
   4654                             Slog.v(TAG, "Next matching activity: found current " + r.packageName
   4655                                     + "/" + r.info.name);
   4656                             Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
   4657                                     ? "null" : aInfo.packageName + "/" + aInfo.name));
   4658                         }
   4659                         break;
   4660                     }
   4661                 }
   4662             } catch (RemoteException e) {
   4663             }
   4664 
   4665             if (aInfo == null) {
   4666                 // Nobody who is next!
   4667                 ActivityOptions.abort(options);
   4668                 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
   4669                 return false;
   4670             }
   4671 
   4672             intent.setComponent(new ComponentName(
   4673                     aInfo.applicationInfo.packageName, aInfo.name));
   4674             intent.setFlags(intent.getFlags()&~(
   4675                     Intent.FLAG_ACTIVITY_FORWARD_RESULT|
   4676                     Intent.FLAG_ACTIVITY_CLEAR_TOP|
   4677                     Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
   4678                     Intent.FLAG_ACTIVITY_NEW_TASK));
   4679 
   4680             // Okay now we need to start the new activity, replacing the
   4681             // currently running activity.  This is a little tricky because
   4682             // we want to start the new one as if the current one is finished,
   4683             // but not finish the current one first so that there is no flicker.
   4684             // And thus...
   4685             final boolean wasFinishing = r.finishing;
   4686             r.finishing = true;
   4687 
   4688             // Propagate reply information over to the new activity.
   4689             final ActivityRecord resultTo = r.resultTo;
   4690             final String resultWho = r.resultWho;
   4691             final int requestCode = r.requestCode;
   4692             r.resultTo = null;
   4693             if (resultTo != null) {
   4694                 resultTo.removeResultsLocked(r, resultWho, requestCode);
   4695             }
   4696 
   4697             final long origId = Binder.clearCallingIdentity();
   4698             int res = mActivityStarter.startActivityLocked(r.app.thread, intent,
   4699                     null /*ephemeralIntent*/, r.resolvedType, aInfo, null /*rInfo*/, null,
   4700                     null, resultTo != null ? resultTo.appToken : null, resultWho, requestCode, -1,
   4701                     r.launchedFromUid, r.launchedFromPackage, -1, r.launchedFromUid, 0, options,
   4702                     false, false, null, null, null);
   4703             Binder.restoreCallingIdentity(origId);
   4704 
   4705             r.finishing = wasFinishing;
   4706             if (res != ActivityManager.START_SUCCESS) {
   4707                 return false;
   4708             }
   4709             return true;
   4710         }
   4711     }
   4712 
   4713     @Override
   4714     public final int startActivityFromRecents(int taskId, Bundle bOptions) {
   4715         if (checkCallingPermission(START_TASKS_FROM_RECENTS) != PackageManager.PERMISSION_GRANTED) {
   4716             String msg = "Permission Denial: startActivityFromRecents called without " +
   4717                     START_TASKS_FROM_RECENTS;
   4718             Slog.w(TAG, msg);
   4719             throw new SecurityException(msg);
   4720         }
   4721         final long origId = Binder.clearCallingIdentity();
   4722         try {
   4723             synchronized (this) {
   4724                 return mStackSupervisor.startActivityFromRecentsInner(taskId, bOptions);
   4725             }
   4726         } finally {
   4727             Binder.restoreCallingIdentity(origId);
   4728         }
   4729     }
   4730 
   4731     final int startActivityInPackage(int uid, String callingPackage,
   4732             Intent intent, String resolvedType, IBinder resultTo,
   4733             String resultWho, int requestCode, int startFlags, Bundle bOptions, int userId,
   4734             IActivityContainer container, TaskRecord inTask) {
   4735 
   4736         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
   4737                 userId, false, ALLOW_FULL_ONLY, "startActivityInPackage", null);
   4738 
   4739         // TODO: Switch to user app stacks here.
   4740         int ret = mActivityStarter.startActivityMayWait(null, uid, callingPackage, intent,
   4741                 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
   4742                 null, null, null, bOptions, false, userId, container, inTask);
   4743         return ret;
   4744     }
   4745 
   4746     @Override
   4747     public final int startActivities(IApplicationThread caller, String callingPackage,
   4748             Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
   4749             int userId) {
   4750         enforceNotIsolatedCaller("startActivities");
   4751         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
   4752                 userId, false, ALLOW_FULL_ONLY, "startActivity", null);
   4753         // TODO: Switch to user app stacks here.
   4754         int ret = mActivityStarter.startActivities(caller, -1, callingPackage, intents,
   4755                 resolvedTypes, resultTo, bOptions, userId);
   4756         return ret;
   4757     }
   4758 
   4759     final int startActivitiesInPackage(int uid, String callingPackage,
   4760             Intent[] intents, String[] resolvedTypes, IBinder resultTo,
   4761             Bundle bOptions, int userId) {
   4762 
   4763         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
   4764                 userId, false, ALLOW_FULL_ONLY, "startActivityInPackage", null);
   4765         // TODO: Switch to user app stacks here.
   4766         int ret = mActivityStarter.startActivities(null, uid, callingPackage, intents, resolvedTypes,
   4767                 resultTo, bOptions, userId);
   4768         return ret;
   4769     }
   4770 
   4771     @Override
   4772     public void reportActivityFullyDrawn(IBinder token) {
   4773         synchronized (this) {
   4774             ActivityRecord r = ActivityRecord.isInStackLocked(token);
   4775             if (r == null) {
   4776                 return;
   4777             }
   4778             r.reportFullyDrawnLocked();
   4779         }
   4780     }
   4781 
   4782     @Override
   4783     public void setRequestedOrientation(IBinder token, int requestedOrientation) {
   4784         synchronized (this) {
   4785             ActivityRecord r = ActivityRecord.isInStackLocked(token);
   4786             if (r == null) {
   4787                 return;
   4788             }
   4789             TaskRecord task = r.task;
   4790             if (task != null && (!task.mFullscreen || !task.stack.mFullscreen)) {
   4791                 // Fixed screen orientation isn't supported when activities aren't in full screen
   4792                 // mode.
   4793                 return;
   4794             }
   4795             final long origId = Binder.clearCallingIdentity();
   4796             mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
   4797             Configuration config = mWindowManager.updateOrientationFromAppTokens(
   4798                     mConfiguration, r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
   4799             if (config != null) {
   4800                 r.frozenBeforeDestroy = true;
   4801                 if (!updateConfigurationLocked(config, r, false)) {
   4802                     mStackSupervisor.resumeFocusedStackTopActivityLocked();
   4803                 }
   4804             }
   4805             Binder.restoreCallingIdentity(origId);
   4806         }
   4807     }
   4808 
   4809     @Override
   4810     public int getRequestedOrientation(IBinder token) {
   4811         synchronized (this) {
   4812             ActivityRecord r = ActivityRecord.isInStackLocked(token);
   4813             if (r == null) {
   4814                 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
   4815             }
   4816             return mWindowManager.getAppOrientation(r.appToken);
   4817         }
   4818     }
   4819 
   4820     /**
   4821      * This is the internal entry point for handling Activity.finish().
   4822      *
   4823      * @param token The Binder token referencing the Activity we want to finish.
   4824      * @param resultCode Result code, if any, from this Activity.
   4825      * @param resultData Result data (Intent), if any, from this Activity.
   4826      * @param finishTask Whether to finish the task associated with this Activity.
   4827      *
   4828      * @return Returns true if the activity successfully finished, or false if it is still running.
   4829      */
   4830     @Override
   4831     public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
   4832             int finishTask) {
   4833         // Refuse possible leaked file descriptors
   4834         if (resultData != null && resultData.hasFileDescriptors() == true) {
   4835             throw new IllegalArgumentException("File descriptors passed in Intent");
   4836         }
   4837 
   4838         synchronized(this) {
   4839             ActivityRecord r = ActivityRecord.isInStackLocked(token);
   4840             if (r == null) {
   4841                 return true;
   4842             }
   4843             // Keep track of the root activity of the task before we finish it
   4844             TaskRecord tr = r.task;
   4845             ActivityRecord rootR = tr.getRootActivity();
   4846             if (rootR == null) {
   4847                 Slog.w(TAG, "Finishing task with all activities already finished");
   4848             }
   4849             // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
   4850             // finish.
   4851             if (tr.