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