blob: a69b0ee70f4d2f8ccbe8910a492987bed4db2cdb [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 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 android.app;
18
Andrii Kulian88e05cb2017-12-05 17:21:10 -080019import static android.app.servertransaction.ActivityLifecycleItem.ON_CREATE;
20import static android.app.servertransaction.ActivityLifecycleItem.ON_DESTROY;
21import static android.app.servertransaction.ActivityLifecycleItem.ON_PAUSE;
22import static android.app.servertransaction.ActivityLifecycleItem.ON_RESUME;
23import static android.app.servertransaction.ActivityLifecycleItem.ON_START;
24import static android.app.servertransaction.ActivityLifecycleItem.ON_STOP;
25import static android.app.servertransaction.ActivityLifecycleItem.PRE_ON_CREATE;
Andrii Kulianb047b8b2017-02-08 18:38:26 -080026import static android.view.Display.INVALID_DISPLAY;
27
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -070028import android.annotation.NonNull;
29import android.annotation.Nullable;
Dianne Hackborn69c6adc2015-06-02 10:52:59 -070030import android.app.assist.AssistContent;
31import android.app.assist.AssistStructure;
Christopher Tate45281862010-03-05 15:46:30 -080032import android.app.backup.BackupAgent;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080033import android.app.servertransaction.ActivityLifecycleItem.LifecycleState;
Andrii Kulian446e8242017-10-26 15:17:29 -070034import android.app.servertransaction.ActivityResultItem;
35import android.app.servertransaction.ClientTransaction;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080036import android.app.servertransaction.PendingTransactionActions;
37import android.app.servertransaction.PendingTransactionActions.StopInfo;
38import android.app.servertransaction.TransactionExecutor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.BroadcastReceiver;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070040import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.ComponentName;
42import android.content.ContentProvider;
43import android.content.Context;
44import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070045import android.content.IIntentReceiver;
Jesse Hall317fa5a2017-05-23 15:46:55 -070046import android.content.Intent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.content.pm.ActivityInfo;
48import android.content.pm.ApplicationInfo;
49import android.content.pm.IPackageManager;
50import android.content.pm.InstrumentationInfo;
Christopher Tate346acb12012-10-15 19:20:25 -070051import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.content.pm.PackageManager;
Sen Hubde75702010-05-28 01:54:03 -070053import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070054import android.content.pm.ParceledListSlice;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.content.pm.ProviderInfo;
56import android.content.pm.ServiceInfo;
57import android.content.res.AssetManager;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -070058import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.content.res.Configuration;
60import android.content.res.Resources;
Alan Viverettee54d2452015-05-06 10:41:43 -070061import android.content.res.Resources.Theme;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.database.sqlite.SQLiteDatabase;
63import android.database.sqlite.SQLiteDebug;
Vasu Noric3849202010-03-09 10:47:25 -080064import android.database.sqlite.SQLiteDebug.DbStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.graphics.Bitmap;
66import android.graphics.Canvas;
Jeff Brownbd6e1502012-08-28 03:27:37 -070067import android.hardware.display.DisplayManagerGlobal;
Paul Jensene0bef712014-12-10 15:12:18 -050068import android.net.ConnectivityManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070069import android.net.IConnectivityManager;
Paul Jensene0bef712014-12-10 15:12:18 -050070import android.net.Network;
Robert Greenwalt434203a2010-10-11 16:00:27 -070071import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040072import android.net.ProxyInfo;
Jason Monk83520b92014-05-09 15:16:06 -040073import android.net.Uri;
Joe Onoratod630f102011-03-17 18:42:26 -070074import android.os.AsyncTask;
Amith Yamasani742a6712011-05-04 14:49:28 -070075import android.os.Binder;
Jeff Sharkey344744b2016-01-28 19:03:30 -070076import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Bundle;
78import android.os.Debug;
Geremy Condrab7faaf42012-09-19 18:07:42 -070079import android.os.DropBoxManager;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070080import android.os.Environment;
Jesse Hallb12249b2016-12-12 12:53:02 -080081import android.os.GraphicsEnvironment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.Handler;
Jeff Sharkey8439ac02017-12-12 17:26:23 -070083import android.os.HandlerExecutor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.os.IBinder;
Adam Lesinskib61e4052016-05-19 18:23:05 -070085import android.os.LocaleList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.os.Looper;
87import android.os.Message;
88import android.os.MessageQueue;
Dianne Hackbornfabb70b2014-11-11 12:22:36 -080089import android.os.Parcel;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070090import android.os.ParcelFileDescriptor;
Craig Mautnera0026042014-04-23 11:45:37 -070091import android.os.PersistableBundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.os.Process;
93import android.os.RemoteException;
94import android.os.ServiceManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070095import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import android.os.SystemClock;
Jeff Brownefd43bd2012-09-21 17:02:35 -070097import android.os.SystemProperties;
Dianne Hackborn1ded0b12012-04-26 14:14:50 -070098import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070099import android.os.UserHandle;
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600100import android.provider.BlockedNumberContract;
101import android.provider.CalendarContract;
102import android.provider.CallLog;
103import android.provider.ContactsContract;
104import android.provider.Downloads;
Seigo Nonaka54084b62017-04-24 14:46:23 -0700105import android.provider.FontsContract;
Narayan Kamathccb2a0862013-12-19 14:49:36 +0000106import android.provider.Settings;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700107import android.renderscript.RenderScriptCacheDir;
Chad Brubakerc72875b2016-04-27 16:35:11 -0700108import android.security.NetworkSecurityPolicy;
Chad Brubaker78d47122015-11-17 22:26:58 -0800109import android.security.net.config.NetworkSecurityConfigProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.util.AndroidRuntimeException;
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700111import android.util.ArrayMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.util.DisplayMetrics;
113import android.util.EventLog;
114import android.util.Log;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700115import android.util.LogPrinter;
Andrii Kulianb372da62018-01-18 10:46:24 -0800116import android.util.MergedConfiguration;
Craig Mautnereb8abf72014-07-02 15:04:09 -0700117import android.util.Pair;
Jeff Brown6754ba22011-12-14 20:20:01 -0800118import android.util.PrintWriterPrinter;
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800119import android.util.Slog;
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -0700120import android.util.SparseIntArray;
Adam Powell14874662013-07-18 19:42:41 -0700121import android.util.SuperNotCalledException;
Kweku Adams598e9a22017-11-02 17:12:20 -0700122import android.util.proto.ProtoOutputStream;
Adam Lesinski3ad1b482016-04-01 16:41:41 -0700123import android.view.ContextThemeWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import android.view.Display;
John Reck51aaf902015-12-02 15:08:07 -0800125import android.view.ThreadedRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126import android.view.View;
127import android.view.ViewDebug;
128import android.view.ViewManager;
Dianne Hackborn6dd005b2011-07-18 13:22:50 -0700129import android.view.ViewRootImpl;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130import android.view.Window;
131import android.view.WindowManager;
Jeff Brown98365d72012-08-19 20:30:52 -0700132import android.view.WindowManagerGlobal;
Richard Uhler2c036192016-09-14 09:48:31 +0100133import android.webkit.WebView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700135import com.android.internal.annotations.GuardedBy;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800136import com.android.internal.annotations.VisibleForTesting;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700137import com.android.internal.app.IVoiceInteractor;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800138import com.android.internal.content.ReferrerIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139import com.android.internal.os.BinderInternal;
140import com.android.internal.os.RuntimeInit;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700141import com.android.internal.os.SomeArgs;
Jeff Sharkey3e195892016-03-05 19:48:59 -0700142import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -0700143import com.android.internal.util.FastPrintWriter;
Kenny Root12e75222013-04-23 22:34:24 -0700144import com.android.org.conscrypt.OpenSSLSocketImpl;
Robin Lee3d076af2014-04-25 14:57:49 +0100145import com.android.org.conscrypt.TrustedCertificateStore;
Kweku Adams598e9a22017-11-02 17:12:20 -0700146import com.android.server.am.proto.MemInfoProto;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700147
148import dalvik.system.BaseDexClassLoader;
149import dalvik.system.CloseGuard;
150import dalvik.system.VMDebug;
151import dalvik.system.VMRuntime;
152
Jesse Hall317fa5a2017-05-23 15:46:55 -0700153import libcore.io.DropBox;
154import libcore.io.EventLogger;
155import libcore.io.IoUtils;
156import libcore.net.event.NetworkEventDispatcher;
157
158import org.apache.harmony.dalvik.ddmc.DdmVmInternal;
159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160import java.io.File;
161import java.io.FileDescriptor;
162import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700163import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164import java.io.PrintWriter;
165import java.lang.ref.WeakReference;
Svet Ganov37e43272016-09-09 16:01:32 -0700166import java.lang.reflect.Field;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -0400167import java.lang.reflect.Method;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700168import java.net.InetAddress;
Narayan Kamathccb2a0862013-12-19 14:49:36 +0000169import java.text.DateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170import java.util.ArrayList;
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -0600171import java.util.Arrays;
Bryce Leea33c13d2018-02-08 14:37:06 -0800172import java.util.Iterator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173import java.util.List;
Adam Lesinskib61e4052016-05-19 18:23:05 -0700174import java.util.Locale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175import java.util.Map;
Kenny Roote6585b32013-12-13 12:00:26 -0800176import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177import java.util.TimeZone;
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700178import java.util.concurrent.Executor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700180final class RemoteServiceException extends AndroidRuntimeException {
181 public RemoteServiceException(String msg) {
182 super(msg);
183 }
184}
185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186/**
187 * This manages the execution of the main thread in an
188 * application process, scheduling and executing activities,
189 * broadcasts, and other operations on it as the activity
190 * manager requests.
191 *
192 * {@hide}
193 */
Andrii Kulian446e8242017-10-26 15:17:29 -0700194public final class ActivityThread extends ClientTransactionHandler {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700195 /** @hide */
196 public static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700197 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
Joe Onorato43a17652011-04-06 19:22:23 -0700198 static final boolean localLOGV = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700199 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborne829fef2010-10-26 17:44:01 -0700200 /** @hide */
201 public static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700202 private static final boolean DEBUG_RESULTS = false;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700203 private static final boolean DEBUG_BACKUP = false;
Craig Mautner88c05892013-06-28 09:47:45 -0700204 public static final boolean DEBUG_CONFIGURATION = false;
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800205 private static final boolean DEBUG_SERVICE = false;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800206 public static final boolean DEBUG_MEMORY_TRIM = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700207 private static final boolean DEBUG_PROVIDER = false;
Andrii Kulianb372da62018-01-18 10:46:24 -0800208 public static final boolean DEBUG_ORDER = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
Craig Mautnere3119b72015-01-20 15:02:36 -0800211 private static final int LOG_AM_ON_PAUSE_CALLED = 30021;
212 private static final int LOG_AM_ON_RESUME_CALLED = 30022;
Wale Ogunwalecd7043e2016-02-27 17:37:46 -0800213 private static final int LOG_AM_ON_STOP_CALLED = 30049;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
Dianne Hackborn455625e2015-01-21 09:55:13 -0800215 /** Type for IActivityManager.serviceDoneExecuting: anonymous operation */
216 public static final int SERVICE_DONE_EXECUTING_ANON = 0;
217 /** Type for IActivityManager.serviceDoneExecuting: done with an onStart call */
218 public static final int SERVICE_DONE_EXECUTING_START = 1;
219 /** Type for IActivityManager.serviceDoneExecuting: done stopping (destroying) service */
220 public static final int SERVICE_DONE_EXECUTING_STOP = 2;
221
Filip Gruszczynskica664812015-12-04 12:43:36 -0800222 // Whether to invoke an activity callback after delivering new configuration.
223 private static final boolean REPORT_TO_ACTIVITY = true;
224
Bryce Leed946f862018-01-16 15:59:47 -0800225 // Maximum number of recent tokens to maintain for debugging purposes
Bryce Leea33c13d2018-02-08 14:37:06 -0800226 private static final int MAX_DESTROYED_ACTIVITIES = 10;
Bryce Leed946f862018-01-16 15:59:47 -0800227
Sudheer Shanka84a48952017-03-08 18:19:01 -0800228 /**
229 * Denotes an invalid sequence number corresponding to a process state change.
230 */
231 public static final long INVALID_PROC_STATE_SEQ = -1;
232
Sudheer Shankaf6690102017-10-16 10:20:32 -0700233 /**
234 * Identifier for the sequence no. associated with this process start. It will be provided
235 * as one of the arguments when the process starts.
236 */
237 public static final String PROC_START_SEQ_IDENT = "seq=";
238
Sudheer Shanka84a48952017-03-08 18:19:01 -0800239 private final Object mNetworkPolicyLock = new Object();
240
241 /**
242 * Denotes the sequence number of the process state change for which the main thread needs
243 * to block until the network rules are updated for it.
244 *
245 * Value of {@link #INVALID_PROC_STATE_SEQ} indicates there is no need for blocking.
246 */
247 @GuardedBy("mNetworkPolicyLock")
248 private long mNetworkBlockSeq = INVALID_PROC_STATE_SEQ;
249
Jeff Browndefd4a62014-03-10 21:24:37 -0700250 private ContextImpl mSystemContext;
Adam Lesinskia82b6262017-03-21 16:56:17 -0700251 private ContextImpl mSystemUiContext;
Bob Leee5408332009-09-04 18:31:17 -0700252
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700253 static volatile IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700255 final ApplicationThread mAppThread = new ApplicationThread();
256 final Looper mLooper = Looper.myLooper();
257 final H mH = new H();
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700258 final Executor mExecutor = new HandlerExecutor(mH);
Dianne Hackborn782d4982015-07-08 17:36:37 -0700259 final ArrayMap<IBinder, ActivityClientRecord> mActivities = new ArrayMap<>();
Bryce Leea33c13d2018-02-08 14:37:06 -0800260 final ArrayList<DestroyedActivityInfo> mRecentDestroyedActivities = new ArrayList<>();
Bryce Leed946f862018-01-16 15:59:47 -0800261
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700262 // List of new activities (via ActivityRecord.nextIdle) that should
263 // be reported when next we idle.
264 ActivityClientRecord mNewActivities = null;
265 // Number of activities that are currently visible on-screen.
266 int mNumVisibleActivities = 0;
Amith Yamasani4f128e42016-05-10 11:44:12 -0700267 ArrayList<WeakReference<AssistStructure>> mLastAssistStructures = new ArrayList<>();
268 private int mLastSessionId;
Dianne Hackborn782d4982015-07-08 17:36:37 -0700269 final ArrayMap<IBinder, Service> mServices = new ArrayMap<>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700270 AppBindData mBoundApplication;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700271 Profiler mProfiler;
Dianne Hackborn908aecc2012-07-31 16:37:34 -0700272 int mCurDefaultDisplayDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -0700273 boolean mDensityCompatMode;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700274 Configuration mConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700275 Configuration mCompatConfiguration;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700276 Application mInitialApplication;
277 final ArrayList<Application> mAllApplications
278 = new ArrayList<Application>();
279 // set of instantiated backup agents, keyed by package name
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700280 final ArrayMap<String, BackupAgent> mBackupAgents = new ArrayMap<String, BackupAgent>();
Jeff Sharkey66a017b2013-01-17 18:18:22 -0800281 /** Reference to singleton {@link ActivityThread} */
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700282 private static volatile ActivityThread sCurrentActivityThread;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700283 Instrumentation mInstrumentation;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700284 String mInstrumentationPackageName = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700285 String mInstrumentationAppDir = null;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700286 String[] mInstrumentationSplitAppDirs = null;
287 String mInstrumentationLibDir = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700288 String mInstrumentedAppDir = null;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700289 String[] mInstrumentedSplitAppDirs = null;
290 String mInstrumentedLibDir = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700291 boolean mSystemThread = false;
292 boolean mJitEnabled = false;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700293 boolean mSomeActivitiesChanged = false;
Chong Zhang4951f9d2016-06-23 13:15:08 -0700294 boolean mUpdatingSystemConfig = false;
David Brazdild960cc42018-01-31 07:59:17 +0000295 /* package */ boolean mHiddenApiWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100297 // These can be accessed by multiple threads; mResourcesManager is the lock.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700298 // XXX For now we keep around information about all packages we have
299 // seen, not removing entries from this map.
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800300 // NOTE: The activity and window managers need to call in to
Dianne Hackborn2f0b1752011-05-31 17:59:49 -0700301 // ActivityThread to do things like update resource configurations,
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800302 // which means this lock gets held while the activity and window managers
303 // holds their own lock. Thus you MUST NEVER call back into the activity manager
304 // or window manager or anything that depends on them while holding this lock.
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700305 // These LoadedApk are only valid for the userId that we're running as.
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100306 @GuardedBy("mResourcesManager")
307 final ArrayMap<String, WeakReference<LoadedApk>> mPackages = new ArrayMap<>();
308 @GuardedBy("mResourcesManager")
309 final ArrayMap<String, WeakReference<LoadedApk>> mResourcePackages = new ArrayMap<>();
310 @GuardedBy("mResourcesManager")
311 final ArrayList<ActivityClientRecord> mRelaunchingActivities = new ArrayList<>();
312 @GuardedBy("mResourcesManager")
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700313 Configuration mPendingConfiguration = null;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800314 // An executor that performs multi-step transactions.
315 private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800316
Craig Mautner88c05892013-06-28 09:47:45 -0700317 private final ResourcesManager mResourcesManager;
318
Jeff Sharkey6d515712012-09-20 16:06:08 -0700319 private static final class ProviderKey {
320 final String authority;
321 final int userId;
322
323 public ProviderKey(String authority, int userId) {
324 this.authority = authority;
325 this.userId = userId;
326 }
327
328 @Override
329 public boolean equals(Object o) {
330 if (o instanceof ProviderKey) {
331 final ProviderKey other = (ProviderKey) o;
Kenny Roote6585b32013-12-13 12:00:26 -0800332 return Objects.equals(authority, other.authority) && userId == other.userId;
Jeff Sharkey6d515712012-09-20 16:06:08 -0700333 }
334 return false;
335 }
336
337 @Override
338 public int hashCode() {
339 return ((authority != null) ? authority.hashCode() : 0) ^ userId;
340 }
341 }
342
Bryce Leea33c13d2018-02-08 14:37:06 -0800343 /**
344 * TODO(b/71506345): Remove this once bug is resolved.
345 */
346 private static final class DestroyedActivityInfo {
347 private final Integer mToken;
348 private final String mReason;
349 private final long mTime;
350
351 DestroyedActivityInfo(Integer token, String reason) {
352 mToken = token;
353 mReason = reason;
354 mTime = System.currentTimeMillis();
355 }
356
357 void dump(PrintWriter pw, String prefix) {
358 pw.println(prefix + "[token:" + mToken + " | time:" + mTime + " | reason:" + mReason
359 + "]");
360 }
361 }
362
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700363 // The lock of mProviderMap protects the following variables.
Wale Ogunwale1d646122015-04-24 14:45:14 -0700364 final ArrayMap<ProviderKey, ProviderClientRecord> mProviderMap
365 = new ArrayMap<ProviderKey, ProviderClientRecord>();
366 final ArrayMap<IBinder, ProviderRefCount> mProviderRefCountMap
367 = new ArrayMap<IBinder, ProviderRefCount>();
368 final ArrayMap<IBinder, ProviderClientRecord> mLocalProviders
369 = new ArrayMap<IBinder, ProviderClientRecord>();
370 final ArrayMap<ComponentName, ProviderClientRecord> mLocalProvidersByName
371 = new ArrayMap<ComponentName, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800372
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700373 final ArrayMap<Activity, ArrayList<OnActivityPausedListener>> mOnPauseListeners
Wale Ogunwale1d646122015-04-24 14:45:14 -0700374 = new ArrayMap<Activity, ArrayList<OnActivityPausedListener>>();
Jeff Hamilton52d32032011-01-08 15:31:26 -0600375
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700376 final GcIdler mGcIdler = new GcIdler();
377 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700379 static volatile Handler sMainThreadHandler; // set once in main()
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700380
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800381 Bundle mCoreSettings = null;
382
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800383 /** Activity client record, used for bookkeeping for the real {@link Activity} instance. */
384 public static final class ActivityClientRecord {
385 public IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700386 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 Intent intent;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800388 String referrer;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700389 IVoiceInteractor voiceInteractor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800390 Bundle state;
Craig Mautnera0026042014-04-23 11:45:37 -0700391 PersistableBundle persistentState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 Activity activity;
393 Window window;
394 Activity parent;
395 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700396 Activity.NonConfigurationInstances lastNonConfigurationInstances;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800397 // TODO(lifecycler): Use mLifecycleState instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 boolean paused;
399 boolean stopped;
400 boolean hideForNow;
401 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700402 Configuration createdConfig;
Wale Ogunwale60454db2015-01-23 16:05:07 -0800403 Configuration overrideConfig;
Wale Ogunwalec2607b42015-02-07 16:16:59 -0800404 // Used for consolidating configs before sending on to Activity.
405 private Configuration tmpConfig = new Configuration();
Andrii Kulian44607962017-03-16 11:06:24 -0700406 // Callback used for updating activity override config.
407 ViewRootImpl.ActivityConfigCallback configCallback;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700408 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800409
Jeff Hao1b012d32014-08-20 10:35:34 -0700410 ProfilerInfo profilerInfo;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 ActivityInfo activityInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400413 CompatibilityInfo compatInfo;
Todd Kennedy233a0b12018-01-29 20:30:24 +0000414 public LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800415
416 List<ResultInfo> pendingResults;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800417 List<ReferrerIntent> pendingIntents;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418
419 boolean startsNotResumed;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800420 public final boolean isForward;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800421 int pendingConfigChanges;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800422
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700423 Window mPendingRemoveWindow;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800424 WindowManager mPendingRemoveWindowManager;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700425 boolean mPreserveWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800427 @LifecycleState
428 private int mLifecycleState = PRE_ON_CREATE;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700429
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800430 @VisibleForTesting
431 public ActivityClientRecord() {
432 this.isForward = false;
433 init();
434 }
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700435
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800436 public ActivityClientRecord(IBinder token, Intent intent, int ident,
437 ActivityInfo info, Configuration overrideConfig, CompatibilityInfo compatInfo,
438 String referrer, IVoiceInteractor voiceInteractor, Bundle state,
439 PersistableBundle persistentState, List<ResultInfo> pendingResults,
440 List<ReferrerIntent> pendingNewIntents, boolean isForward,
441 ProfilerInfo profilerInfo, ClientTransactionHandler client) {
442 this.token = token;
443 this.ident = ident;
444 this.intent = intent;
445 this.referrer = referrer;
446 this.voiceInteractor = voiceInteractor;
447 this.activityInfo = info;
448 this.compatInfo = compatInfo;
449 this.state = state;
450 this.persistentState = persistentState;
451 this.pendingResults = pendingResults;
452 this.pendingIntents = pendingNewIntents;
453 this.isForward = isForward;
454 this.profilerInfo = profilerInfo;
455 this.overrideConfig = overrideConfig;
Todd Kennedy233a0b12018-01-29 20:30:24 +0000456 this.packageInfo = client.getPackageInfoNoCheck(activityInfo.applicationInfo,
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800457 compatInfo);
458 init();
459 }
460
461 /** Common initializer for all constructors. */
462 private void init() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 parent = null;
464 embeddedID = null;
465 paused = false;
466 stopped = false;
467 hideForNow = false;
468 nextIdle = null;
Andrii Kulian44607962017-03-16 11:06:24 -0700469 configCallback = (Configuration overrideConfig, int newDisplayId) -> {
470 if (activity == null) {
471 throw new IllegalStateException(
472 "Received config update for non-existing activity");
473 }
Andrii Kulian446e8242017-10-26 15:17:29 -0700474 activity.mMainThread.handleActivityConfigurationChanged(token, overrideConfig,
475 newDisplayId);
Andrii Kulian44607962017-03-16 11:06:24 -0700476 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 }
478
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800479 /** Get the current lifecycle state. */
480 public int getLifecycleState() {
481 return mLifecycleState;
482 }
483
484 /** Update the current lifecycle state for internal bookkeeping. */
485 public void setState(@LifecycleState int newLifecycleState) {
486 mLifecycleState = newLifecycleState;
487 switch (mLifecycleState) {
488 case ON_CREATE:
489 paused = true;
490 stopped = true;
491 break;
492 case ON_START:
493 paused = true;
494 stopped = false;
495 break;
496 case ON_RESUME:
497 paused = false;
498 stopped = false;
499 break;
500 case ON_PAUSE:
501 paused = true;
502 stopped = false;
503 break;
504 case ON_STOP:
505 paused = true;
506 stopped = true;
507 break;
508 }
509 }
510
Andrii Kulian391161f2018-01-29 10:50:02 -0800511 private boolean isPreHoneycomb() {
512 return activity != null && activity.getApplicationInfo().targetSdkVersion
513 < android.os.Build.VERSION_CODES.HONEYCOMB;
514 }
515
516 private boolean isPreP() {
517 return activity != null && activity.getApplicationInfo().targetSdkVersion
518 < android.os.Build.VERSION_CODES.P;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800519 }
520
Craig Mautnera0026042014-04-23 11:45:37 -0700521 public boolean isPersistable() {
Craig Mautner43e52ed2014-06-16 17:18:52 -0700522 return activityInfo.persistableMode == ActivityInfo.PERSIST_ACROSS_REBOOTS;
Craig Mautnera0026042014-04-23 11:45:37 -0700523 }
524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 public String toString() {
Dianne Hackbornb61a0262012-05-14 17:19:18 -0700526 ComponentName componentName = intent != null ? intent.getComponent() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527 return "ActivityRecord{"
528 + Integer.toHexString(System.identityHashCode(this))
529 + " token=" + token + " " + (componentName == null
530 ? "no component name" : componentName.toShortString())
531 + "}";
532 }
Andrii Kulian58178f22016-03-16 13:44:56 -0700533
534 public String getStateString() {
535 StringBuilder sb = new StringBuilder();
536 sb.append("ActivityClientRecord{");
537 sb.append("paused=").append(paused);
538 sb.append(", stopped=").append(stopped);
539 sb.append(", hideForNow=").append(hideForNow);
540 sb.append(", startsNotResumed=").append(startsNotResumed);
541 sb.append(", isForward=").append(isForward);
542 sb.append(", pendingConfigChanges=").append(pendingConfigChanges);
Andrii Kulian58178f22016-03-16 13:44:56 -0700543 sb.append(", preserveWindow=").append(mPreserveWindow);
544 if (activity != null) {
545 sb.append(", Activity{");
546 sb.append("resumed=").append(activity.mResumed);
547 sb.append(", stopped=").append(activity.mStopped);
548 sb.append(", finished=").append(activity.isFinishing());
549 sb.append(", destroyed=").append(activity.isDestroyed());
550 sb.append(", startedActivity=").append(activity.mStartedActivity);
551 sb.append(", temporaryPause=").append(activity.mTemporaryPause);
552 sb.append(", changingConfigurations=").append(activity.mChangingConfigurations);
Andrii Kulian58178f22016-03-16 13:44:56 -0700553 sb.append("}");
554 }
555 sb.append("}");
556 return sb.toString();
557 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558 }
559
Wale Ogunwale1d646122015-04-24 14:45:14 -0700560 final class ProviderClientRecord {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700561 final String[] mNames;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 final IContentProvider mProvider;
563 final ContentProvider mLocalProvider;
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700564 final ContentProviderHolder mHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700566 ProviderClientRecord(String[] names, IContentProvider provider,
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700567 ContentProvider localProvider, ContentProviderHolder holder) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700568 mNames = names;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 mProvider = provider;
570 mLocalProvider = localProvider;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700571 mHolder = holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 }
573 }
574
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400575 static final class ReceiverData extends BroadcastReceiver.PendingResult {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700576 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700577 boolean ordered, boolean sticky, IBinder token, int sendingUser) {
578 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky,
riddle_hsu1f5ac4d2015-01-03 15:38:21 +0800579 token, sendingUser, intent.getFlags());
Dianne Hackborne829fef2010-10-26 17:44:01 -0700580 this.intent = intent;
581 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 Intent intent;
584 ActivityInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400585 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 public String toString() {
587 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700588 info.packageName + " resultCode=" + getResultCode()
589 + " resultData=" + getResultData() + " resultExtras="
590 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 }
592 }
593
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400594 static final class CreateBackupAgentData {
Christopher Tate181fafa2009-05-14 11:12:14 -0700595 ApplicationInfo appInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400596 CompatibilityInfo compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700597 int backupMode;
598 public String toString() {
599 return "CreateBackupAgentData{appInfo=" + appInfo
600 + " backupAgent=" + appInfo.backupAgentName
601 + " mode=" + backupMode + "}";
602 }
603 }
Bob Leee5408332009-09-04 18:31:17 -0700604
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400605 static final class CreateServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 IBinder token;
607 ServiceInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400608 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 Intent intent;
610 public String toString() {
611 return "CreateServiceData{token=" + token + " className="
612 + info.name + " packageName=" + info.packageName
613 + " intent=" + intent + "}";
614 }
615 }
616
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400617 static final class BindServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 IBinder token;
619 Intent intent;
620 boolean rebind;
621 public String toString() {
622 return "BindServiceData{token=" + token + " intent=" + intent + "}";
623 }
624 }
625
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400626 static final class ServiceArgsData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 IBinder token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700628 boolean taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700630 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 Intent args;
632 public String toString() {
633 return "ServiceArgsData{token=" + token + " startId=" + startId
634 + " args=" + args + "}";
635 }
636 }
637
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400638 static final class AppBindData {
Todd Kennedy233a0b12018-01-29 20:30:24 +0000639 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 String processName;
641 ApplicationInfo appInfo;
642 List<ProviderInfo> providers;
643 ComponentName instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 Bundle instrumentationArgs;
645 IInstrumentationWatcher instrumentationWatcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800646 IUiAutomationConnection instrumentationUiAutomationConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 int debugMode;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400648 boolean enableBinderTracking;
Man Caocfa78b22015-06-11 20:14:34 -0700649 boolean trackAllocation;
Christopher Tate181fafa2009-05-14 11:12:14 -0700650 boolean restrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700651 boolean persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 Configuration config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400653 CompatibilityInfo compatInfo;
Svet Ganov37e43272016-09-09 16:01:32 -0700654 String buildSerial;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700655
656 /** Initial values for {@link Profiler}. */
Jeff Hao1b012d32014-08-20 10:35:34 -0700657 ProfilerInfo initProfilerInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700658
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800659 boolean autofillCompatibilityEnabled;
660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 public String toString() {
662 return "AppBindData{appInfo=" + appInfo + "}";
663 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700664 }
665
666 static final class Profiler {
667 String profileFile;
668 ParcelFileDescriptor profileFd;
Jeff Hao1b012d32014-08-20 10:35:34 -0700669 int samplingInterval;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700670 boolean autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800671 boolean streamingOutput;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700672 boolean profiling;
673 boolean handlingProfiling;
Jeff Hao1b012d32014-08-20 10:35:34 -0700674 public void setProfiler(ProfilerInfo profilerInfo) {
675 ParcelFileDescriptor fd = profilerInfo.profileFd;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700676 if (profiling) {
677 if (fd != null) {
678 try {
679 fd.close();
680 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700681 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700682 }
683 }
684 return;
685 }
686 if (profileFd != null) {
687 try {
688 profileFd.close();
689 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700690 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700691 }
692 }
Jeff Hao1b012d32014-08-20 10:35:34 -0700693 profileFile = profilerInfo.profileFile;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700694 profileFd = fd;
Jeff Hao1b012d32014-08-20 10:35:34 -0700695 samplingInterval = profilerInfo.samplingInterval;
696 autoStopProfiler = profilerInfo.autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800697 streamingOutput = profilerInfo.streamingOutput;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700698 }
699 public void startProfiling() {
700 if (profileFd == null || profiling) {
701 return;
702 }
703 try {
Andreas Gampeeff06392016-05-10 12:51:45 -0700704 int bufferSize = SystemProperties.getInt("debug.traceview-buffer-size-mb", 8);
Jeff Hao1b012d32014-08-20 10:35:34 -0700705 VMDebug.startMethodTracing(profileFile, profileFd.getFileDescriptor(),
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800706 bufferSize * 1024 * 1024, 0, samplingInterval != 0, samplingInterval,
707 streamingOutput);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700708 profiling = true;
709 } catch (RuntimeException e) {
710 Slog.w(TAG, "Profiling failed on path " + profileFile);
711 try {
712 profileFd.close();
713 profileFd = null;
714 } catch (IOException e2) {
715 Slog.w(TAG, "Failure closing profile fd", e2);
716 }
717 }
718 }
719 public void stopProfiling() {
720 if (profiling) {
721 profiling = false;
722 Debug.stopMethodTracing();
723 if (profileFd != null) {
724 try {
725 profileFd.close();
726 } catch (IOException e) {
727 }
728 }
729 profileFd = null;
730 profileFile = null;
731 }
732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 }
734
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400735 static final class DumpComponentInfo {
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700736 ParcelFileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700737 IBinder token;
Dianne Hackborn30d71892010-12-11 10:37:55 -0800738 String prefix;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 String[] args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 }
741
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400742 static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800743 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 String what;
745 String who;
746 }
747
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400748 static final class DumpHeapData {
Christopher Ferris8d652f82017-04-11 16:29:18 -0700749 public boolean managed;
750 public boolean mallocInfo;
Makoto Onuki4556b7b2017-07-07 14:58:58 -0700751 public boolean runGc;
Andy McFadden824c5102010-07-09 16:26:57 -0700752 String path;
753 ParcelFileDescriptor fd;
754 }
755
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400756 static final class UpdateCompatibilityData {
757 String pkg;
758 CompatibilityInfo info;
759 }
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800760
Adam Skorydfc7fd72013-08-05 19:23:41 -0700761 static final class RequestAssistContextExtras {
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800762 IBinder activityToken;
763 IBinder requestToken;
764 int requestType;
Amith Yamasani4f128e42016-05-10 11:44:12 -0700765 int sessionId;
Svet Ganovfd31f852017-04-26 15:54:27 -0700766 int flags;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800767 }
Anwar Ghuloum3a8ce1b2013-04-26 16:18:28 -0700768
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700769 private class ApplicationThread extends IApplicationThread.Stub {
Vasu Nori3c7131f2010-09-21 14:36:57 -0700770 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700771
Dianne Hackborna413dc02013-07-12 12:02:55 -0700772 private int mLastProcessState = -1;
773
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700774 private void updatePendingConfiguration(Configuration config) {
Craig Mautner88c05892013-06-28 09:47:45 -0700775 synchronized (mResourcesManager) {
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700776 if (mPendingConfiguration == null ||
777 mPendingConfiguration.isOtherSeqNewer(config)) {
778 mPendingConfiguration = config;
779 }
780 }
781 }
782
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800783 public final void scheduleSleeping(IBinder token, boolean sleeping) {
Jeff Brown9ef09972013-10-15 20:49:59 -0700784 sendMessage(H.SLEEPING, token, sleeping ? 1 : 0);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800785 }
786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 public final void scheduleReceiver(Intent intent, ActivityInfo info,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400788 CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700789 boolean sync, int sendingUser, int processState) {
790 updateProcessState(processState, false);
Dianne Hackborne829fef2010-10-26 17:44:01 -0700791 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700792 sync, false, mAppThread.asBinder(), sendingUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 r.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400794 r.compatInfo = compatInfo;
Jeff Brown9ef09972013-10-15 20:49:59 -0700795 sendMessage(H.RECEIVER, r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 }
797
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400798 public final void scheduleCreateBackupAgent(ApplicationInfo app,
799 CompatibilityInfo compatInfo, int backupMode) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700800 CreateBackupAgentData d = new CreateBackupAgentData();
801 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400802 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700803 d.backupMode = backupMode;
804
Jeff Brown9ef09972013-10-15 20:49:59 -0700805 sendMessage(H.CREATE_BACKUP_AGENT, d);
Christopher Tate181fafa2009-05-14 11:12:14 -0700806 }
807
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400808 public final void scheduleDestroyBackupAgent(ApplicationInfo app,
809 CompatibilityInfo compatInfo) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700810 CreateBackupAgentData d = new CreateBackupAgentData();
811 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400812 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700813
Jeff Brown9ef09972013-10-15 20:49:59 -0700814 sendMessage(H.DESTROY_BACKUP_AGENT, d);
Christopher Tate181fafa2009-05-14 11:12:14 -0700815 }
816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 public final void scheduleCreateService(IBinder token,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700818 ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
819 updateProcessState(processState, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 CreateServiceData s = new CreateServiceData();
821 s.token = token;
822 s.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400823 s.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824
Jeff Brown9ef09972013-10-15 20:49:59 -0700825 sendMessage(H.CREATE_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 }
827
828 public final void scheduleBindService(IBinder token, Intent intent,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700829 boolean rebind, int processState) {
830 updateProcessState(processState, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 BindServiceData s = new BindServiceData();
832 s.token = token;
833 s.intent = intent;
834 s.rebind = rebind;
835
Amith Yamasani742a6712011-05-04 14:49:28 -0700836 if (DEBUG_SERVICE)
837 Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
838 + Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
Jeff Brown9ef09972013-10-15 20:49:59 -0700839 sendMessage(H.BIND_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 }
841
842 public final void scheduleUnbindService(IBinder token, Intent intent) {
843 BindServiceData s = new BindServiceData();
844 s.token = token;
845 s.intent = intent;
846
Jeff Brown9ef09972013-10-15 20:49:59 -0700847 sendMessage(H.UNBIND_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 }
849
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -0700850 public final void scheduleServiceArgs(IBinder token, ParceledListSlice args) {
851 List<ServiceStartArgs> list = args.getList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -0700853 for (int i = 0; i < list.size(); i++) {
854 ServiceStartArgs ssa = list.get(i);
855 ServiceArgsData s = new ServiceArgsData();
856 s.token = token;
857 s.taskRemoved = ssa.taskRemoved;
858 s.startId = ssa.startId;
859 s.flags = ssa.flags;
860 s.args = ssa.args;
861
862 sendMessage(H.SERVICE_ARGS, s);
863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 }
865
866 public final void scheduleStopService(IBinder token) {
Jeff Brown9ef09972013-10-15 20:49:59 -0700867 sendMessage(H.STOP_SERVICE, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 }
869
Jeff Hao1b012d32014-08-20 10:35:34 -0700870 public final void bindApplication(String processName, ApplicationInfo appInfo,
871 List<ProviderInfo> providers, ComponentName instrumentationName,
872 ProfilerInfo profilerInfo, Bundle instrumentationArgs,
873 IInstrumentationWatcher instrumentationWatcher,
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800874 IUiAutomationConnection instrumentationUiConnection, int debugMode,
Pablo Ceballosa4d4e822015-10-05 10:27:52 -0700875 boolean enableBinderTracking, boolean trackAllocation,
876 boolean isRestrictedBackupMode, boolean persistent, Configuration config,
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700877 CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800878 String buildSerial, boolean autofillCompatibilityEnabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879
880 if (services != null) {
881 // Setup the service cache in the ServiceManager
882 ServiceManager.initServiceCache(services);
883 }
884
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800885 setCoreSettings(coreSettings);
886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 AppBindData data = new AppBindData();
888 data.processName = processName;
889 data.appInfo = appInfo;
890 data.providers = providers;
891 data.instrumentationName = instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 data.instrumentationArgs = instrumentationArgs;
893 data.instrumentationWatcher = instrumentationWatcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800894 data.instrumentationUiAutomationConnection = instrumentationUiConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 data.debugMode = debugMode;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400896 data.enableBinderTracking = enableBinderTracking;
Man Caocfa78b22015-06-11 20:14:34 -0700897 data.trackAllocation = trackAllocation;
Christopher Tate181fafa2009-05-14 11:12:14 -0700898 data.restrictedBackupMode = isRestrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700899 data.persistent = persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 data.config = config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400901 data.compatInfo = compatInfo;
Jeff Hao1b012d32014-08-20 10:35:34 -0700902 data.initProfilerInfo = profilerInfo;
Svet Ganov37e43272016-09-09 16:01:32 -0700903 data.buildSerial = buildSerial;
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800904 data.autofillCompatibilityEnabled = autofillCompatibilityEnabled;
Jeff Brown9ef09972013-10-15 20:49:59 -0700905 sendMessage(H.BIND_APPLICATION, data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 }
907
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -0400908 public final void runIsolatedEntryPoint(String entryPoint, String[] entryPointArgs) {
909 SomeArgs args = SomeArgs.obtain();
910 args.arg1 = entryPoint;
911 args.arg2 = entryPointArgs;
912 sendMessage(H.RUN_ISOLATED_ENTRY_POINT, args);
913 }
914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 public final void scheduleExit() {
Jeff Brown9ef09972013-10-15 20:49:59 -0700916 sendMessage(H.EXIT_APPLICATION, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 }
918
Christopher Tate5e1ab332009-09-01 20:32:49 -0700919 public final void scheduleSuicide() {
Jeff Brown9ef09972013-10-15 20:49:59 -0700920 sendMessage(H.SUICIDE, null);
Christopher Tate5e1ab332009-09-01 20:32:49 -0700921 }
922
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100923 public void scheduleApplicationInfoChanged(ApplicationInfo ai) {
924 sendMessage(H.APPLICATION_INFO_CHANGED, ai);
925 }
926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 public void updateTimeZone() {
928 TimeZone.setDefault(null);
929 }
930
Robert Greenwalt03595d02010-11-02 14:08:23 -0700931 public void clearDnsCache() {
932 // a non-standard API to get this to libcore
933 InetAddress.clearDnsCache();
Paul Jensene401d172014-09-12 10:47:39 -0400934 // Allow libcore to perform the necessary actions as it sees fit upon a network
935 // configuration change.
936 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Robert Greenwalt03595d02010-11-02 14:08:23 -0700937 }
938
Jason Monk83520b92014-05-09 15:16:06 -0400939 public void setHttpProxy(String host, String port, String exclList, Uri pacFileUrl) {
Paul Jensen72db88e2015-03-10 10:54:12 -0400940 final ConnectivityManager cm = ConnectivityManager.from(getSystemContext());
941 final Network network = cm.getBoundNetworkForProcess();
Paul Jensene0bef712014-12-10 15:12:18 -0500942 if (network != null) {
Paul Jensen72db88e2015-03-10 10:54:12 -0400943 Proxy.setHttpProxySystemProperty(cm.getDefaultProxy());
Paul Jensene0bef712014-12-10 15:12:18 -0500944 } else {
945 Proxy.setHttpProxySystemProperty(host, port, exclList, pacFileUrl);
946 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700947 }
948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 public void processInBackground() {
950 mH.removeMessages(H.GC_WHEN_IDLE);
951 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
952 }
953
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700954 public void dumpService(ParcelFileDescriptor pfd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700955 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700956 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700957 data.fd = pfd.dup();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700958 data.token = servicetoken;
959 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -0700960 sendMessage(H.DUMP_SERVICE, data, 0, 0, true /*async*/);
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700961 } catch (IOException e) {
962 Slog.w(TAG, "dumpService failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700963 } finally {
964 IoUtils.closeQuietly(pfd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 }
966 }
967
968 // This function exists to make sure all receiver dispatching is
969 // correctly ordered, since these are one-way calls and the binder driver
970 // applies transaction ordering per object for such calls.
971 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700972 int resultCode, String dataStr, Bundle extras, boolean ordered,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700973 boolean sticky, int sendingUser, int processState) throws RemoteException {
974 updateProcessState(processState, false);
Dianne Hackborn20e80982012-08-31 19:00:44 -0700975 receiver.performReceive(intent, resultCode, dataStr, extras, ordered,
976 sticky, sendingUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 }
Bob Leee5408332009-09-04 18:31:17 -0700978
Wale Ogunwalec2607b42015-02-07 16:16:59 -0800979 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 public void scheduleLowMemory() {
Jeff Brown9ef09972013-10-15 20:49:59 -0700981 sendMessage(H.LOW_MEMORY, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 }
983
Wale Ogunwale60454db2015-01-23 16:05:07 -0800984 @Override
Jeff Hao1b012d32014-08-20 10:35:34 -0700985 public void profilerControl(boolean start, ProfilerInfo profilerInfo, int profileType) {
986 sendMessage(H.PROFILER_CONTROL, profilerInfo, start ? 1 : 0, profileType);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800987 }
988
Makoto Onuki4556b7b2017-07-07 14:58:58 -0700989 @Override
Christopher Ferris8d652f82017-04-11 16:29:18 -0700990 public void dumpHeap(boolean managed, boolean mallocInfo, boolean runGc, String path,
991 ParcelFileDescriptor fd) {
Andy McFadden824c5102010-07-09 16:26:57 -0700992 DumpHeapData dhd = new DumpHeapData();
Christopher Ferris8d652f82017-04-11 16:29:18 -0700993 dhd.managed = managed;
994 dhd.mallocInfo = mallocInfo;
Makoto Onuki4556b7b2017-07-07 14:58:58 -0700995 dhd.runGc = runGc;
Andy McFadden824c5102010-07-09 16:26:57 -0700996 dhd.path = path;
997 dhd.fd = fd;
Christopher Ferris8d652f82017-04-11 16:29:18 -0700998 sendMessage(H.DUMP_HEAP, dhd, 0, 0, true /*async*/);
Andy McFadden824c5102010-07-09 16:26:57 -0700999 }
1000
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001001 public void attachAgent(String agent) {
1002 sendMessage(H.ATTACH_AGENT, agent);
1003 }
1004
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001005 public void setSchedulingGroup(int group) {
1006 // Note: do this immediately, since going into the foreground
1007 // should happen regardless of what pending work we have to do
1008 // and the activity manager will wait for us to report back that
1009 // we are done before sending us to the background.
1010 try {
1011 Process.setProcessGroup(Process.myPid(), group);
1012 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001013 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001014 }
1015 }
Bob Leee5408332009-09-04 18:31:17 -07001016
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001017 public void dispatchPackageBroadcast(int cmd, String[] packages) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001018 sendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001019 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001020
1021 public void scheduleCrash(String msg) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001022 sendMessage(H.SCHEDULE_CRASH, msg);
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001023 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07001024
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001025 public void dumpActivity(ParcelFileDescriptor pfd, IBinder activitytoken,
Dianne Hackborn30d71892010-12-11 10:37:55 -08001026 String prefix, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07001027 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001028 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001029 data.fd = pfd.dup();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001030 data.token = activitytoken;
1031 data.prefix = prefix;
1032 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001033 sendMessage(H.DUMP_ACTIVITY, data, 0, 0, true /*async*/);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001034 } catch (IOException e) {
1035 Slog.w(TAG, "dumpActivity failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001036 } finally {
1037 IoUtils.closeQuietly(pfd);
Dianne Hackborn625ac272010-09-17 18:29:22 -07001038 }
1039 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07001040
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001041 public void dumpProvider(ParcelFileDescriptor pfd, IBinder providertoken,
Marco Nelissen18cb2872011-11-15 11:19:53 -08001042 String[] args) {
1043 DumpComponentInfo data = new DumpComponentInfo();
1044 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001045 data.fd = pfd.dup();
Marco Nelissen18cb2872011-11-15 11:19:53 -08001046 data.token = providertoken;
1047 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001048 sendMessage(H.DUMP_PROVIDER, data, 0, 0, true /*async*/);
Marco Nelissen18cb2872011-11-15 11:19:53 -08001049 } catch (IOException e) {
1050 Slog.w(TAG, "dumpProvider failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001051 } finally {
1052 IoUtils.closeQuietly(pfd);
Marco Nelissen18cb2872011-11-15 11:19:53 -08001053 }
1054 }
1055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001057 public void dumpMemInfo(ParcelFileDescriptor pfd, Debug.MemoryInfo mem, boolean checkin,
Colin Crossc4fb5f92016-02-02 16:51:15 -08001058 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
1059 boolean dumpUnreachable, String[] args) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001060 FileOutputStream fout = new FileOutputStream(pfd.getFileDescriptor());
Dianne Hackborn8c841092013-06-24 13:46:13 -07001061 PrintWriter pw = new FastPrintWriter(fout);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001062 try {
Colin Crossc4fb5f92016-02-02 16:51:15 -08001063 dumpMemInfo(pw, mem, checkin, dumpFullInfo, dumpDalvik, dumpSummaryOnly, dumpUnreachable);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001064 } finally {
Chet Haase9c1e23b2011-03-24 10:51:31 -07001065 pw.flush();
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001066 IoUtils.closeQuietly(pfd);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001067 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001068 }
1069
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001070 private void dumpMemInfo(PrintWriter pw, Debug.MemoryInfo memInfo, boolean checkin,
Colin Crossc4fb5f92016-02-02 16:51:15 -08001071 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly, boolean dumpUnreachable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 long nativeMax = Debug.getNativeHeapSize() / 1024;
1073 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1074 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 Runtime runtime = Runtime.getRuntime();
Mathieu Chartierd288a262015-07-10 13:44:42 -07001077 runtime.gc(); // Do GC since countInstancesOfClass counts unreachable objects.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 long dalvikMax = runtime.totalMemory() / 1024;
1079 long dalvikFree = runtime.freeMemory() / 1024;
1080 long dalvikAllocated = dalvikMax - dalvikFree;
Richard Uhler2c036192016-09-14 09:48:31 +01001081
1082 Class[] classesToCount = new Class[] {
1083 ContextImpl.class,
1084 Activity.class,
1085 WebView.class,
1086 OpenSSLSocketImpl.class
1087 };
1088 long[] instanceCounts = VMDebug.countInstancesOfClasses(classesToCount, true);
1089 long appContextInstanceCount = instanceCounts[0];
1090 long activityInstanceCount = instanceCounts[1];
1091 long webviewInstanceCount = instanceCounts[2];
1092 long openSslSocketCount = instanceCounts[3];
1093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 long viewInstanceCount = ViewDebug.getViewInstanceCount();
Romain Guy65b345f2011-07-27 18:51:50 -07001095 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 int globalAssetCount = AssetManager.getGlobalAssetCount();
1097 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1098 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1099 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1100 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Dianne Hackbornfabb70b2014-11-11 12:22:36 -08001101 long parcelSize = Parcel.getGlobalAllocSize();
1102 long parcelCount = Parcel.getGlobalAllocCount();
Vasu Noric3849202010-03-09 10:47:25 -08001103 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -07001104
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07001105 dumpMemInfoTable(pw, memInfo, checkin, dumpFullInfo, dumpDalvik, dumpSummaryOnly,
1106 Process.myPid(),
Dianne Hackborne77187d2013-10-25 16:32:41 -07001107 (mBoundApplication != null) ? mBoundApplication.processName : "unknown",
1108 nativeMax, nativeAllocated, nativeFree,
1109 dalvikMax, dalvikAllocated, dalvikFree);
1110
Dianne Hackbornb437e092011-08-05 17:50:29 -07001111 if (checkin) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 // NOTE: if you change anything significant below, also consider changing
1113 // ACTIVITY_THREAD_CHECKIN_VERSION.
Anwar Ghuloum3c615062013-05-13 14:18:02 -07001114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 // Object counts
1116 pw.print(viewInstanceCount); pw.print(',');
1117 pw.print(viewRootInstanceCount); pw.print(',');
1118 pw.print(appContextInstanceCount); pw.print(',');
1119 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 pw.print(globalAssetCount); pw.print(',');
1122 pw.print(globalAssetManagerCount); pw.print(',');
1123 pw.print(binderLocalObjectCount); pw.print(',');
1124 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 pw.print(binderDeathObjectCount); pw.print(',');
1127 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 // SQL
Vasu Noric3849202010-03-09 10:47:25 -08001130 pw.print(stats.memoryUsed / 1024); pw.print(',');
Jeff Brown2a293b62012-01-19 14:02:22 -08001131 pw.print(stats.memoryUsed / 1024); pw.print(',');
1132 pw.print(stats.pageCacheOverflow / 1024); pw.print(',');
Dianne Hackbornb437e092011-08-05 17:50:29 -07001133 pw.print(stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001134 for (int i = 0; i < stats.dbStats.size(); i++) {
1135 DbStats dbStats = stats.dbStats.get(i);
Dianne Hackbornb437e092011-08-05 17:50:29 -07001136 pw.print(','); pw.print(dbStats.dbName);
1137 pw.print(','); pw.print(dbStats.pageSize);
1138 pw.print(','); pw.print(dbStats.dbSize);
1139 pw.print(','); pw.print(dbStats.lookaside);
1140 pw.print(','); pw.print(dbStats.cache);
1141 pw.print(','); pw.print(dbStats.cache);
Vasu Noric3849202010-03-09 10:47:25 -08001142 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07001143 pw.println();
Bob Leee5408332009-09-04 18:31:17 -07001144
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001145 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 }
Bob Leee5408332009-09-04 18:31:17 -07001147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 pw.println(" ");
1149 pw.println(" Objects");
Romain Guy65b345f2011-07-27 18:51:50 -07001150 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRootImpl:",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 viewRootInstanceCount);
1152
1153 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
1154 "Activities:", activityInstanceCount);
1155
1156 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
1157 "AssetManagers:", globalAssetManagerCount);
1158
1159 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
1160 "Proxy Binders:", binderProxyObjectCount);
Dianne Hackbornfabb70b2014-11-11 12:22:36 -08001161 printRow(pw, TWO_COUNT_COLUMNS, "Parcel memory:", parcelSize/1024,
1162 "Parcel count:", parcelCount);
1163 printRow(pw, TWO_COUNT_COLUMNS, "Death Recipients:", binderDeathObjectCount,
1164 "OpenSSL Sockets:", openSslSocketCount);
Richard Uhler2c036192016-09-14 09:48:31 +01001165 printRow(pw, ONE_COUNT_COLUMN, "WebViews:", webviewInstanceCount);
Bob Leee5408332009-09-04 18:31:17 -07001166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 // SQLite mem info
1168 pw.println(" ");
1169 pw.println(" SQL");
Jeff Brown2a293b62012-01-19 14:02:22 -08001170 printRow(pw, ONE_COUNT_COLUMN, "MEMORY_USED:", stats.memoryUsed / 1024);
1171 printRow(pw, TWO_COUNT_COLUMNS, "PAGECACHE_OVERFLOW:",
1172 stats.pageCacheOverflow / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001173 pw.println(" ");
1174 int N = stats.dbStats.size();
1175 if (N > 0) {
1176 pw.println(" DATABASES");
Kweku Adams983829f2017-12-06 14:53:50 -08001177 printRow(pw, DB_INFO_FORMAT, "pgsz", "dbsz", "Lookaside(b)", "cache",
Vasu Nori3c7131f2010-09-21 14:36:57 -07001178 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -08001179 for (int i = 0; i < N; i++) {
1180 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -07001181 printRow(pw, DB_INFO_FORMAT,
1182 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
1183 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
1184 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
1185 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -08001186 }
1187 }
Bob Leee5408332009-09-04 18:31:17 -07001188
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001189 // Asset details.
1190 String assetAlloc = AssetManager.getAssetAllocations();
1191 if (assetAlloc != null) {
1192 pw.println(" ");
1193 pw.println(" Asset Allocations");
1194 pw.print(assetAlloc);
1195 }
Colin Crossc4fb5f92016-02-02 16:51:15 -08001196
1197 // Unreachable native memory
1198 if (dumpUnreachable) {
1199 boolean showContents = ((mBoundApplication != null)
1200 && ((mBoundApplication.appInfo.flags&ApplicationInfo.FLAG_DEBUGGABLE) != 0))
1201 || android.os.Build.IS_DEBUGGABLE;
1202 pw.println(" ");
1203 pw.println(" Unreachable memory");
1204 pw.print(Debug.getUnreachableMemory(100, showContents));
1205 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001206 }
1207
1208 @Override
Kweku Adams983829f2017-12-06 14:53:50 -08001209 public void dumpMemInfoProto(ParcelFileDescriptor pfd, Debug.MemoryInfo mem,
1210 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
1211 boolean dumpUnreachable, String[] args) {
1212 ProtoOutputStream proto = new ProtoOutputStream(pfd.getFileDescriptor());
1213 try {
1214 dumpMemInfo(proto, mem, dumpFullInfo, dumpDalvik, dumpSummaryOnly, dumpUnreachable);
1215 } finally {
1216 proto.flush();
1217 IoUtils.closeQuietly(pfd);
1218 }
1219 }
1220
1221 private void dumpMemInfo(ProtoOutputStream proto, Debug.MemoryInfo memInfo,
1222 boolean dumpFullInfo, boolean dumpDalvik,
1223 boolean dumpSummaryOnly, boolean dumpUnreachable) {
1224 long nativeMax = Debug.getNativeHeapSize() / 1024;
1225 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1226 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1227
1228 Runtime runtime = Runtime.getRuntime();
1229 runtime.gc(); // Do GC since countInstancesOfClass counts unreachable objects.
1230 long dalvikMax = runtime.totalMemory() / 1024;
1231 long dalvikFree = runtime.freeMemory() / 1024;
1232 long dalvikAllocated = dalvikMax - dalvikFree;
1233
1234 Class[] classesToCount = new Class[] {
1235 ContextImpl.class,
1236 Activity.class,
1237 WebView.class,
1238 OpenSSLSocketImpl.class
1239 };
1240 long[] instanceCounts = VMDebug.countInstancesOfClasses(classesToCount, true);
1241 long appContextInstanceCount = instanceCounts[0];
1242 long activityInstanceCount = instanceCounts[1];
1243 long webviewInstanceCount = instanceCounts[2];
1244 long openSslSocketCount = instanceCounts[3];
1245
1246 long viewInstanceCount = ViewDebug.getViewInstanceCount();
1247 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
1248 int globalAssetCount = AssetManager.getGlobalAssetCount();
1249 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1250 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1251 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1252 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
1253 long parcelSize = Parcel.getGlobalAllocSize();
1254 long parcelCount = Parcel.getGlobalAllocCount();
1255 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
1256
1257 final long mToken = proto.start(MemInfoProto.AppData.PROCESS_MEMORY);
1258 proto.write(MemInfoProto.ProcessMemory.PID, Process.myPid());
1259 proto.write(MemInfoProto.ProcessMemory.PROCESS_NAME,
1260 (mBoundApplication != null) ? mBoundApplication.processName : "unknown");
1261 dumpMemInfoTable(proto, memInfo, dumpDalvik, dumpSummaryOnly,
1262 nativeMax, nativeAllocated, nativeFree,
1263 dalvikMax, dalvikAllocated, dalvikFree);
1264 proto.end(mToken);
1265
1266 final long oToken = proto.start(MemInfoProto.AppData.OBJECTS);
1267 proto.write(MemInfoProto.AppData.ObjectStats.VIEW_INSTANCE_COUNT, viewInstanceCount);
1268 proto.write(MemInfoProto.AppData.ObjectStats.VIEW_ROOT_INSTANCE_COUNT,
1269 viewRootInstanceCount);
1270 proto.write(MemInfoProto.AppData.ObjectStats.APP_CONTEXT_INSTANCE_COUNT,
1271 appContextInstanceCount);
1272 proto.write(MemInfoProto.AppData.ObjectStats.ACTIVITY_INSTANCE_COUNT,
1273 activityInstanceCount);
1274 proto.write(MemInfoProto.AppData.ObjectStats.GLOBAL_ASSET_COUNT, globalAssetCount);
1275 proto.write(MemInfoProto.AppData.ObjectStats.GLOBAL_ASSET_MANAGER_COUNT,
1276 globalAssetManagerCount);
1277 proto.write(MemInfoProto.AppData.ObjectStats.LOCAL_BINDER_OBJECT_COUNT,
1278 binderLocalObjectCount);
1279 proto.write(MemInfoProto.AppData.ObjectStats.PROXY_BINDER_OBJECT_COUNT,
1280 binderProxyObjectCount);
1281 proto.write(MemInfoProto.AppData.ObjectStats.PARCEL_MEMORY_KB, parcelSize / 1024);
1282 proto.write(MemInfoProto.AppData.ObjectStats.PARCEL_COUNT, parcelCount);
1283 proto.write(MemInfoProto.AppData.ObjectStats.BINDER_OBJECT_DEATH_COUNT,
1284 binderDeathObjectCount);
1285 proto.write(MemInfoProto.AppData.ObjectStats.OPEN_SSL_SOCKET_COUNT, openSslSocketCount);
1286 proto.write(MemInfoProto.AppData.ObjectStats.WEBVIEW_INSTANCE_COUNT,
1287 webviewInstanceCount);
1288 proto.end(oToken);
1289
1290 // SQLite mem info
1291 final long sToken = proto.start(MemInfoProto.AppData.SQL);
1292 proto.write(MemInfoProto.AppData.SqlStats.MEMORY_USED_KB, stats.memoryUsed / 1024);
1293 proto.write(MemInfoProto.AppData.SqlStats.PAGECACHE_OVERFLOW_KB,
1294 stats.pageCacheOverflow / 1024);
1295 proto.write(MemInfoProto.AppData.SqlStats.MALLOC_SIZE_KB, stats.largestMemAlloc / 1024);
1296 int n = stats.dbStats.size();
1297 for (int i = 0; i < n; i++) {
1298 DbStats dbStats = stats.dbStats.get(i);
1299
1300 final long dToken = proto.start(MemInfoProto.AppData.SqlStats.DATABASES);
1301 proto.write(MemInfoProto.AppData.SqlStats.Database.NAME, dbStats.dbName);
1302 proto.write(MemInfoProto.AppData.SqlStats.Database.PAGE_SIZE, dbStats.pageSize);
1303 proto.write(MemInfoProto.AppData.SqlStats.Database.DB_SIZE, dbStats.dbSize);
1304 proto.write(MemInfoProto.AppData.SqlStats.Database.LOOKASIDE_B, dbStats.lookaside);
1305 proto.write(MemInfoProto.AppData.SqlStats.Database.CACHE, dbStats.cache);
1306 proto.end(dToken);
1307 }
1308 proto.end(sToken);
1309
1310 // Asset details.
1311 String assetAlloc = AssetManager.getAssetAllocations();
1312 if (assetAlloc != null) {
1313 proto.write(MemInfoProto.AppData.ASSET_ALLOCATIONS, assetAlloc);
1314 }
1315
1316 // Unreachable native memory
1317 if (dumpUnreachable) {
1318 int flags = mBoundApplication == null ? 0 : mBoundApplication.appInfo.flags;
1319 boolean showContents = (flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0
1320 || android.os.Build.IS_DEBUGGABLE;
1321 proto.write(MemInfoProto.AppData.UNREACHABLE_MEMORY,
1322 Debug.getUnreachableMemory(100, showContents));
1323 }
1324 }
1325
1326 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001327 public void dumpGfxInfo(ParcelFileDescriptor pfd, String[] args) {
Chris Craikfc294242016-12-13 18:10:46 -08001328 nDumpGraphicsInfo(pfd.getFileDescriptor());
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001329 WindowManagerGlobal.getInstance().dumpGfxInfo(pfd.getFileDescriptor(), args);
1330 IoUtils.closeQuietly(pfd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 }
1332
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001333 private void dumpDatabaseInfo(ParcelFileDescriptor pfd, String[] args) {
1334 PrintWriter pw = new FastPrintWriter(
1335 new FileOutputStream(pfd.getFileDescriptor()));
Jeff Brown6754ba22011-12-14 20:20:01 -08001336 PrintWriterPrinter printer = new PrintWriterPrinter(pw);
1337 SQLiteDebug.dump(printer, args);
1338 pw.flush();
1339 }
1340
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001341 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001342 public void dumpDbInfo(final ParcelFileDescriptor pfd, final String[] args) {
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001343 if (mSystemThread) {
Felipe Leme29de4922016-06-07 16:14:07 -07001344 // Ensure this invocation is asynchronous to prevent writer waiting if buffer cannot
1345 // be consumed. But it must duplicate the file descriptor first, since caller might
1346 // be closing it.
1347 final ParcelFileDescriptor dup;
1348 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001349 dup = pfd.dup();
Felipe Leme29de4922016-06-07 16:14:07 -07001350 } catch (IOException e) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001351 Log.w(TAG, "Could not dup FD " + pfd.getFileDescriptor().getInt$());
Felipe Leme29de4922016-06-07 16:14:07 -07001352 return;
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001353 } finally {
1354 IoUtils.closeQuietly(pfd);
Felipe Leme29de4922016-06-07 16:14:07 -07001355 }
1356
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001357 AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
1358 @Override
1359 public void run() {
Felipe Lemec74972f2016-06-08 09:12:37 -07001360 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001361 dumpDatabaseInfo(dup, args);
Felipe Lemec74972f2016-06-08 09:12:37 -07001362 } finally {
1363 IoUtils.closeQuietly(dup);
1364 }
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001365 }
1366 });
1367 } else {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001368 dumpDatabaseInfo(pfd, args);
1369 IoUtils.closeQuietly(pfd);
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001370 }
1371 }
1372
1373 @Override
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001374 public void unstableProviderDied(IBinder provider) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001375 sendMessage(H.UNSTABLE_PROVIDER_DIED, provider);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001376 }
1377
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001378 @Override
Adam Skorydfc7fd72013-08-05 19:23:41 -07001379 public void requestAssistContextExtras(IBinder activityToken, IBinder requestToken,
Svet Ganovfd31f852017-04-26 15:54:27 -07001380 int requestType, int sessionId, int flags) {
Adam Skorydfc7fd72013-08-05 19:23:41 -07001381 RequestAssistContextExtras cmd = new RequestAssistContextExtras();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001382 cmd.activityToken = activityToken;
1383 cmd.requestToken = requestToken;
1384 cmd.requestType = requestType;
Amith Yamasani4f128e42016-05-10 11:44:12 -07001385 cmd.sessionId = sessionId;
Svet Ganovfd31f852017-04-26 15:54:27 -07001386 cmd.flags = flags;
Jeff Brown9ef09972013-10-15 20:49:59 -07001387 sendMessage(H.REQUEST_ASSIST_CONTEXT_EXTRAS, cmd);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001388 }
1389
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08001390 public void setCoreSettings(Bundle coreSettings) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001391 sendMessage(H.SET_CORE_SETTINGS, coreSettings);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001392 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001393
1394 public void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) {
1395 UpdateCompatibilityData ucd = new UpdateCompatibilityData();
1396 ucd.pkg = pkg;
1397 ucd.info = info;
Jeff Brown9ef09972013-10-15 20:49:59 -07001398 sendMessage(H.UPDATE_PACKAGE_COMPATIBILITY_INFO, ucd);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001399 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001400
1401 public void scheduleTrimMemory(int level) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001402 sendMessage(H.TRIM_MEMORY, null, level);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001403 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001404
Craig Mautner5eda9b32013-07-02 11:58:16 -07001405 public void scheduleTranslucentConversionComplete(IBinder token, boolean drawComplete) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001406 sendMessage(H.TRANSLUCENT_CONVERSION_COMPLETE, token, drawComplete ? 1 : 0);
Craig Mautner5eda9b32013-07-02 11:58:16 -07001407 }
Dianne Hackborna413dc02013-07-12 12:02:55 -07001408
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001409 public void scheduleOnNewActivityOptions(IBinder token, Bundle options) {
Craig Mautnereb8abf72014-07-02 15:04:09 -07001410 sendMessage(H.ON_NEW_ACTIVITY_OPTIONS,
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001411 new Pair<IBinder, ActivityOptions>(token, ActivityOptions.fromBundle(options)));
Craig Mautnereb8abf72014-07-02 15:04:09 -07001412 }
1413
Dianne Hackborna413dc02013-07-12 12:02:55 -07001414 public void setProcessState(int state) {
1415 updateProcessState(state, true);
1416 }
1417
1418 public void updateProcessState(int processState, boolean fromIpc) {
1419 synchronized (this) {
1420 if (mLastProcessState != processState) {
1421 mLastProcessState = processState;
Mathieu Chartier1e370902013-07-18 10:58:01 -07001422 // Update Dalvik state based on ActivityManager.PROCESS_STATE_* constants.
1423 final int DALVIK_PROCESS_STATE_JANK_PERCEPTIBLE = 0;
1424 final int DALVIK_PROCESS_STATE_JANK_IMPERCEPTIBLE = 1;
1425 int dalvikProcessState = DALVIK_PROCESS_STATE_JANK_IMPERCEPTIBLE;
1426 // TODO: Tune this since things like gmail sync are important background but not jank perceptible.
1427 if (processState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
1428 dalvikProcessState = DALVIK_PROCESS_STATE_JANK_PERCEPTIBLE;
1429 }
1430 VMRuntime.getRuntime().updateProcessState(dalvikProcessState);
Dianne Hackborna413dc02013-07-12 12:02:55 -07001431 if (false) {
1432 Slog.i(TAG, "******************* PROCESS STATE CHANGED TO: " + processState
1433 + (fromIpc ? " (from ipc": ""));
1434 }
1435 }
1436 }
1437 }
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001438
Sudheer Shanka84a48952017-03-08 18:19:01 -08001439 /**
1440 * Updates {@link #mNetworkBlockSeq}. This is used by ActivityManagerService to inform
1441 * the main thread that it needs to wait for the network rules to get updated before
1442 * launching an activity.
1443 */
1444 @Override
1445 public void setNetworkBlockSeq(long procStateSeq) {
1446 synchronized (mNetworkPolicyLock) {
1447 mNetworkBlockSeq = procStateSeq;
1448 }
1449 }
1450
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001451 @Override
1452 public void scheduleInstallProvider(ProviderInfo provider) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001453 sendMessage(H.INSTALL_PROVIDER, provider);
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001454 }
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001455
1456 @Override
Neil Fullerb7146fe2016-11-15 16:52:15 +00001457 public final void updateTimePrefs(int timeFormatPreference) {
1458 final Boolean timeFormatPreferenceBool;
1459 // For convenience we are using the Intent extra values.
1460 if (timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_12_HOUR) {
1461 timeFormatPreferenceBool = Boolean.FALSE;
1462 } else if (timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_24_HOUR) {
1463 timeFormatPreferenceBool = Boolean.TRUE;
1464 } else {
1465 // timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_LOCALE_DEFAULT
1466 // (or unknown).
1467 timeFormatPreferenceBool = null;
1468 }
1469 DateFormat.set24HourTimePref(timeFormatPreferenceBool);
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001470 }
Craig Mautneree2e45a2014-06-27 12:10:03 -07001471
1472 @Override
Craig Mautner8746a472014-07-24 15:12:54 -07001473 public void scheduleEnterAnimationComplete(IBinder token) {
1474 sendMessage(H.ENTER_ANIMATION_COMPLETE, token);
1475 }
Jeff Sharkey605eb792014-11-04 13:34:06 -08001476
1477 @Override
1478 public void notifyCleartextNetwork(byte[] firstPacket) {
1479 if (StrictMode.vmCleartextNetworkEnabled()) {
1480 StrictMode.onCleartextNetworkDetected(firstPacket);
1481 }
1482 }
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001483
1484 @Override
1485 public void startBinderTracking() {
1486 sendMessage(H.START_BINDER_TRACKING, null);
1487 }
1488
1489 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001490 public void stopBinderTrackingAndDump(ParcelFileDescriptor pfd) {
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001491 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001492 sendMessage(H.STOP_BINDER_TRACKING_AND_DUMP, pfd.dup());
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001493 } catch (IOException e) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001494 } finally {
1495 IoUtils.closeQuietly(pfd);
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001496 }
1497 }
Wale Ogunwale5f986092015-12-04 15:35:38 -08001498
1499 @Override
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001500 public void scheduleLocalVoiceInteractionStarted(IBinder token,
1501 IVoiceInteractor voiceInteractor) throws RemoteException {
1502 SomeArgs args = SomeArgs.obtain();
1503 args.arg1 = token;
1504 args.arg2 = voiceInteractor;
1505 sendMessage(H.LOCAL_VOICE_INTERACTION_STARTED, args);
1506 }
Chad Brubakerc72875b2016-04-27 16:35:11 -07001507
1508 @Override
1509 public void handleTrustStorageUpdate() {
1510 NetworkSecurityPolicy.getInstance().handleTrustStorageUpdate();
1511 }
Andrii Kulian446e8242017-10-26 15:17:29 -07001512
1513 @Override
1514 public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
1515 ActivityThread.this.scheduleTransaction(transaction);
1516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 }
1518
Andrii Kulian446e8242017-10-26 15:17:29 -07001519 @Override
1520 public void updatePendingConfiguration(Configuration config) {
1521 mAppThread.updatePendingConfiguration(config);
1522 }
1523
1524 @Override
1525 public void updateProcessState(int processState, boolean fromIpc) {
1526 mAppThread.updateProcessState(processState, fromIpc);
1527 }
1528
Andrii Kulian446e8242017-10-26 15:17:29 -07001529 class H extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 public static final int BIND_APPLICATION = 110;
1531 public static final int EXIT_APPLICATION = 111;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 public static final int RECEIVER = 113;
1533 public static final int CREATE_SERVICE = 114;
1534 public static final int SERVICE_ARGS = 115;
1535 public static final int STOP_SERVICE = 116;
Dianne Hackborn09233282014-04-30 11:33:59 -07001536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 public static final int CONFIGURATION_CHANGED = 118;
1538 public static final int CLEAN_UP_CONTEXT = 119;
1539 public static final int GC_WHEN_IDLE = 120;
1540 public static final int BIND_SERVICE = 121;
1541 public static final int UNBIND_SERVICE = 122;
1542 public static final int DUMP_SERVICE = 123;
1543 public static final int LOW_MEMORY = 124;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001544 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001545 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001546 public static final int DESTROY_BACKUP_AGENT = 129;
1547 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001548 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001549 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001550 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001551 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -07001552 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001553 public static final int DUMP_ACTIVITY = 136;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001554 public static final int SLEEPING = 137;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001555 public static final int SET_CORE_SETTINGS = 138;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001556 public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001557 public static final int TRIM_MEMORY = 140;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001558 public static final int DUMP_PROVIDER = 141;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001559 public static final int UNSTABLE_PROVIDER_DIED = 142;
Adam Skorydfc7fd72013-08-05 19:23:41 -07001560 public static final int REQUEST_ASSIST_CONTEXT_EXTRAS = 143;
Craig Mautner5eda9b32013-07-02 11:58:16 -07001561 public static final int TRANSLUCENT_CONVERSION_COMPLETE = 144;
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001562 public static final int INSTALL_PROVIDER = 145;
Craig Mautnereb8abf72014-07-02 15:04:09 -07001563 public static final int ON_NEW_ACTIVITY_OPTIONS = 146;
Craig Mautner8746a472014-07-24 15:12:54 -07001564 public static final int ENTER_ANIMATION_COMPLETE = 149;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001565 public static final int START_BINDER_TRACKING = 150;
1566 public static final int STOP_BINDER_TRACKING_AND_DUMP = 151;
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001567 public static final int LOCAL_VOICE_INTERACTION_STARTED = 154;
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001568 public static final int ATTACH_AGENT = 155;
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001569 public static final int APPLICATION_INFO_CHANGED = 156;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001570 public static final int RUN_ISOLATED_ENTRY_POINT = 158;
Andrii Kulian446e8242017-10-26 15:17:29 -07001571 public static final int EXECUTE_TRANSACTION = 159;
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001574 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 switch (code) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 case BIND_APPLICATION: return "BIND_APPLICATION";
1577 case EXIT_APPLICATION: return "EXIT_APPLICATION";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 case RECEIVER: return "RECEIVER";
1579 case CREATE_SERVICE: return "CREATE_SERVICE";
1580 case SERVICE_ARGS: return "SERVICE_ARGS";
1581 case STOP_SERVICE: return "STOP_SERVICE";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1583 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1584 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1585 case BIND_SERVICE: return "BIND_SERVICE";
1586 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1587 case DUMP_SERVICE: return "DUMP_SERVICE";
1588 case LOW_MEMORY: return "LOW_MEMORY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001589 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001590 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1591 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001592 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001593 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001594 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001595 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001596 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -07001597 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -07001598 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001599 case SLEEPING: return "SLEEPING";
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001600 case SET_CORE_SETTINGS: return "SET_CORE_SETTINGS";
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001601 case UPDATE_PACKAGE_COMPATIBILITY_INFO: return "UPDATE_PACKAGE_COMPATIBILITY_INFO";
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001602 case TRIM_MEMORY: return "TRIM_MEMORY";
Marco Nelissen18cb2872011-11-15 11:19:53 -08001603 case DUMP_PROVIDER: return "DUMP_PROVIDER";
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001604 case UNSTABLE_PROVIDER_DIED: return "UNSTABLE_PROVIDER_DIED";
Adam Skorydfc7fd72013-08-05 19:23:41 -07001605 case REQUEST_ASSIST_CONTEXT_EXTRAS: return "REQUEST_ASSIST_CONTEXT_EXTRAS";
Craig Mautner5eda9b32013-07-02 11:58:16 -07001606 case TRANSLUCENT_CONVERSION_COMPLETE: return "TRANSLUCENT_CONVERSION_COMPLETE";
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001607 case INSTALL_PROVIDER: return "INSTALL_PROVIDER";
Craig Mautnereb8abf72014-07-02 15:04:09 -07001608 case ON_NEW_ACTIVITY_OPTIONS: return "ON_NEW_ACTIVITY_OPTIONS";
Craig Mautner8746a472014-07-24 15:12:54 -07001609 case ENTER_ANIMATION_COMPLETE: return "ENTER_ANIMATION_COMPLETE";
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001610 case LOCAL_VOICE_INTERACTION_STARTED: return "LOCAL_VOICE_INTERACTION_STARTED";
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001611 case ATTACH_AGENT: return "ATTACH_AGENT";
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001612 case APPLICATION_INFO_CHANGED: return "APPLICATION_INFO_CHANGED";
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001613 case RUN_ISOLATED_ENTRY_POINT: return "RUN_ISOLATED_ENTRY_POINT";
Andrii Kulian446e8242017-10-26 15:17:29 -07001614 case EXECUTE_TRANSACTION: return "EXECUTE_TRANSACTION";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 }
1616 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001617 return Integer.toString(code);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 }
1619 public void handleMessage(Message msg) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001620 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 switch (msg.what) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 case BIND_APPLICATION:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001623 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 AppBindData data = (AppBindData)msg.obj;
1625 handleBindApplication(data);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001626 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 break;
1628 case EXIT_APPLICATION:
1629 if (mInitialApplication != null) {
1630 mInitialApplication.onTerminate();
1631 }
1632 Looper.myLooper().quit();
1633 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 case RECEIVER:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001635 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveComp");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 handleReceiver((ReceiverData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001637 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 break;
1639 case CREATE_SERVICE:
Tim Murrayb6f5a422016-04-07 15:25:22 -07001640 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceCreate: " + String.valueOf(msg.obj)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 handleCreateService((CreateServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001642 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 break;
1644 case BIND_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001645 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 handleBindService((BindServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001647 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 break;
1649 case UNBIND_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001650 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceUnbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 handleUnbindService((BindServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001652 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 break;
1654 case SERVICE_ARGS:
Tim Murrayb6f5a422016-04-07 15:25:22 -07001655 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceStart: " + String.valueOf(msg.obj)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 handleServiceArgs((ServiceArgsData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001657 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 break;
1659 case STOP_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001660 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 handleStopService((IBinder)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001662 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 case CONFIGURATION_CHANGED:
Andrii Kulian446e8242017-10-26 15:17:29 -07001665 handleConfigurationChanged((Configuration) msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 break;
1667 case CLEAN_UP_CONTEXT:
1668 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1669 cci.context.performFinalCleanup(cci.who, cci.what);
1670 break;
1671 case GC_WHEN_IDLE:
1672 scheduleGcIdler();
1673 break;
1674 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001675 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 break;
1677 case LOW_MEMORY:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001678 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "lowMemory");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 handleLowMemory();
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001680 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001682 case PROFILER_CONTROL:
Jeff Hao1b012d32014-08-20 10:35:34 -07001683 handleProfilerControl(msg.arg1 != 0, (ProfilerInfo)msg.obj, msg.arg2);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001684 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001685 case CREATE_BACKUP_AGENT:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001686 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupCreateAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001687 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001688 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate181fafa2009-05-14 11:12:14 -07001689 break;
1690 case DESTROY_BACKUP_AGENT:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001691 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupDestroyAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001692 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001693 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate181fafa2009-05-14 11:12:14 -07001694 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001695 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001696 Process.killProcess(Process.myPid());
1697 break;
1698 case REMOVE_PROVIDER:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001699 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "providerRemove");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001700 completeRemoveProvider((ProviderRefCount)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001701 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001702 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001703 case ENABLE_JIT:
1704 ensureJitEnabled();
1705 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001706 case DISPATCH_PACKAGE_BROADCAST:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001707 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastPackage");
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001708 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001709 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001710 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001711 case SCHEDULE_CRASH:
1712 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001713 case DUMP_HEAP:
Christopher Ferris8d652f82017-04-11 16:29:18 -07001714 handleDumpHeap((DumpHeapData) msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001715 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001716 case DUMP_ACTIVITY:
1717 handleDumpActivity((DumpComponentInfo)msg.obj);
1718 break;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001719 case DUMP_PROVIDER:
1720 handleDumpProvider((DumpComponentInfo)msg.obj);
1721 break;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001722 case SLEEPING:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001723 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "sleeping");
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001724 handleSleeping((IBinder)msg.obj, msg.arg1 != 0);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001725 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001726 break;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001727 case SET_CORE_SETTINGS:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001728 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setCoreSettings");
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001729 handleSetCoreSettings((Bundle) msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001730 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001731 break;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001732 case UPDATE_PACKAGE_COMPATIBILITY_INFO:
1733 handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001734 break;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001735 case TRIM_MEMORY:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001736 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "trimMemory");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001737 handleTrimMemory(msg.arg1);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001738 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001739 break;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001740 case UNSTABLE_PROVIDER_DIED:
1741 handleUnstableProviderDied((IBinder)msg.obj, false);
1742 break;
Adam Skorydfc7fd72013-08-05 19:23:41 -07001743 case REQUEST_ASSIST_CONTEXT_EXTRAS:
1744 handleRequestAssistContextExtras((RequestAssistContextExtras)msg.obj);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001745 break;
Craig Mautner5eda9b32013-07-02 11:58:16 -07001746 case TRANSLUCENT_CONVERSION_COMPLETE:
1747 handleTranslucentConversionComplete((IBinder)msg.obj, msg.arg1 == 1);
1748 break;
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001749 case INSTALL_PROVIDER:
1750 handleInstallProvider((ProviderInfo) msg.obj);
1751 break;
Craig Mautnereb8abf72014-07-02 15:04:09 -07001752 case ON_NEW_ACTIVITY_OPTIONS:
1753 Pair<IBinder, ActivityOptions> pair = (Pair<IBinder, ActivityOptions>) msg.obj;
1754 onNewActivityOptions(pair.first, pair.second);
Dake Gu7ef70b02014-07-08 18:37:12 -07001755 break;
Craig Mautner8746a472014-07-24 15:12:54 -07001756 case ENTER_ANIMATION_COMPLETE:
1757 handleEnterAnimationComplete((IBinder) msg.obj);
1758 break;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001759 case START_BINDER_TRACKING:
1760 handleStartBinderTracking();
1761 break;
1762 case STOP_BINDER_TRACKING_AND_DUMP:
1763 handleStopBinderTrackingAndDump((ParcelFileDescriptor) msg.obj);
1764 break;
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001765 case LOCAL_VOICE_INTERACTION_STARTED:
1766 handleLocalVoiceInteractionStarted((IBinder) ((SomeArgs) msg.obj).arg1,
1767 (IVoiceInteractor) ((SomeArgs) msg.obj).arg2);
Amith Yamasani61019112017-01-10 15:05:00 -08001768 break;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08001769 case ATTACH_AGENT: {
1770 Application app = getApplication();
1771 handleAttachAgent((String) msg.obj, app != null ? app.mLoadedApk : null);
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001772 break;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08001773 }
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001774 case APPLICATION_INFO_CHANGED:
1775 mUpdatingSystemConfig = true;
1776 try {
1777 handleApplicationInfoChanged((ApplicationInfo) msg.obj);
1778 } finally {
1779 mUpdatingSystemConfig = false;
1780 }
1781 break;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001782 case RUN_ISOLATED_ENTRY_POINT:
1783 handleRunIsolatedEntryPoint((String) ((SomeArgs) msg.obj).arg1,
1784 (String[]) ((SomeArgs) msg.obj).arg2);
1785 break;
Andrii Kulian446e8242017-10-26 15:17:29 -07001786 case EXECUTE_TRANSACTION:
Andrii Kulian04470682018-01-10 15:32:31 -08001787 final ClientTransaction transaction = (ClientTransaction) msg.obj;
1788 mTransactionExecutor.execute(transaction);
1789 if (isSystem()) {
1790 // Client transactions inside system process are recycled on the client side
1791 // instead of ClientLifecycleManager to avoid being cleared before this
1792 // message is handled.
1793 transaction.recycle();
1794 }
Andrii Kulian446e8242017-10-26 15:17:29 -07001795 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 }
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07001797 Object obj = msg.obj;
1798 if (obj instanceof SomeArgs) {
1799 ((SomeArgs) obj).recycle();
1800 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001801 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 }
1803 }
1804
Romain Guy65b345f2011-07-27 18:51:50 -07001805 private class Idler implements MessageQueue.IdleHandler {
Craig Mautner48d0d182013-06-11 07:53:06 -07001806 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001808 ActivityClientRecord a = mNewActivities;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001809 boolean stopProfiling = false;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001810 if (mBoundApplication != null && mProfiler.profileFd != null
1811 && mProfiler.autoStopProfiler) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001812 stopProfiling = true;
1813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 if (a != null) {
1815 mNewActivities = null;
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001816 IActivityManager am = ActivityManager.getService();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001817 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001819 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 TAG, "Reporting idle of " + a +
1821 " finished=" +
Romain Guy65b345f2011-07-27 18:51:50 -07001822 (a.activity != null && a.activity.mFinished));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 if (a.activity != null && !a.activity.mFinished) {
1824 try {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001825 am.activityIdle(a.token, a.createdConfig, stopProfiling);
Dianne Hackborne88846e2009-09-30 21:34:25 -07001826 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001828 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 }
1830 }
1831 prev = a;
1832 a = a.nextIdle;
1833 prev.nextIdle = null;
1834 } while (a != null);
1835 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001836 if (stopProfiling) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001837 mProfiler.stopProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001838 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001839 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 return false;
1841 }
1842 }
1843
1844 final class GcIdler implements MessageQueue.IdleHandler {
Craig Mautner48d0d182013-06-11 07:53:06 -07001845 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 public final boolean queueIdle() {
1847 doGcIfNeeded();
1848 return false;
1849 }
1850 }
1851
Romain Guy65b345f2011-07-27 18:51:50 -07001852 public static ActivityThread currentActivityThread() {
Jeff Sharkey66a017b2013-01-17 18:18:22 -08001853 return sCurrentActivityThread;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855
Wale Ogunwale9a6ef1e2015-06-02 13:41:00 -07001856 public static boolean isSystem() {
1857 return (sCurrentActivityThread != null) ? sCurrentActivityThread.mSystemThread : false;
1858 }
1859
Svetoslavfbf0eca2015-05-01 16:52:41 -07001860 public static String currentOpPackageName() {
1861 ActivityThread am = currentActivityThread();
1862 return (am != null && am.getApplication() != null)
1863 ? am.getApplication().getOpPackageName() : null;
1864 }
1865
Romain Guy65b345f2011-07-27 18:51:50 -07001866 public static String currentPackageName() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001867 ActivityThread am = currentActivityThread();
1868 return (am != null && am.mBoundApplication != null)
Dianne Hackbornb57a50b2013-04-11 17:29:32 -07001869 ? am.mBoundApplication.appInfo.packageName : null;
1870 }
1871
1872 public static String currentProcessName() {
1873 ActivityThread am = currentActivityThread();
1874 return (am != null && am.mBoundApplication != null)
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001875 ? am.mBoundApplication.processName : null;
1876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877
Romain Guy65b345f2011-07-27 18:51:50 -07001878 public static Application currentApplication() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001879 ActivityThread am = currentActivityThread();
1880 return am != null ? am.mInitialApplication : null;
1881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001883 public static IPackageManager getPackageManager() {
1884 if (sPackageManager != null) {
1885 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1886 return sPackageManager;
1887 }
1888 IBinder b = ServiceManager.getService("package");
1889 //Slog.v("PackageManager", "default service binder = " + b);
1890 sPackageManager = IPackageManager.Stub.asInterface(b);
1891 //Slog.v("PackageManager", "default service = " + sPackageManager);
1892 return sPackageManager;
1893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894
Romain Guy65b345f2011-07-27 18:51:50 -07001895 private Configuration mMainThreadConfig = new Configuration();
Amith Yamasani4f128e42016-05-10 11:44:12 -07001896
Dianne Hackborn908aecc2012-07-31 16:37:34 -07001897 Configuration applyConfigCompatMainThread(int displayDensity, Configuration config,
1898 CompatibilityInfo compat) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001899 if (config == null) {
1900 return null;
1901 }
Craig Mautner48d0d182013-06-11 07:53:06 -07001902 if (!compat.supportsScreen()) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001903 mMainThreadConfig.setTo(config);
1904 config = mMainThreadConfig;
Dianne Hackborn908aecc2012-07-31 16:37:34 -07001905 compat.applyToConfiguration(displayDensity, config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001906 }
1907 return config;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001910 /**
Todd Kennedy39bfee52016-02-24 10:28:21 -08001911 * Creates the top level resources for the given package. Will return an existing
1912 * Resources if one has already been created.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001913 */
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07001914 Resources getTopLevelResources(String resDir, String[] splitResDirs, String[] overlayDirs,
Adam Lesinski082614c2016-03-04 14:33:47 -08001915 String[] libDirs, int displayId, LoadedApk pkgInfo) {
1916 return mResourcesManager.getResources(null, resDir, splitResDirs, overlayDirs, libDirs,
1917 displayId, null, pkgInfo.getCompatibilityInfo(), pkgInfo.getClassLoader());
Todd Kennedy39bfee52016-02-24 10:28:21 -08001918 }
1919
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001920 final Handler getHandler() {
1921 return mH;
1922 }
1923
Todd Kennedy233a0b12018-01-29 20:30:24 +00001924 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
1925 int flags) {
1926 return getPackageInfo(packageName, compatInfo, flags, UserHandle.myUserId());
Amith Yamasani98edc952012-09-25 14:09:27 -07001927 }
1928
Todd Kennedy233a0b12018-01-29 20:30:24 +00001929 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
1930 int flags, int userId) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07001931 final boolean differentUser = (UserHandle.myUserId() != userId);
Craig Mautner88c05892013-06-28 09:47:45 -07001932 synchronized (mResourcesManager) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001933 WeakReference<LoadedApk> ref;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07001934 if (differentUser) {
1935 // Caching not supported across users
1936 ref = null;
1937 } else if ((flags & Context.CONTEXT_INCLUDE_CODE) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 ref = mPackages.get(packageName);
1939 } else {
1940 ref = mResourcePackages.get(packageName);
1941 }
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07001942
Todd Kennedy233a0b12018-01-29 20:30:24 +00001943 LoadedApk packageInfo = ref != null ? ref.get() : null;
1944 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
1945 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1946 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
1947 if (packageInfo != null && (packageInfo.mResources == null
1948 || packageInfo.mResources.getAssets().isUpToDate())) {
1949 if (packageInfo.isSecurityViolation()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1951 throw new SecurityException(
1952 "Requesting code from " + packageName
1953 + " to be run in process "
1954 + mBoundApplication.processName
1955 + "/" + mBoundApplication.appInfo.uid);
1956 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00001957 return packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 }
1959 }
1960
1961 ApplicationInfo ai = null;
1962 try {
1963 ai = getPackageManager().getApplicationInfo(packageName,
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001964 PackageManager.GET_SHARED_LIBRARY_FILES
1965 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1966 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001968 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 }
1970
1971 if (ai != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00001972 return getPackageInfo(ai, compatInfo, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 }
1974
1975 return null;
1976 }
1977
Todd Kennedy233a0b12018-01-29 20:30:24 +00001978 public final LoadedApk getPackageInfo(ApplicationInfo ai, CompatibilityInfo compatInfo,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001979 int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
1981 boolean securityViolation = includeCode && ai.uid != 0
1982 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001983 ? !UserHandle.isSameApp(ai.uid, mBoundApplication.appInfo.uid)
Amith Yamasani742a6712011-05-04 14:49:28 -07001984 : true);
Dianne Hackbornfee756f2014-07-16 17:31:10 -07001985 boolean registerPackage = includeCode && (flags&Context.CONTEXT_REGISTER_PACKAGE) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 if ((flags&(Context.CONTEXT_INCLUDE_CODE
1987 |Context.CONTEXT_IGNORE_SECURITY))
1988 == Context.CONTEXT_INCLUDE_CODE) {
1989 if (securityViolation) {
1990 String msg = "Requesting code from " + ai.packageName
1991 + " (with uid " + ai.uid + ")";
1992 if (mBoundApplication != null) {
1993 msg = msg + " to be run in process "
1994 + mBoundApplication.processName + " (with uid "
1995 + mBoundApplication.appInfo.uid + ")";
1996 }
1997 throw new SecurityException(msg);
1998 }
1999 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00002000 return getPackageInfo(ai, compatInfo, null, securityViolation, includeCode,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002001 registerPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 }
2003
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002004 @Override
Todd Kennedy233a0b12018-01-29 20:30:24 +00002005 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002006 CompatibilityInfo compatInfo) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002007 return getPackageInfo(ai, compatInfo, null, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 }
2009
Todd Kennedy233a0b12018-01-29 20:30:24 +00002010 public final LoadedApk peekPackageInfo(String packageName, boolean includeCode) {
Craig Mautner88c05892013-06-28 09:47:45 -07002011 synchronized (mResourcesManager) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002012 WeakReference<LoadedApk> ref;
2013 if (includeCode) {
2014 ref = mPackages.get(packageName);
2015 } else {
2016 ref = mResourcePackages.get(packageName);
2017 }
2018 return ref != null ? ref.get() : null;
2019 }
2020 }
2021
Todd Kennedy233a0b12018-01-29 20:30:24 +00002022 private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002023 ClassLoader baseLoader, boolean securityViolation, boolean includeCode,
2024 boolean registerPackage) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002025 final boolean differentUser = (UserHandle.myUserId() != UserHandle.getUserId(aInfo.uid));
Craig Mautner88c05892013-06-28 09:47:45 -07002026 synchronized (mResourcesManager) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002027 WeakReference<LoadedApk> ref;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002028 if (differentUser) {
2029 // Caching not supported across users
2030 ref = null;
2031 } else if (includeCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 ref = mPackages.get(aInfo.packageName);
2033 } else {
2034 ref = mResourcePackages.get(aInfo.packageName);
2035 }
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002036
Todd Kennedy233a0b12018-01-29 20:30:24 +00002037 LoadedApk packageInfo = ref != null ? ref.get() : null;
2038 if (packageInfo == null || (packageInfo.mResources != null
2039 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002040 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 : "Loading resource-only package ") + aInfo.packageName
2042 + " (in " + (mBoundApplication != null
2043 ? mBoundApplication.processName : null)
2044 + ")");
Todd Kennedy233a0b12018-01-29 20:30:24 +00002045 packageInfo =
Jeff Browndefd4a62014-03-10 21:24:37 -07002046 new LoadedApk(this, aInfo, compatInfo, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 securityViolation, includeCode &&
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002048 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0, registerPackage);
Narayan Kamathcb383182014-10-29 17:56:42 +00002049
2050 if (mSystemThread && "android".equals(aInfo.packageName)) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002051 packageInfo.installSystemApplicationInfo(aInfo,
2052 getSystemContext().mPackageInfo.getClassLoader());
Narayan Kamathcb383182014-10-29 17:56:42 +00002053 }
2054
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002055 if (differentUser) {
2056 // Caching not supported across users
2057 } else if (includeCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 mPackages.put(aInfo.packageName,
Todd Kennedy233a0b12018-01-29 20:30:24 +00002059 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 } else {
2061 mResourcePackages.put(aInfo.packageName,
Todd Kennedy233a0b12018-01-29 20:30:24 +00002062 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 }
2064 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00002065 return packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 }
2067 }
2068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 ActivityThread() {
Craig Mautner88c05892013-06-28 09:47:45 -07002070 mResourcesManager = ResourcesManager.getInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 }
2072
2073 public ApplicationThread getApplicationThread()
2074 {
2075 return mAppThread;
2076 }
2077
2078 public Instrumentation getInstrumentation()
2079 {
2080 return mInstrumentation;
2081 }
2082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 public boolean isProfiling() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002084 return mProfiler != null && mProfiler.profileFile != null
2085 && mProfiler.profileFd == null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 }
2087
2088 public String getProfileFilePath() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002089 return mProfiler.profileFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 }
2091
2092 public Looper getLooper() {
2093 return mLooper;
2094 }
2095
Jeff Sharkey8439ac02017-12-12 17:26:23 -07002096 public Executor getExecutor() {
2097 return mExecutor;
2098 }
2099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002100 public Application getApplication() {
2101 return mInitialApplication;
2102 }
Bob Leee5408332009-09-04 18:31:17 -07002103
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07002104 public String getProcessName() {
2105 return mBoundApplication.processName;
2106 }
Bob Leee5408332009-09-04 18:31:17 -07002107
Dianne Hackborn21556372010-02-04 16:34:40 -08002108 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 synchronized (this) {
2110 if (mSystemContext == null) {
Jeff Browndefd4a62014-03-10 21:24:37 -07002111 mSystemContext = ContextImpl.createSystemContext(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112 }
Jeff Browndefd4a62014-03-10 21:24:37 -07002113 return mSystemContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115 }
2116
Adam Lesinskia82b6262017-03-21 16:56:17 -07002117 public ContextImpl getSystemUiContext() {
2118 synchronized (this) {
2119 if (mSystemUiContext == null) {
Adam Lesinski6f1a9172017-04-10 16:35:19 -07002120 mSystemUiContext = ContextImpl.createSystemUiContext(getSystemContext());
Adam Lesinskia82b6262017-03-21 16:56:17 -07002121 }
2122 return mSystemUiContext;
2123 }
2124 }
2125
Narayan Kamath29564cd2014-08-07 10:57:40 +01002126 public void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
Mike Cleron432b7132009-09-24 15:28:29 -07002127 synchronized (this) {
Narayan Kamath29564cd2014-08-07 10:57:40 +01002128 getSystemContext().installSystemApplicationInfo(info, classLoader);
Adam Lesinskia82b6262017-03-21 16:56:17 -07002129 getSystemUiContext().installSystemApplicationInfo(info, classLoader);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002130
2131 // give ourselves a default profiler
2132 mProfiler = new Profiler();
Mike Cleron432b7132009-09-24 15:28:29 -07002133 }
2134 }
2135
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002136 void ensureJitEnabled() {
2137 if (!mJitEnabled) {
2138 mJitEnabled = true;
2139 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
2140 }
2141 }
Craig Mautner48d0d182013-06-11 07:53:06 -07002142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 void scheduleGcIdler() {
2144 if (!mGcIdlerScheduled) {
2145 mGcIdlerScheduled = true;
2146 Looper.myQueue().addIdleHandler(mGcIdler);
2147 }
2148 mH.removeMessages(H.GC_WHEN_IDLE);
2149 }
2150
2151 void unscheduleGcIdler() {
2152 if (mGcIdlerScheduled) {
2153 mGcIdlerScheduled = false;
2154 Looper.myQueue().removeIdleHandler(mGcIdler);
2155 }
2156 mH.removeMessages(H.GC_WHEN_IDLE);
2157 }
2158
2159 void doGcIfNeeded() {
2160 mGcIdlerScheduled = false;
2161 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002162 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 // + "m now=" + now);
2164 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002165 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002166 BinderInternal.forceGc("bg");
2167 }
2168 }
2169
Dianne Hackborne77187d2013-10-25 16:32:41 -07002170 private static final String HEAP_FULL_COLUMN
2171 = "%13s %8s %8s %8s %8s %8s %8s %8s %8s %8s %8s";
2172 private static final String HEAP_COLUMN
2173 = "%13s %8s %8s %8s %8s %8s %8s %8s";
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002174 private static final String ONE_COUNT_COLUMN = "%21s %8d";
2175 private static final String TWO_COUNT_COLUMNS = "%21s %8d %21s %8d";
2176 private static final String ONE_COUNT_COLUMN_HEADER = "%21s %8s";
Dianne Hackborne77187d2013-10-25 16:32:41 -07002177
2178 // Formatting for checkin service - update version if row format changes
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002179 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 4;
Dianne Hackborne77187d2013-10-25 16:32:41 -07002180
2181 static void printRow(PrintWriter pw, String format, Object...objs) {
2182 pw.println(String.format(format, objs));
2183 }
2184
Bryce Leed946f862018-01-16 15:59:47 -08002185 @Override
2186 public void dump(PrintWriter pw, String prefix) {
Bryce Leea33c13d2018-02-08 14:37:06 -08002187 pw.println(prefix + "Activities:");
Bryce Leed946f862018-01-16 15:59:47 -08002188
Bryce Leea33c13d2018-02-08 14:37:06 -08002189 if (!mActivities.isEmpty()) {
2190 final Iterator<Map.Entry<IBinder, ActivityClientRecord>> activitiesIterator =
2191 mActivities.entrySet().iterator();
2192
2193 while (activitiesIterator.hasNext()) {
2194 final ArrayMap.Entry<IBinder, ActivityClientRecord> entry =
2195 activitiesIterator.next();
2196 pw.println(prefix + " [token:" + entry.getKey().hashCode() + " record:"
2197 + entry.getValue().toString() + "]");
2198 }
Bryce Leed946f862018-01-16 15:59:47 -08002199 }
2200
Bryce Leea33c13d2018-02-08 14:37:06 -08002201 if (!mRecentDestroyedActivities.isEmpty()) {
2202 pw.println(prefix + "Recent destroyed activities:");
2203 for (int i = 0, size = mRecentDestroyedActivities.size(); i < size; i++) {
2204 final DestroyedActivityInfo info = mRecentDestroyedActivities.get(i);
2205 pw.print(prefix);
2206 info.dump(pw, " ");
2207 }
2208 }
Bryce Leed946f862018-01-16 15:59:47 -08002209 }
2210
Dianne Hackborne77187d2013-10-25 16:32:41 -07002211 public static void dumpMemInfoTable(PrintWriter pw, Debug.MemoryInfo memInfo, boolean checkin,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002212 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
2213 int pid, String processName,
Dianne Hackborne77187d2013-10-25 16:32:41 -07002214 long nativeMax, long nativeAllocated, long nativeFree,
2215 long dalvikMax, long dalvikAllocated, long dalvikFree) {
2216
2217 // For checkin, we print one long comma-separated list of values
2218 if (checkin) {
2219 // NOTE: if you change anything significant below, also consider changing
2220 // ACTIVITY_THREAD_CHECKIN_VERSION.
2221
2222 // Header
2223 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
2224 pw.print(pid); pw.print(',');
2225 pw.print(processName); pw.print(',');
2226
2227 // Heap info - max
2228 pw.print(nativeMax); pw.print(',');
2229 pw.print(dalvikMax); pw.print(',');
2230 pw.print("N/A,");
2231 pw.print(nativeMax + dalvikMax); pw.print(',');
2232
2233 // Heap info - allocated
2234 pw.print(nativeAllocated); pw.print(',');
2235 pw.print(dalvikAllocated); pw.print(',');
2236 pw.print("N/A,");
2237 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
2238
2239 // Heap info - free
2240 pw.print(nativeFree); pw.print(',');
2241 pw.print(dalvikFree); pw.print(',');
2242 pw.print("N/A,");
2243 pw.print(nativeFree + dalvikFree); pw.print(',');
2244
2245 // Heap info - proportional set size
2246 pw.print(memInfo.nativePss); pw.print(',');
2247 pw.print(memInfo.dalvikPss); pw.print(',');
2248 pw.print(memInfo.otherPss); pw.print(',');
2249 pw.print(memInfo.getTotalPss()); pw.print(',');
2250
2251 // Heap info - swappable set size
2252 pw.print(memInfo.nativeSwappablePss); pw.print(',');
2253 pw.print(memInfo.dalvikSwappablePss); pw.print(',');
2254 pw.print(memInfo.otherSwappablePss); pw.print(',');
2255 pw.print(memInfo.getTotalSwappablePss()); pw.print(',');
2256
2257 // Heap info - shared dirty
2258 pw.print(memInfo.nativeSharedDirty); pw.print(',');
2259 pw.print(memInfo.dalvikSharedDirty); pw.print(',');
2260 pw.print(memInfo.otherSharedDirty); pw.print(',');
2261 pw.print(memInfo.getTotalSharedDirty()); pw.print(',');
2262
2263 // Heap info - shared clean
2264 pw.print(memInfo.nativeSharedClean); pw.print(',');
2265 pw.print(memInfo.dalvikSharedClean); pw.print(',');
2266 pw.print(memInfo.otherSharedClean); pw.print(',');
2267 pw.print(memInfo.getTotalSharedClean()); pw.print(',');
2268
2269 // Heap info - private Dirty
2270 pw.print(memInfo.nativePrivateDirty); pw.print(',');
2271 pw.print(memInfo.dalvikPrivateDirty); pw.print(',');
2272 pw.print(memInfo.otherPrivateDirty); pw.print(',');
2273 pw.print(memInfo.getTotalPrivateDirty()); pw.print(',');
2274
2275 // Heap info - private Clean
2276 pw.print(memInfo.nativePrivateClean); pw.print(',');
2277 pw.print(memInfo.dalvikPrivateClean); pw.print(',');
2278 pw.print(memInfo.otherPrivateClean); pw.print(',');
2279 pw.print(memInfo.getTotalPrivateClean()); pw.print(',');
2280
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002281 // Heap info - swapped out
2282 pw.print(memInfo.nativeSwappedOut); pw.print(',');
2283 pw.print(memInfo.dalvikSwappedOut); pw.print(',');
2284 pw.print(memInfo.otherSwappedOut); pw.print(',');
2285 pw.print(memInfo.getTotalSwappedOut()); pw.print(',');
2286
2287 // Heap info - swapped out pss
2288 if (memInfo.hasSwappedOutPss) {
2289 pw.print(memInfo.nativeSwappedOutPss); pw.print(',');
2290 pw.print(memInfo.dalvikSwappedOutPss); pw.print(',');
2291 pw.print(memInfo.otherSwappedOutPss); pw.print(',');
2292 pw.print(memInfo.getTotalSwappedOutPss()); pw.print(',');
2293 } else {
2294 pw.print("N/A,");
2295 pw.print("N/A,");
2296 pw.print("N/A,");
2297 pw.print("N/A,");
2298 }
2299
Dianne Hackborne77187d2013-10-25 16:32:41 -07002300 // Heap info - other areas
2301 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
2302 pw.print(Debug.MemoryInfo.getOtherLabel(i)); pw.print(',');
2303 pw.print(memInfo.getOtherPss(i)); pw.print(',');
2304 pw.print(memInfo.getOtherSwappablePss(i)); pw.print(',');
2305 pw.print(memInfo.getOtherSharedDirty(i)); pw.print(',');
2306 pw.print(memInfo.getOtherSharedClean(i)); pw.print(',');
2307 pw.print(memInfo.getOtherPrivateDirty(i)); pw.print(',');
2308 pw.print(memInfo.getOtherPrivateClean(i)); pw.print(',');
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002309 pw.print(memInfo.getOtherSwappedOut(i)); pw.print(',');
2310 if (memInfo.hasSwappedOutPss) {
2311 pw.print(memInfo.getOtherSwappedOutPss(i)); pw.print(',');
2312 } else {
2313 pw.print("N/A,");
2314 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002315 }
2316 return;
2317 }
2318
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002319 if (!dumpSummaryOnly) {
2320 if (dumpFullInfo) {
2321 printRow(pw, HEAP_FULL_COLUMN, "", "Pss", "Pss", "Shared", "Private",
Martijn Coenene0764852016-01-07 17:04:22 -08002322 "Shared", "Private", memInfo.hasSwappedOutPss ? "SwapPss" : "Swap",
2323 "Heap", "Heap", "Heap");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002324 printRow(pw, HEAP_FULL_COLUMN, "", "Total", "Clean", "Dirty", "Dirty",
Martijn Coenene0764852016-01-07 17:04:22 -08002325 "Clean", "Clean", "Dirty",
2326 "Size", "Alloc", "Free");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002327 printRow(pw, HEAP_FULL_COLUMN, "", "------", "------", "------", "------",
2328 "------", "------", "------", "------", "------", "------");
2329 printRow(pw, HEAP_FULL_COLUMN, "Native Heap", memInfo.nativePss,
2330 memInfo.nativeSwappablePss, memInfo.nativeSharedDirty,
2331 memInfo.nativePrivateDirty, memInfo.nativeSharedClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002332 memInfo.nativePrivateClean, memInfo.hasSwappedOutPss ?
Richard Uhler91702eb32017-06-23 16:54:25 +01002333 memInfo.nativeSwappedOutPss : memInfo.nativeSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002334 nativeMax, nativeAllocated, nativeFree);
2335 printRow(pw, HEAP_FULL_COLUMN, "Dalvik Heap", memInfo.dalvikPss,
2336 memInfo.dalvikSwappablePss, memInfo.dalvikSharedDirty,
2337 memInfo.dalvikPrivateDirty, memInfo.dalvikSharedClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002338 memInfo.dalvikPrivateClean, memInfo.hasSwappedOutPss ?
Richard Uhler91702eb32017-06-23 16:54:25 +01002339 memInfo.dalvikSwappedOutPss : memInfo.dalvikSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002340 dalvikMax, dalvikAllocated, dalvikFree);
2341 } else {
2342 printRow(pw, HEAP_COLUMN, "", "Pss", "Private",
Martijn Coenene0764852016-01-07 17:04:22 -08002343 "Private", memInfo.hasSwappedOutPss ? "SwapPss" : "Swap",
2344 "Heap", "Heap", "Heap");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002345 printRow(pw, HEAP_COLUMN, "", "Total", "Dirty",
2346 "Clean", "Dirty", "Size", "Alloc", "Free");
2347 printRow(pw, HEAP_COLUMN, "", "------", "------", "------",
2348 "------", "------", "------", "------", "------");
2349 printRow(pw, HEAP_COLUMN, "Native Heap", memInfo.nativePss,
2350 memInfo.nativePrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002351 memInfo.nativePrivateClean,
2352 memInfo.hasSwappedOutPss ? memInfo.nativeSwappedOutPss :
2353 memInfo.nativeSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002354 nativeMax, nativeAllocated, nativeFree);
2355 printRow(pw, HEAP_COLUMN, "Dalvik Heap", memInfo.dalvikPss,
2356 memInfo.dalvikPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002357 memInfo.dalvikPrivateClean,
2358 memInfo.hasSwappedOutPss ? memInfo.dalvikSwappedOutPss :
2359 memInfo.dalvikSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002360 dalvikMax, dalvikAllocated, dalvikFree);
Dianne Hackborne77187d2013-10-25 16:32:41 -07002361 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002362
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002363 int otherPss = memInfo.otherPss;
2364 int otherSwappablePss = memInfo.otherSwappablePss;
2365 int otherSharedDirty = memInfo.otherSharedDirty;
2366 int otherPrivateDirty = memInfo.otherPrivateDirty;
2367 int otherSharedClean = memInfo.otherSharedClean;
2368 int otherPrivateClean = memInfo.otherPrivateClean;
2369 int otherSwappedOut = memInfo.otherSwappedOut;
Martijn Coenene0764852016-01-07 17:04:22 -08002370 int otherSwappedOutPss = memInfo.otherSwappedOutPss;
Dianne Hackborne77187d2013-10-25 16:32:41 -07002371
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002372 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
Dianne Hackborne77187d2013-10-25 16:32:41 -07002373 final int myPss = memInfo.getOtherPss(i);
2374 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2375 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2376 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2377 final int mySharedClean = memInfo.getOtherSharedClean(i);
2378 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2379 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
Martijn Coenene0764852016-01-07 17:04:22 -08002380 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Dianne Hackborne77187d2013-10-25 16:32:41 -07002381 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
Martijn Coenene0764852016-01-07 17:04:22 -08002382 || mySharedClean != 0 || myPrivateClean != 0
2383 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Dianne Hackborne77187d2013-10-25 16:32:41 -07002384 if (dumpFullInfo) {
2385 printRow(pw, HEAP_FULL_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2386 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002387 mySharedClean, myPrivateClean,
2388 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2389 "", "", "");
Dianne Hackborne77187d2013-10-25 16:32:41 -07002390 } else {
2391 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2392 myPss, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002393 myPrivateClean,
2394 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2395 "", "", "");
Dianne Hackborne77187d2013-10-25 16:32:41 -07002396 }
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002397 otherPss -= myPss;
2398 otherSwappablePss -= mySwappablePss;
2399 otherSharedDirty -= mySharedDirty;
2400 otherPrivateDirty -= myPrivateDirty;
2401 otherSharedClean -= mySharedClean;
2402 otherPrivateClean -= myPrivateClean;
2403 otherSwappedOut -= mySwappedOut;
Martijn Coenene0764852016-01-07 17:04:22 -08002404 otherSwappedOutPss -= mySwappedOutPss;
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002405 }
2406 }
2407
2408 if (dumpFullInfo) {
2409 printRow(pw, HEAP_FULL_COLUMN, "Unknown", otherPss, otherSwappablePss,
2410 otherSharedDirty, otherPrivateDirty, otherSharedClean, otherPrivateClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002411 memInfo.hasSwappedOutPss ? otherSwappedOutPss : otherSwappedOut,
2412 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002413 printRow(pw, HEAP_FULL_COLUMN, "TOTAL", memInfo.getTotalPss(),
2414 memInfo.getTotalSwappablePss(),
2415 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
2416 memInfo.getTotalSharedClean(), memInfo.getTotalPrivateClean(),
Thierry Strudel9b511602016-02-25 17:46:38 -08002417 memInfo.hasSwappedOutPss ? memInfo.getTotalSwappedOutPss() :
2418 memInfo.getTotalSwappedOut(),
Martijn Coenene0764852016-01-07 17:04:22 -08002419 nativeMax+dalvikMax, nativeAllocated+dalvikAllocated,
2420 nativeFree+dalvikFree);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002421 } else {
2422 printRow(pw, HEAP_COLUMN, "Unknown", otherPss,
Martijn Coenene0764852016-01-07 17:04:22 -08002423 otherPrivateDirty, otherPrivateClean,
2424 memInfo.hasSwappedOutPss ? otherSwappedOutPss : otherSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002425 "", "", "");
2426 printRow(pw, HEAP_COLUMN, "TOTAL", memInfo.getTotalPss(),
2427 memInfo.getTotalPrivateDirty(),
2428 memInfo.getTotalPrivateClean(),
Martijn Coenene0764852016-01-07 17:04:22 -08002429 memInfo.hasSwappedOutPss ? memInfo.getTotalSwappedOutPss() :
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002430 memInfo.getTotalSwappedOut(),
2431 nativeMax+dalvikMax,
2432 nativeAllocated+dalvikAllocated, nativeFree+dalvikFree);
2433 }
2434
2435 if (dumpDalvik) {
2436 pw.println(" ");
2437 pw.println(" Dalvik Details");
2438
2439 for (int i=Debug.MemoryInfo.NUM_OTHER_STATS;
2440 i<Debug.MemoryInfo.NUM_OTHER_STATS + Debug.MemoryInfo.NUM_DVK_STATS; i++) {
2441 final int myPss = memInfo.getOtherPss(i);
2442 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2443 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2444 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2445 final int mySharedClean = memInfo.getOtherSharedClean(i);
2446 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2447 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
Martijn Coenene0764852016-01-07 17:04:22 -08002448 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002449 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
Martijn Coenene0764852016-01-07 17:04:22 -08002450 || mySharedClean != 0 || myPrivateClean != 0
2451 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002452 if (dumpFullInfo) {
2453 printRow(pw, HEAP_FULL_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2454 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002455 mySharedClean, myPrivateClean,
2456 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2457 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002458 } else {
2459 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2460 myPss, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002461 myPrivateClean,
2462 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2463 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002464 }
2465 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002466 }
2467 }
2468 }
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002469
2470 pw.println(" ");
2471 pw.println(" App Summary");
2472 printRow(pw, ONE_COUNT_COLUMN_HEADER, "", "Pss(KB)");
2473 printRow(pw, ONE_COUNT_COLUMN_HEADER, "", "------");
2474 printRow(pw, ONE_COUNT_COLUMN,
2475 "Java Heap:", memInfo.getSummaryJavaHeap());
2476 printRow(pw, ONE_COUNT_COLUMN,
2477 "Native Heap:", memInfo.getSummaryNativeHeap());
2478 printRow(pw, ONE_COUNT_COLUMN,
2479 "Code:", memInfo.getSummaryCode());
2480 printRow(pw, ONE_COUNT_COLUMN,
2481 "Stack:", memInfo.getSummaryStack());
2482 printRow(pw, ONE_COUNT_COLUMN,
2483 "Graphics:", memInfo.getSummaryGraphics());
2484 printRow(pw, ONE_COUNT_COLUMN,
2485 "Private Other:", memInfo.getSummaryPrivateOther());
2486 printRow(pw, ONE_COUNT_COLUMN,
2487 "System:", memInfo.getSummarySystem());
2488 pw.println(" ");
Martijn Coenene0764852016-01-07 17:04:22 -08002489 if (memInfo.hasSwappedOutPss) {
2490 printRow(pw, TWO_COUNT_COLUMNS,
2491 "TOTAL:", memInfo.getSummaryTotalPss(),
2492 "TOTAL SWAP PSS:", memInfo.getSummaryTotalSwapPss());
2493 } else {
2494 printRow(pw, TWO_COUNT_COLUMNS,
2495 "TOTAL:", memInfo.getSummaryTotalPss(),
2496 "TOTAL SWAP (KB):", memInfo.getSummaryTotalSwap());
2497 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002498 }
2499
Kweku Adams598e9a22017-11-02 17:12:20 -07002500 /**
2501 * Dump heap info to proto.
2502 *
2503 * @param hasSwappedOutPss determines whether to use dirtySwap or dirtySwapPss
2504 */
Kweku Adams983829f2017-12-06 14:53:50 -08002505 private static void dumpMemoryInfo(ProtoOutputStream proto, long fieldId, String name,
Kweku Adams598e9a22017-11-02 17:12:20 -07002506 int pss, int cleanPss, int sharedDirty, int privateDirty,
2507 int sharedClean, int privateClean,
2508 boolean hasSwappedOutPss, int dirtySwap, int dirtySwapPss) {
2509 final long token = proto.start(fieldId);
2510
Kweku Adams983829f2017-12-06 14:53:50 -08002511 proto.write(MemInfoProto.ProcessMemory.MemoryInfo.NAME, name);
2512 proto.write(MemInfoProto.ProcessMemory.MemoryInfo.TOTAL_PSS_KB, pss);
2513 proto.write(MemInfoProto.ProcessMemory.MemoryInfo.CLEAN_PSS_KB, cleanPss);
2514 proto.write(MemInfoProto.ProcessMemory.MemoryInfo.SHARED_DIRTY_KB, sharedDirty);
2515 proto.write(MemInfoProto.ProcessMemory.MemoryInfo.PRIVATE_DIRTY_KB, privateDirty);
2516 proto.write(MemInfoProto.ProcessMemory.MemoryInfo.SHARED_CLEAN_KB, sharedClean);
2517 proto.write(MemInfoProto.ProcessMemory.MemoryInfo.PRIVATE_CLEAN_KB, privateClean);
Kweku Adams598e9a22017-11-02 17:12:20 -07002518 if (hasSwappedOutPss) {
Kweku Adams983829f2017-12-06 14:53:50 -08002519 proto.write(MemInfoProto.ProcessMemory.MemoryInfo.DIRTY_SWAP_PSS_KB, dirtySwapPss);
Kweku Adams598e9a22017-11-02 17:12:20 -07002520 } else {
Kweku Adams983829f2017-12-06 14:53:50 -08002521 proto.write(MemInfoProto.ProcessMemory.MemoryInfo.DIRTY_SWAP_KB, dirtySwap);
Kweku Adams598e9a22017-11-02 17:12:20 -07002522 }
2523
2524 proto.end(token);
2525 }
2526
2527 /**
2528 * Dump mem info data to proto.
2529 */
2530 public static void dumpMemInfoTable(ProtoOutputStream proto, Debug.MemoryInfo memInfo,
2531 boolean dumpDalvik, boolean dumpSummaryOnly,
2532 long nativeMax, long nativeAllocated, long nativeFree,
2533 long dalvikMax, long dalvikAllocated, long dalvikFree) {
2534
2535 if (!dumpSummaryOnly) {
Kweku Adams983829f2017-12-06 14:53:50 -08002536 final long nhToken = proto.start(MemInfoProto.ProcessMemory.NATIVE_HEAP);
2537 dumpMemoryInfo(proto, MemInfoProto.ProcessMemory.HeapInfo.MEM_INFO, "Native Heap",
Kweku Adams598e9a22017-11-02 17:12:20 -07002538 memInfo.nativePss, memInfo.nativeSwappablePss, memInfo.nativeSharedDirty,
2539 memInfo.nativePrivateDirty, memInfo.nativeSharedClean,
2540 memInfo.nativePrivateClean, memInfo.hasSwappedOutPss,
2541 memInfo.nativeSwappedOut, memInfo.nativeSwappedOutPss);
Kweku Adams983829f2017-12-06 14:53:50 -08002542 proto.write(MemInfoProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB, nativeMax);
2543 proto.write(MemInfoProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB, nativeAllocated);
2544 proto.write(MemInfoProto.ProcessMemory.HeapInfo.HEAP_FREE_KB, nativeFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002545 proto.end(nhToken);
2546
Kweku Adams983829f2017-12-06 14:53:50 -08002547 final long dvToken = proto.start(MemInfoProto.ProcessMemory.DALVIK_HEAP);
2548 dumpMemoryInfo(proto, MemInfoProto.ProcessMemory.HeapInfo.MEM_INFO, "Dalvik Heap",
Kweku Adams598e9a22017-11-02 17:12:20 -07002549 memInfo.dalvikPss, memInfo.dalvikSwappablePss, memInfo.dalvikSharedDirty,
2550 memInfo.dalvikPrivateDirty, memInfo.dalvikSharedClean,
2551 memInfo.dalvikPrivateClean, memInfo.hasSwappedOutPss,
2552 memInfo.dalvikSwappedOut, memInfo.dalvikSwappedOutPss);
Kweku Adams983829f2017-12-06 14:53:50 -08002553 proto.write(MemInfoProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB, dalvikMax);
2554 proto.write(MemInfoProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB, dalvikAllocated);
2555 proto.write(MemInfoProto.ProcessMemory.HeapInfo.HEAP_FREE_KB, dalvikFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002556 proto.end(dvToken);
2557
2558 int otherPss = memInfo.otherPss;
2559 int otherSwappablePss = memInfo.otherSwappablePss;
2560 int otherSharedDirty = memInfo.otherSharedDirty;
2561 int otherPrivateDirty = memInfo.otherPrivateDirty;
2562 int otherSharedClean = memInfo.otherSharedClean;
2563 int otherPrivateClean = memInfo.otherPrivateClean;
2564 int otherSwappedOut = memInfo.otherSwappedOut;
2565 int otherSwappedOutPss = memInfo.otherSwappedOutPss;
2566
2567 for (int i = 0; i < Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
2568 final int myPss = memInfo.getOtherPss(i);
2569 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2570 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2571 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2572 final int mySharedClean = memInfo.getOtherSharedClean(i);
2573 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2574 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
2575 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
2576 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
2577 || mySharedClean != 0 || myPrivateClean != 0
2578 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Kweku Adams983829f2017-12-06 14:53:50 -08002579 dumpMemoryInfo(proto, MemInfoProto.ProcessMemory.OTHER_HEAPS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002580 Debug.MemoryInfo.getOtherLabel(i),
2581 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
2582 mySharedClean, myPrivateClean,
2583 memInfo.hasSwappedOutPss, mySwappedOut, mySwappedOutPss);
2584
2585 otherPss -= myPss;
2586 otherSwappablePss -= mySwappablePss;
2587 otherSharedDirty -= mySharedDirty;
2588 otherPrivateDirty -= myPrivateDirty;
2589 otherSharedClean -= mySharedClean;
2590 otherPrivateClean -= myPrivateClean;
2591 otherSwappedOut -= mySwappedOut;
2592 otherSwappedOutPss -= mySwappedOutPss;
2593 }
2594 }
2595
Kweku Adams983829f2017-12-06 14:53:50 -08002596 dumpMemoryInfo(proto, MemInfoProto.ProcessMemory.UNKNOWN_HEAP, "Unknown",
Kweku Adams598e9a22017-11-02 17:12:20 -07002597 otherPss, otherSwappablePss,
2598 otherSharedDirty, otherPrivateDirty, otherSharedClean, otherPrivateClean,
2599 memInfo.hasSwappedOutPss, otherSwappedOut, otherSwappedOutPss);
Kweku Adams983829f2017-12-06 14:53:50 -08002600 final long tToken = proto.start(MemInfoProto.ProcessMemory.TOTAL_HEAP);
2601 dumpMemoryInfo(proto, MemInfoProto.ProcessMemory.HeapInfo.MEM_INFO, "TOTAL",
Kweku Adams598e9a22017-11-02 17:12:20 -07002602 memInfo.getTotalPss(), memInfo.getTotalSwappablePss(),
2603 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
2604 memInfo.getTotalSharedClean(), memInfo.getTotalPrivateClean(),
2605 memInfo.hasSwappedOutPss, memInfo.getTotalSwappedOut(),
2606 memInfo.getTotalSwappedOutPss());
Kweku Adams983829f2017-12-06 14:53:50 -08002607 proto.write(MemInfoProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB, nativeMax + dalvikMax);
2608 proto.write(MemInfoProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002609 nativeAllocated + dalvikAllocated);
Kweku Adams983829f2017-12-06 14:53:50 -08002610 proto.write(MemInfoProto.ProcessMemory.HeapInfo.HEAP_FREE_KB, nativeFree + dalvikFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002611 proto.end(tToken);
2612
2613 if (dumpDalvik) {
2614 for (int i = Debug.MemoryInfo.NUM_OTHER_STATS;
2615 i < Debug.MemoryInfo.NUM_OTHER_STATS + Debug.MemoryInfo.NUM_DVK_STATS;
2616 i++) {
2617 final int myPss = memInfo.getOtherPss(i);
2618 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2619 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2620 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2621 final int mySharedClean = memInfo.getOtherSharedClean(i);
2622 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2623 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
2624 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
2625 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
2626 || mySharedClean != 0 || myPrivateClean != 0
2627 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Kweku Adams983829f2017-12-06 14:53:50 -08002628 dumpMemoryInfo(proto, MemInfoProto.ProcessMemory.DALVIK_DETAILS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002629 Debug.MemoryInfo.getOtherLabel(i),
2630 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
2631 mySharedClean, myPrivateClean,
2632 memInfo.hasSwappedOutPss, mySwappedOut, mySwappedOutPss);
2633 }
2634 }
2635 }
2636 }
2637
Kweku Adams983829f2017-12-06 14:53:50 -08002638 final long asToken = proto.start(MemInfoProto.ProcessMemory.APP_SUMMARY);
2639 proto.write(MemInfoProto.ProcessMemory.AppSummary.JAVA_HEAP_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002640 memInfo.getSummaryJavaHeap());
Kweku Adams983829f2017-12-06 14:53:50 -08002641 proto.write(MemInfoProto.ProcessMemory.AppSummary.NATIVE_HEAP_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002642 memInfo.getSummaryNativeHeap());
Kweku Adams983829f2017-12-06 14:53:50 -08002643 proto.write(MemInfoProto.ProcessMemory.AppSummary.CODE_PSS_KB, memInfo.getSummaryCode());
2644 proto.write(MemInfoProto.ProcessMemory.AppSummary.STACK_PSS_KB, memInfo.getSummaryStack());
2645 proto.write(MemInfoProto.ProcessMemory.AppSummary.GRAPHICS_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002646 memInfo.getSummaryGraphics());
Kweku Adams983829f2017-12-06 14:53:50 -08002647 proto.write(MemInfoProto.ProcessMemory.AppSummary.PRIVATE_OTHER_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002648 memInfo.getSummaryPrivateOther());
Kweku Adams983829f2017-12-06 14:53:50 -08002649 proto.write(MemInfoProto.ProcessMemory.AppSummary.SYSTEM_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002650 memInfo.getSummarySystem());
2651 if (memInfo.hasSwappedOutPss) {
Kweku Adams983829f2017-12-06 14:53:50 -08002652 proto.write(MemInfoProto.ProcessMemory.AppSummary.TOTAL_SWAP_PSS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002653 memInfo.getSummaryTotalSwapPss());
2654 } else {
Kweku Adams983829f2017-12-06 14:53:50 -08002655 proto.write(MemInfoProto.ProcessMemory.AppSummary.TOTAL_SWAP_PSS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002656 memInfo.getSummaryTotalSwap());
2657 }
2658 proto.end(asToken);
2659 }
2660
Jeff Hamilton52d32032011-01-08 15:31:26 -06002661 public void registerOnActivityPausedListener(Activity activity,
2662 OnActivityPausedListener listener) {
2663 synchronized (mOnPauseListeners) {
2664 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
2665 if (list == null) {
2666 list = new ArrayList<OnActivityPausedListener>();
2667 mOnPauseListeners.put(activity, list);
2668 }
2669 list.add(listener);
2670 }
2671 }
2672
Jeff Hamiltonce3224c2011-01-17 11:05:03 -08002673 public void unregisterOnActivityPausedListener(Activity activity,
2674 OnActivityPausedListener listener) {
2675 synchronized (mOnPauseListeners) {
2676 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
2677 if (list != null) {
2678 list.remove(listener);
2679 }
2680 }
2681 }
2682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 public final ActivityInfo resolveActivityInfo(Intent intent) {
2684 ActivityInfo aInfo = intent.resolveActivityInfo(
2685 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
2686 if (aInfo == null) {
2687 // Throw an exception.
2688 Instrumentation.checkStartActivityResult(
Dianne Hackborna4972e92012-03-14 10:38:05 -07002689 ActivityManager.START_CLASS_NOT_FOUND, intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 }
2691 return aInfo;
2692 }
Bob Leee5408332009-09-04 18:31:17 -07002693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002695 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002696 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002697 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002699 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 r.intent = intent;
2701 r.state = state;
2702 r.parent = parent;
2703 r.embeddedID = id;
2704 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002705 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 if (localLOGV) {
2707 ComponentName compname = intent.getComponent();
2708 String name;
2709 if (compname != null) {
2710 name = compname.toShortString();
2711 } else {
2712 name = "(Intent " + intent + ").getComponent() returned null";
2713 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002714 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715 + ", comp=" + name
2716 + ", token=" + token);
2717 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002718 // TODO(lifecycler): Can't switch to use #handleLaunchActivity() because it will try to
2719 // call #reportSizeConfigurations(), but the server might not know anything about the
2720 // activity if it was launched from LocalAcvitivyManager.
2721 return performLaunchActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 }
2723
2724 public final Activity getActivity(IBinder token) {
2725 return mActivities.get(token).activity;
2726 }
2727
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002728 @Override
2729 public ActivityClientRecord getActivityClient(IBinder token) {
2730 return mActivities.get(token);
2731 }
2732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 public final void sendActivityResult(
2734 IBinder token, String id, int requestCode,
2735 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002736 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07002737 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2739 list.add(new ResultInfo(id, requestCode, resultCode, data));
Andrii Kulian9c5ea9c2017-12-07 09:31:01 -08002740 final ClientTransaction clientTransaction = ClientTransaction.obtain(mAppThread, token);
2741 clientTransaction.addCallback(ActivityResultItem.obtain(list));
Andrii Kulian446e8242017-10-26 15:17:29 -07002742 try {
2743 mAppThread.scheduleTransaction(clientTransaction);
2744 } catch (RemoteException e) {
2745 // Local scheduling
2746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 }
2748
Andrii Kulian446e8242017-10-26 15:17:29 -07002749 void sendMessage(int what, Object obj) {
Jeff Brown9ef09972013-10-15 20:49:59 -07002750 sendMessage(what, obj, 0, 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002751 }
2752
Jeff Brown9ef09972013-10-15 20:49:59 -07002753 private void sendMessage(int what, Object obj, int arg1) {
2754 sendMessage(what, obj, arg1, 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 }
2756
Jeff Brown9ef09972013-10-15 20:49:59 -07002757 private void sendMessage(int what, Object obj, int arg1, int arg2) {
2758 sendMessage(what, obj, arg1, arg2, false);
2759 }
2760
2761 private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
2762 if (DEBUG_MESSAGES) Slog.v(
2763 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
2764 + ": " + arg1 + " / " + obj);
2765 Message msg = Message.obtain();
2766 msg.what = what;
2767 msg.obj = obj;
2768 msg.arg1 = arg1;
2769 msg.arg2 = arg2;
2770 if (async) {
2771 msg.setAsynchronous(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002772 }
Jeff Brown9ef09972013-10-15 20:49:59 -07002773 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774 }
2775
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07002776 private void sendMessage(int what, Object obj, int arg1, int arg2, int seq) {
2777 if (DEBUG_MESSAGES) Slog.v(
2778 TAG, "SCHEDULE " + mH.codeToString(what) + " arg1=" + arg1 + " arg2=" + arg2 +
2779 "seq= " + seq);
2780 Message msg = Message.obtain();
2781 msg.what = what;
2782 SomeArgs args = SomeArgs.obtain();
2783 args.arg1 = obj;
2784 args.argi1 = arg1;
2785 args.argi2 = arg2;
2786 args.argi3 = seq;
2787 msg.obj = args;
2788 mH.sendMessage(msg);
2789 }
2790
Dianne Hackborn21556372010-02-04 16:34:40 -08002791 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002792 String what) {
2793 ContextCleanupInfo cci = new ContextCleanupInfo();
2794 cci.context = context;
2795 cci.who = who;
2796 cci.what = what;
Jeff Brown9ef09972013-10-15 20:49:59 -07002797 sendMessage(H.CLEAN_UP_CONTEXT, cci);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798 }
2799
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002800 /** Core implementation of activity launch. */
2801 private Activity performLaunchActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002802 ActivityInfo aInfo = r.activityInfo;
Todd Kennedy233a0b12018-01-29 20:30:24 +00002803 if (r.packageInfo == null) {
2804 r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002805 Context.CONTEXT_INCLUDE_CODE);
2806 }
Bob Leee5408332009-09-04 18:31:17 -07002807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 ComponentName component = r.intent.getComponent();
2809 if (component == null) {
2810 component = r.intent.resolveActivity(
2811 mInitialApplication.getPackageManager());
2812 r.intent.setComponent(component);
2813 }
2814
2815 if (r.activityInfo.targetActivity != null) {
2816 component = new ComponentName(r.activityInfo.packageName,
2817 r.activityInfo.targetActivity);
2818 }
2819
Adam Lesinski4e862812016-11-21 16:02:24 -08002820 ContextImpl appContext = createBaseContextForActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 Activity activity = null;
2822 try {
Adam Lesinski4e862812016-11-21 16:02:24 -08002823 java.lang.ClassLoader cl = appContext.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04002824 activity = mInstrumentation.newActivity(
2825 cl, component.getClassName(), r.intent);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002826 StrictMode.incrementExpectedActivityCount(activity.getClass());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 r.intent.setExtrasClassLoader(cl);
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01002828 r.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 if (r.state != null) {
2830 r.state.setClassLoader(cl);
2831 }
2832 } catch (Exception e) {
2833 if (!mInstrumentation.onException(activity, e)) {
2834 throw new RuntimeException(
2835 "Unable to instantiate activity " + component
2836 + ": " + e.toString(), e);
2837 }
2838 }
2839
2840 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002841 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07002842
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002843 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
2844 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 TAG, r + ": app=" + app
2846 + ", appName=" + app.getPackageName()
Todd Kennedy233a0b12018-01-29 20:30:24 +00002847 + ", pkg=" + r.packageInfo.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 + ", comp=" + r.intent.getComponent().toShortString()
Todd Kennedy233a0b12018-01-29 20:30:24 +00002849 + ", dir=" + r.packageInfo.getAppDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850
2851 if (activity != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002853 Configuration config = new Configuration(mCompatConfiguration);
Andrii Kuliand0ad9382016-04-18 20:54:20 -07002854 if (r.overrideConfig != null) {
2855 config.updateFrom(r.overrideConfig);
2856 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002857 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002858 + r.activityInfo.name + " with config " + config);
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07002859 Window window = null;
2860 if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
2861 window = r.mPendingRemoveWindow;
2862 r.mPendingRemoveWindow = null;
2863 r.mPendingRemoveWindowManager = null;
2864 }
Adam Lesinski4e862812016-11-21 16:02:24 -08002865 appContext.setOuterContext(activity);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002866 activity.attach(appContext, this, getInstrumentation(), r.token,
2867 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Craig Mautner233ceee2014-05-09 17:05:11 -07002868 r.embeddedID, r.lastNonConfigurationInstances, config,
Andrii Kulian51c1b672017-04-07 18:39:32 -07002869 r.referrer, r.voiceInteractor, window, r.configCallback);
Bob Leee5408332009-09-04 18:31:17 -07002870
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002871 r.lastNonConfigurationInstances = null;
Sudheer Shanka84a48952017-03-08 18:19:01 -08002872 checkAndBlockForNetworkAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 activity.mStartedActivity = false;
2874 int theme = r.activityInfo.getThemeResource();
2875 if (theme != 0) {
2876 activity.setTheme(theme);
2877 }
2878
2879 activity.mCalled = false;
Craig Mautnera0026042014-04-23 11:45:37 -07002880 if (r.isPersistable()) {
2881 mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
2882 } else {
2883 mInstrumentation.callActivityOnCreate(activity, r.state);
2884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 if (!activity.mCalled) {
2886 throw new SuperNotCalledException(
2887 "Activity " + r.intent.getComponent().toShortString() +
2888 " did not call through to super.onCreate()");
2889 }
2890 r.activity = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002892 r.setState(ON_CREATE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893
2894 mActivities.put(r.token, r);
2895
2896 } catch (SuperNotCalledException e) {
2897 throw e;
2898
2899 } catch (Exception e) {
2900 if (!mInstrumentation.onException(activity, e)) {
2901 throw new RuntimeException(
2902 "Unable to start activity " + component
2903 + ": " + e.toString(), e);
2904 }
2905 }
2906
2907 return activity;
2908 }
2909
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002910 @Override
2911 public void handleStartActivity(ActivityClientRecord r,
2912 PendingTransactionActions pendingActions) {
2913 final Activity activity = r.activity;
2914 if (r.activity == null) {
2915 // TODO(lifecycler): What do we do in this case?
2916 return;
2917 }
2918 if (!r.stopped) {
2919 throw new IllegalStateException("Can't start activity that is not stopped.");
2920 }
2921 if (r.activity.mFinished) {
2922 // TODO(lifecycler): How can this happen?
2923 return;
2924 }
2925
2926 // Start
2927 activity.performStart();
2928 r.setState(ON_START);
2929
2930 if (pendingActions == null) {
2931 // No more work to do.
2932 return;
2933 }
2934
2935 // Restore instance state
2936 if (pendingActions.shouldRestoreInstanceState()) {
2937 if (r.isPersistable()) {
2938 if (r.state != null || r.persistentState != null) {
2939 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
2940 r.persistentState);
2941 }
2942 } else if (r.state != null) {
2943 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
2944 }
2945 }
2946
2947 // Call postOnCreate()
2948 if (pendingActions.shouldCallOnPostCreate()) {
2949 activity.mCalled = false;
2950 if (r.isPersistable()) {
2951 mInstrumentation.callActivityOnPostCreate(activity, r.state,
2952 r.persistentState);
2953 } else {
2954 mInstrumentation.callActivityOnPostCreate(activity, r.state);
2955 }
2956 if (!activity.mCalled) {
2957 throw new SuperNotCalledException(
2958 "Activity " + r.intent.getComponent().toShortString()
2959 + " did not call through to super.onPostCreate()");
2960 }
2961 }
2962 }
2963
Sudheer Shanka84a48952017-03-08 18:19:01 -08002964 /**
2965 * Checks if {@link #mNetworkBlockSeq} is {@link #INVALID_PROC_STATE_SEQ} and if so, returns
2966 * immediately. Otherwise, makes a blocking call to ActivityManagerService to wait for the
2967 * network rules to get updated.
2968 */
2969 private void checkAndBlockForNetworkAccess() {
2970 synchronized (mNetworkPolicyLock) {
2971 if (mNetworkBlockSeq != INVALID_PROC_STATE_SEQ) {
2972 try {
2973 ActivityManager.getService().waitForNetworkStateUpdate(mNetworkBlockSeq);
2974 mNetworkBlockSeq = INVALID_PROC_STATE_SEQ;
2975 } catch (RemoteException ignored) {}
2976 }
2977 }
2978 }
2979
Adam Lesinski4e862812016-11-21 16:02:24 -08002980 private ContextImpl createBaseContextForActivity(ActivityClientRecord r) {
2981 final int displayId;
Craig Mautnere0a38842013-12-16 16:14:02 -08002982 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002983 displayId = ActivityManager.getService().getActivityDisplayId(r.token);
Craig Mautnere0a38842013-12-16 16:14:02 -08002984 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002985 throw e.rethrowFromSystemServer();
Craig Mautnere0a38842013-12-16 16:14:02 -08002986 }
Jeff Brownefd43bd2012-09-21 17:02:35 -07002987
Wale Ogunwale7c726682015-02-06 17:34:28 -08002988 ContextImpl appContext = ContextImpl.createActivityContext(
Todd Kennedy233a0b12018-01-29 20:30:24 +00002989 this, r.packageInfo, r.activityInfo, r.token, displayId, r.overrideConfig);
Wale Ogunwale7c726682015-02-06 17:34:28 -08002990
2991 final DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance();
Jeff Brownefd43bd2012-09-21 17:02:35 -07002992 // For debugging purposes, if the activity's package name contains the value of
2993 // the "debug.use-second-display" system property as a substring, then show
2994 // its content on a secondary display if there is one.
Jeff Brownefd43bd2012-09-21 17:02:35 -07002995 String pkgName = SystemProperties.get("debug.second-display.pkg");
2996 if (pkgName != null && !pkgName.isEmpty()
Todd Kennedy233a0b12018-01-29 20:30:24 +00002997 && r.packageInfo.mPackageName.contains(pkgName)) {
Wale Ogunwale7c726682015-02-06 17:34:28 -08002998 for (int id : dm.getDisplayIds()) {
2999 if (id != Display.DEFAULT_DISPLAY) {
Wale Ogunwale26698512015-06-05 16:55:33 -07003000 Display display =
Bryce Lee609bf652017-02-09 16:50:13 -08003001 dm.getCompatibleDisplay(id, appContext.getResources());
Adam Lesinski4e862812016-11-21 16:02:24 -08003002 appContext = (ContextImpl) appContext.createDisplayContext(display);
Jeff Brownefd43bd2012-09-21 17:02:35 -07003003 break;
3004 }
3005 }
3006 }
Adam Lesinski4e862812016-11-21 16:02:24 -08003007 return appContext;
Jeff Brownefd43bd2012-09-21 17:02:35 -07003008 }
3009
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003010 /**
3011 * Extended implementation of activity launch. Used when server requests a launch or relaunch.
3012 */
Andrii Kulian446e8242017-10-26 15:17:29 -07003013 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003014 public Activity handleLaunchActivity(ActivityClientRecord r,
3015 PendingTransactionActions pendingActions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016 // If we are getting ready to gc after going to the background, well
3017 // we are back active so skip it.
3018 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003019 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003020
Jeff Hao1b012d32014-08-20 10:35:34 -07003021 if (r.profilerInfo != null) {
3022 mProfiler.setProfiler(r.profilerInfo);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003023 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003024 }
3025
Dianne Hackborn58f42a52011-10-10 13:46:34 -07003026 // Make sure we are running with the most recent config.
3027 handleConfigurationChanged(null, null);
3028
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003029 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003030 TAG, "Handling launch of " + r);
Adam Powellcfbe9be2013-11-06 14:58:58 -08003031
Chet Haase0d1c27a2014-11-03 18:35:16 +00003032 // Initialize before creating the activity
Jesse Hallc37984f2017-05-23 16:55:08 -07003033 if (!ThreadedRenderer.sRendererDisabled) {
3034 GraphicsEnvironment.earlyInitEGL();
3035 }
Chet Haase0d1c27a2014-11-03 18:35:16 +00003036 WindowManagerGlobal.initialize();
3037
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003038 final Activity a = performLaunchActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003039
3040 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003041 r.createdConfig = new Configuration(mConfiguration);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003042 reportSizeConfigurations(r);
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003043 if (!r.activity.mFinished && pendingActions != null) {
3044 pendingActions.setOldState(r.state);
3045 pendingActions.setRestoreInstanceState(true);
3046 pendingActions.setCallOnPostCreate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047 }
3048 } else {
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07003049 // If there was an error, for any reason, tell the activity manager to stop us.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003050 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003051 ActivityManager.getService()
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003052 .finishActivity(r.token, Activity.RESULT_CANCELED, null,
3053 Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003055 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056 }
3057 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003058
3059 return a;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003060 }
3061
Filip Gruszczynski23493322015-07-29 17:02:59 -07003062 private void reportSizeConfigurations(ActivityClientRecord r) {
3063 Configuration[] configurations = r.activity.getResources().getSizeConfigurations();
3064 if (configurations == null) {
3065 return;
3066 }
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003067 SparseIntArray horizontal = new SparseIntArray();
3068 SparseIntArray vertical = new SparseIntArray();
3069 SparseIntArray smallest = new SparseIntArray();
Filip Gruszczynski23493322015-07-29 17:02:59 -07003070 for (int i = configurations.length - 1; i >= 0; i--) {
3071 Configuration config = configurations[i];
3072 if (config.screenHeightDp != Configuration.SCREEN_HEIGHT_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003073 vertical.put(config.screenHeightDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003074 }
3075 if (config.screenWidthDp != Configuration.SCREEN_WIDTH_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003076 horizontal.put(config.screenWidthDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003077 }
3078 if (config.smallestScreenWidthDp != Configuration.SMALLEST_SCREEN_WIDTH_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003079 smallest.put(config.smallestScreenWidthDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003080 }
3081 }
Filip Gruszczynski23493322015-07-29 17:02:59 -07003082 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003083 ActivityManager.getService().reportSizeConfigurations(r.token,
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003084 horizontal.copyKeys(), vertical.copyKeys(), smallest.copyKeys());
Filip Gruszczynski23493322015-07-29 17:02:59 -07003085 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003086 throw ex.rethrowFromSystemServer();
Filip Gruszczynski23493322015-07-29 17:02:59 -07003087 }
3088
3089 }
3090
Dianne Hackborn85d558c2014-11-04 10:31:54 -08003091 private void deliverNewIntents(ActivityClientRecord r, List<ReferrerIntent> intents) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 final int N = intents.size();
3093 for (int i=0; i<N; i++) {
Dianne Hackborna01a0fa2014-12-02 10:33:14 -08003094 ReferrerIntent intent = intents.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003095 intent.setExtrasClassLoader(r.activity.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003096 intent.prepareToEnterProcess();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003097 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
3099 }
3100 }
3101
Wale Ogunwale826c7062016-09-13 08:25:54 -07003102 void performNewIntents(IBinder token, List<ReferrerIntent> intents, boolean andPause) {
3103 final ActivityClientRecord r = mActivities.get(token);
3104 if (r == null) {
3105 return;
3106 }
3107
3108 final boolean resumed = !r.paused;
3109 if (resumed) {
3110 r.activity.mTemporaryPause = true;
3111 mInstrumentation.callActivityOnPause(r.activity);
3112 }
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07003113 checkAndBlockForNetworkAccess();
Wale Ogunwale826c7062016-09-13 08:25:54 -07003114 deliverNewIntents(r, intents);
3115 if (resumed) {
Dake Gu67decfa2017-12-27 11:48:08 -08003116 r.activity.performResume(false);
Wale Ogunwale826c7062016-09-13 08:25:54 -07003117 r.activity.mTemporaryPause = false;
3118 }
3119
3120 if (r.paused && andPause) {
3121 // In this case the activity was in the paused state when we delivered the intent,
3122 // to guarantee onResume gets called after onNewIntent we temporarily resume the
3123 // activity and pause again as the caller wanted.
3124 performResumeActivity(token, false, "performNewIntents");
3125 performPauseActivityIfNeeded(r, "performNewIntents");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 }
3127 }
Bob Leee5408332009-09-04 18:31:17 -07003128
Andrii Kulian446e8242017-10-26 15:17:29 -07003129 @Override
3130 public void handleNewIntent(IBinder token, List<ReferrerIntent> intents, boolean andPause) {
3131 performNewIntents(token, intents, andPause);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 }
3133
Adam Skorydfc7fd72013-08-05 19:23:41 -07003134 public void handleRequestAssistContextExtras(RequestAssistContextExtras cmd) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003135 // Filling for autofill has a few differences:
Felipe Leme1ca634a2016-11-28 17:21:21 -08003136 // - it does not need an AssistContent
3137 // - it does not call onProvideAssistData()
3138 // - it needs an IAutoFillCallback
Felipe Leme640f30a2017-03-06 15:44:06 -08003139 boolean forAutofill = cmd.requestType == ActivityManager.ASSIST_CONTEXT_AUTOFILL;
Felipe Leme1ca634a2016-11-28 17:21:21 -08003140
Felipe Leme85d1c2d2017-04-21 08:56:04 -07003141 // TODO: decide if lastSessionId logic applies to autofill sessions
Amith Yamasani4f128e42016-05-10 11:44:12 -07003142 if (mLastSessionId != cmd.sessionId) {
3143 // Clear the existing structures
3144 mLastSessionId = cmd.sessionId;
3145 for (int i = mLastAssistStructures.size() - 1; i >= 0; i--) {
3146 AssistStructure structure = mLastAssistStructures.get(i).get();
3147 if (structure != null) {
3148 structure.clearSendChannel();
3149 }
3150 mLastAssistStructures.remove(i);
Dianne Hackborn782d4982015-07-08 17:36:37 -07003151 }
3152 }
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003153
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003154 Bundle data = new Bundle();
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003155 AssistStructure structure = null;
Felipe Leme640f30a2017-03-06 15:44:06 -08003156 AssistContent content = forAutofill ? null : new AssistContent();
Amith Yamasani858f98d2017-02-22 12:59:53 -08003157 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003158 ActivityClientRecord r = mActivities.get(cmd.activityToken);
Dianne Hackborna3acdb32015-06-08 17:07:40 -07003159 Uri referrer = null;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003160 if (r != null) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003161 if (!forAutofill) {
Felipe Leme1ca634a2016-11-28 17:21:21 -08003162 r.activity.getApplication().dispatchOnProvideAssistData(r.activity, data);
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003163 r.activity.onProvideAssistData(data);
Felipe Leme6d553872016-12-08 17:13:25 -08003164 referrer = r.activity.onProvideReferrer();
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003165 }
Felipe Leme640f30a2017-03-06 15:44:06 -08003166 if (cmd.requestType == ActivityManager.ASSIST_CONTEXT_FULL || forAutofill) {
Svet Ganovfd31f852017-04-26 15:54:27 -07003167 structure = new AssistStructure(r.activity, forAutofill, cmd.flags);
Adam Skory4aaed142015-04-22 11:29:31 -06003168 Intent activityIntent = r.activity.getIntent();
Felipe Leme6d553872016-12-08 17:13:25 -08003169 boolean notSecure = r.window == null ||
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003170 (r.window.getAttributes().flags
Felipe Leme6d553872016-12-08 17:13:25 -08003171 & WindowManager.LayoutParams.FLAG_SECURE) == 0;
3172 if (activityIntent != null && notSecure) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003173 if (!forAutofill) {
Felipe Leme1ca634a2016-11-28 17:21:21 -08003174 Intent intent = new Intent(activityIntent);
3175 intent.setFlags(intent.getFlags() & ~(Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3176 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION));
3177 intent.removeUnsafeExtras();
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003178 content.setDefaultIntent(intent);
3179 }
Adam Skory4aaed142015-04-22 11:29:31 -06003180 } else {
Felipe Leme640f30a2017-03-06 15:44:06 -08003181 if (!forAutofill) {
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003182 content.setDefaultIntent(new Intent());
3183 }
Adam Skory4aaed142015-04-22 11:29:31 -06003184 }
Felipe Leme640f30a2017-03-06 15:44:06 -08003185 if (!forAutofill) {
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003186 r.activity.onProvideAssistContent(content);
3187 }
Dianne Hackborna83ce1d2015-03-11 15:16:13 -07003188 }
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003189 }
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003190 if (structure == null) {
3191 structure = new AssistStructure();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003192 }
Felipe Leme0200d9e2017-01-24 15:10:26 -08003193
Felipe Leme85d1c2d2017-04-21 08:56:04 -07003194 // TODO: decide if lastSessionId logic applies to autofill sessions
Amith Yamasani858f98d2017-02-22 12:59:53 -08003195
3196 structure.setAcquisitionStartTime(startTime);
3197 structure.setAcquisitionEndTime(SystemClock.uptimeMillis());
3198
Amith Yamasani4f128e42016-05-10 11:44:12 -07003199 mLastAssistStructures.add(new WeakReference<>(structure));
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003200 IActivityManager mgr = ActivityManager.getService();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003201 try {
Dianne Hackborna3acdb32015-06-08 17:07:40 -07003202 mgr.reportAssistContextExtras(cmd.requestToken, data, structure, content, referrer);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003203 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003204 throw e.rethrowFromSystemServer();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003205 }
3206 }
Craig Mautner5eda9b32013-07-02 11:58:16 -07003207
3208 public void handleTranslucentConversionComplete(IBinder token, boolean drawComplete) {
3209 ActivityClientRecord r = mActivities.get(token);
3210 if (r != null) {
3211 r.activity.onTranslucentConversionComplete(drawComplete);
3212 }
3213 }
3214
Craig Mautnereb8abf72014-07-02 15:04:09 -07003215 public void onNewActivityOptions(IBinder token, ActivityOptions options) {
3216 ActivityClientRecord r = mActivities.get(token);
3217 if (r != null) {
3218 r.activity.onNewActivityOptions(options);
3219 }
3220 }
3221
Jeff Sharkeydd97f422013-10-08 17:01:30 -07003222 public void handleInstallProvider(ProviderInfo info) {
Jeff Sharkeybb2e2ca2014-10-23 11:42:31 -07003223 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3224 try {
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -06003225 installContentProviders(mInitialApplication, Arrays.asList(info));
Jeff Sharkeybb2e2ca2014-10-23 11:42:31 -07003226 } finally {
3227 StrictMode.setThreadPolicy(oldPolicy);
3228 }
Jeff Sharkeydd97f422013-10-08 17:01:30 -07003229 }
3230
Craig Mautner8746a472014-07-24 15:12:54 -07003231 private void handleEnterAnimationComplete(IBinder token) {
3232 ActivityClientRecord r = mActivities.get(token);
3233 if (r != null) {
Filip Gruszczynski6eafa902014-11-14 14:24:37 -08003234 r.activity.dispatchEnterAnimationComplete();
Craig Mautner8746a472014-07-24 15:12:54 -07003235 }
3236 }
3237
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04003238 private void handleStartBinderTracking() {
3239 Binder.enableTracing();
3240 }
3241
3242 private void handleStopBinderTrackingAndDump(ParcelFileDescriptor fd) {
3243 try {
3244 Binder.disableTracing();
3245 Binder.getTransactionTracker().writeTracesToFile(fd);
3246 } finally {
3247 IoUtils.closeQuietly(fd);
3248 Binder.getTransactionTracker().clearTraces();
3249 }
3250 }
3251
Andrii Kulian446e8242017-10-26 15:17:29 -07003252 @Override
3253 public void handleMultiWindowModeChanged(IBinder token, boolean isInMultiWindowMode,
Winson Chung5af42fc2017-03-24 17:11:33 -07003254 Configuration overrideConfig) {
Wale Ogunwale5f986092015-12-04 15:35:38 -08003255 final ActivityClientRecord r = mActivities.get(token);
3256 if (r != null) {
Winson Chung5af42fc2017-03-24 17:11:33 -07003257 final Configuration newConfig = new Configuration(mConfiguration);
3258 if (overrideConfig != null) {
3259 newConfig.updateFrom(overrideConfig);
3260 }
3261 r.activity.dispatchMultiWindowModeChanged(isInMultiWindowMode, newConfig);
Wale Ogunwale5f986092015-12-04 15:35:38 -08003262 }
3263 }
3264
Andrii Kulian446e8242017-10-26 15:17:29 -07003265 @Override
3266 public void handlePictureInPictureModeChanged(IBinder token, boolean isInPipMode,
Winson Chung5af42fc2017-03-24 17:11:33 -07003267 Configuration overrideConfig) {
Wale Ogunwale5f986092015-12-04 15:35:38 -08003268 final ActivityClientRecord r = mActivities.get(token);
3269 if (r != null) {
Winson Chung5af42fc2017-03-24 17:11:33 -07003270 final Configuration newConfig = new Configuration(mConfiguration);
3271 if (overrideConfig != null) {
3272 newConfig.updateFrom(overrideConfig);
3273 }
3274 r.activity.dispatchPictureInPictureModeChanged(isInPipMode, newConfig);
Wale Ogunwale5f986092015-12-04 15:35:38 -08003275 }
3276 }
3277
Amith Yamasani0af6fa72016-01-17 15:36:19 -08003278 private void handleLocalVoiceInteractionStarted(IBinder token, IVoiceInteractor interactor) {
3279 final ActivityClientRecord r = mActivities.get(token);
3280 if (r != null) {
3281 r.voiceInteractor = interactor;
3282 r.activity.setVoiceInteractor(interactor);
3283 if (interactor == null) {
3284 r.activity.onLocalVoiceInteractionStopped();
3285 } else {
3286 r.activity.onLocalVoiceInteractionStarted();
3287 }
3288 }
3289 }
3290
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003291 private static boolean attemptAttachAgent(String agent, ClassLoader classLoader) {
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003292 try {
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003293 VMDebug.attachAgent(agent, classLoader);
3294 return true;
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003295 } catch (IOException e) {
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003296 Slog.e(TAG, "Attaching agent with " + classLoader + " failed: " + agent);
3297 return false;
3298 }
3299 }
3300
3301 static void handleAttachAgent(String agent, LoadedApk loadedApk) {
3302 ClassLoader classLoader = loadedApk != null ? loadedApk.getClassLoader() : null;
3303 if (attemptAttachAgent(agent, classLoader)) {
3304 return;
3305 }
3306 if (classLoader != null) {
3307 attemptAttachAgent(agent, null);
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003308 }
3309 }
3310
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003311 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
3312
3313 /**
3314 * Return the Intent that's currently being handled by a
3315 * BroadcastReceiver on this thread, or null if none.
3316 * @hide
3317 */
3318 public static Intent getIntentBeingBroadcast() {
3319 return sCurrentBroadcastIntent.get();
3320 }
3321
Romain Guy65b345f2011-07-27 18:51:50 -07003322 private void handleReceiver(ReceiverData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003323 // If we are getting ready to gc after going to the background, well
3324 // we are back active so skip it.
3325 unscheduleGcIdler();
3326
3327 String component = data.intent.getComponent().getClassName();
3328
Todd Kennedy233a0b12018-01-29 20:30:24 +00003329 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003330 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003332 IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333
Adam Lesinski4e862812016-11-21 16:02:24 -08003334 Application app;
Romain Guy65b345f2011-07-27 18:51:50 -07003335 BroadcastReceiver receiver;
Adam Lesinski4e862812016-11-21 16:02:24 -08003336 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00003338 app = packageInfo.makeApplication(false, mInstrumentation);
Adam Lesinski4e862812016-11-21 16:02:24 -08003339 context = (ContextImpl) app.getBaseContext();
3340 if (data.info.splitName != null) {
3341 context = (ContextImpl) context.createContextForSplit(data.info.splitName);
3342 }
3343 java.lang.ClassLoader cl = context.getClassLoader();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 data.intent.setExtrasClassLoader(cl);
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003345 data.intent.prepareToEnterProcess();
Dianne Hackborne829fef2010-10-26 17:44:01 -07003346 data.setExtrasClassLoader(cl);
Todd Kennedy233a0b12018-01-29 20:30:24 +00003347 receiver = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05003348 .instantiateReceiver(cl, data.info.name, data.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07003350 if (DEBUG_BROADCAST) Slog.i(TAG,
3351 "Finishing failed broadcast to " + data.intent.getComponent());
3352 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 throw new RuntimeException(
3354 "Unable to instantiate receiver " + component
3355 + ": " + e.toString(), e);
3356 }
3357
3358 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003359 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 TAG, "Performing receive of " + data.intent
3361 + ": app=" + app
3362 + ", appName=" + app.getPackageName()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003363 + ", pkg=" + packageInfo.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364 + ", comp=" + data.intent.getComponent().toShortString()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003365 + ", dir=" + packageInfo.getAppDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003367 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07003368 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 receiver.onReceive(context.getReceiverRestrictedContext(),
3370 data.intent);
3371 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07003372 if (DEBUG_BROADCAST) Slog.i(TAG,
3373 "Finishing failed broadcast to " + data.intent.getComponent());
3374 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375 if (!mInstrumentation.onException(receiver, e)) {
3376 throw new RuntimeException(
3377 "Unable to start receiver " + component
3378 + ": " + e.toString(), e);
3379 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003380 } finally {
3381 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003382 }
3383
Dianne Hackborne829fef2010-10-26 17:44:01 -07003384 if (receiver.getPendingResult() != null) {
3385 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 }
3387 }
3388
Christopher Tate181fafa2009-05-14 11:12:14 -07003389 // Instantiate a BackupAgent and tell it that it's alive
Romain Guy65b345f2011-07-27 18:51:50 -07003390 private void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003391 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07003392
Christopher Tate346acb12012-10-15 19:20:25 -07003393 // Sanity check the requested target package's uid against ours
3394 try {
3395 PackageInfo requestedPackage = getPackageManager().getPackageInfo(
3396 data.appInfo.packageName, 0, UserHandle.myUserId());
3397 if (requestedPackage.applicationInfo.uid != Process.myUid()) {
3398 Slog.w(TAG, "Asked to instantiate non-matching package "
3399 + data.appInfo.packageName);
3400 return;
3401 }
3402 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003403 throw e.rethrowFromSystemServer();
Christopher Tate346acb12012-10-15 19:20:25 -07003404 }
3405
Christopher Tate181fafa2009-05-14 11:12:14 -07003406 // no longer idle; we have backup work to do
3407 unscheduleGcIdler();
3408
3409 // instantiate the BackupAgent class named in the manifest
Todd Kennedy233a0b12018-01-29 20:30:24 +00003410 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
3411 String packageName = packageInfo.mPackageName;
Christopher Tate346acb12012-10-15 19:20:25 -07003412 if (packageName == null) {
3413 Slog.d(TAG, "Asked to create backup agent for nonexistent package");
3414 return;
3415 }
3416
Christopher Tate181fafa2009-05-14 11:12:14 -07003417 String classname = data.appInfo.backupAgentName;
Christopher Tate79ec80d2011-06-24 14:58:49 -07003418 // full backup operation but no app-supplied agent? use the default implementation
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003419 if (classname == null && (data.backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL
3420 || data.backupMode == ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL)) {
Christopher Tate4a627c72011-04-01 14:43:32 -07003421 classname = "android.app.backup.FullBackupAgent";
Christopher Tate181fafa2009-05-14 11:12:14 -07003422 }
Christopher Tate4a627c72011-04-01 14:43:32 -07003423
Christopher Tate181fafa2009-05-14 11:12:14 -07003424 try {
Christopher Tated1475e02009-07-09 15:36:17 -07003425 IBinder binder = null;
Christopher Tate2e40d112014-07-15 12:37:38 -07003426 BackupAgent agent = mBackupAgents.get(packageName);
3427 if (agent != null) {
3428 // reusing the existing instance
3429 if (DEBUG_BACKUP) {
3430 Slog.v(TAG, "Reusing existing agent instance");
Christopher Tated1475e02009-07-09 15:36:17 -07003431 }
Christopher Tate2e40d112014-07-15 12:37:38 -07003432 binder = agent.onBind();
3433 } else {
3434 try {
3435 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing agent class " + classname);
3436
Todd Kennedy233a0b12018-01-29 20:30:24 +00003437 java.lang.ClassLoader cl = packageInfo.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04003438 agent = (BackupAgent) cl.loadClass(classname).newInstance();
Christopher Tate2e40d112014-07-15 12:37:38 -07003439
3440 // set up the agent's context
Todd Kennedy233a0b12018-01-29 20:30:24 +00003441 ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
Christopher Tate2e40d112014-07-15 12:37:38 -07003442 context.setOuterContext(agent);
3443 agent.attach(context);
3444
3445 agent.onCreate();
3446 binder = agent.onBind();
3447 mBackupAgents.put(packageName, agent);
3448 } catch (Exception e) {
3449 // If this is during restore, fail silently; otherwise go
3450 // ahead and let the user see the crash.
3451 Slog.e(TAG, "Agent threw during creation: " + e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003452 if (data.backupMode != ApplicationThreadConstants.BACKUP_MODE_RESTORE
3453 && data.backupMode !=
3454 ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL) {
Christopher Tate2e40d112014-07-15 12:37:38 -07003455 throw e;
3456 }
3457 // falling through with 'binder' still null
3458 }
Christopher Tated1475e02009-07-09 15:36:17 -07003459 }
Christopher Tate181fafa2009-05-14 11:12:14 -07003460
3461 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07003462 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003463 ActivityManager.getService().backupAgentCreated(packageName, binder);
Christopher Tate181fafa2009-05-14 11:12:14 -07003464 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003465 throw e.rethrowFromSystemServer();
Christopher Tate181fafa2009-05-14 11:12:14 -07003466 }
Christopher Tate181fafa2009-05-14 11:12:14 -07003467 } catch (Exception e) {
3468 throw new RuntimeException("Unable to create BackupAgent "
Christopher Tate4a627c72011-04-01 14:43:32 -07003469 + classname + ": " + e.toString(), e);
Christopher Tate181fafa2009-05-14 11:12:14 -07003470 }
3471 }
3472
3473 // Tear down a BackupAgent
Romain Guy65b345f2011-07-27 18:51:50 -07003474 private void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003475 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07003476
Todd Kennedy233a0b12018-01-29 20:30:24 +00003477 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
3478 String packageName = packageInfo.mPackageName;
Christopher Tate181fafa2009-05-14 11:12:14 -07003479 BackupAgent agent = mBackupAgents.get(packageName);
3480 if (agent != null) {
3481 try {
3482 agent.onDestroy();
3483 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003484 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07003485 e.printStackTrace();
3486 }
3487 mBackupAgents.remove(packageName);
3488 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003489 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07003490 }
3491 }
3492
Romain Guy65b345f2011-07-27 18:51:50 -07003493 private void handleCreateService(CreateServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 // If we are getting ready to gc after going to the background, well
3495 // we are back active so skip it.
3496 unscheduleGcIdler();
3497
Todd Kennedy233a0b12018-01-29 20:30:24 +00003498 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003499 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500 Service service = null;
3501 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00003502 java.lang.ClassLoader cl = packageInfo.getClassLoader();
3503 service = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05003504 .instantiateService(cl, data.info.name, data.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003505 } catch (Exception e) {
3506 if (!mInstrumentation.onException(service, e)) {
3507 throw new RuntimeException(
3508 "Unable to instantiate service " + data.info.name
3509 + ": " + e.toString(), e);
3510 }
3511 }
3512
3513 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003514 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003515
Todd Kennedy233a0b12018-01-29 20:30:24 +00003516 ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
Jeff Browndefd4a62014-03-10 21:24:37 -07003517 context.setOuterContext(service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518
Todd Kennedy233a0b12018-01-29 20:30:24 +00003519 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003520 service.attach(context, this, data.info.name, data.token, app,
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003521 ActivityManager.getService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003522 service.onCreate();
3523 mServices.put(data.token, service);
3524 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003525 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003526 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003527 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003528 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003529 }
3530 } catch (Exception e) {
3531 if (!mInstrumentation.onException(service, e)) {
3532 throw new RuntimeException(
3533 "Unable to create service " + data.info.name
3534 + ": " + e.toString(), e);
3535 }
3536 }
3537 }
3538
Romain Guy65b345f2011-07-27 18:51:50 -07003539 private void handleBindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003540 Service s = mServices.get(data.token);
Amith Yamasani742a6712011-05-04 14:49:28 -07003541 if (DEBUG_SERVICE)
3542 Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003543 if (s != null) {
3544 try {
3545 data.intent.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003546 data.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003547 try {
3548 if (!data.rebind) {
3549 IBinder binder = s.onBind(data.intent);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003550 ActivityManager.getService().publishService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551 data.token, data.intent, binder);
3552 } else {
3553 s.onRebind(data.intent);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003554 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003555 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003557 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003559 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003560 }
3561 } catch (Exception e) {
3562 if (!mInstrumentation.onException(s, e)) {
3563 throw new RuntimeException(
3564 "Unable to bind to service " + s
3565 + " with " + data.intent + ": " + e.toString(), e);
3566 }
3567 }
3568 }
3569 }
3570
Romain Guy65b345f2011-07-27 18:51:50 -07003571 private void handleUnbindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003572 Service s = mServices.get(data.token);
3573 if (s != null) {
3574 try {
3575 data.intent.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003576 data.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 boolean doRebind = s.onUnbind(data.intent);
3578 try {
3579 if (doRebind) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003580 ActivityManager.getService().unbindFinished(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003581 data.token, data.intent, doRebind);
3582 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003583 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003584 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003585 }
3586 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003587 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003588 }
3589 } catch (Exception e) {
3590 if (!mInstrumentation.onException(s, e)) {
3591 throw new RuntimeException(
3592 "Unable to unbind to service " + s
3593 + " with " + data.intent + ": " + e.toString(), e);
3594 }
3595 }
3596 }
3597 }
3598
Dianne Hackborn625ac272010-09-17 18:29:22 -07003599 private void handleDumpService(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08003600 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3601 try {
3602 Service s = mServices.get(info.token);
3603 if (s != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07003604 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
3605 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08003606 s.dump(info.fd.getFileDescriptor(), pw, info.args);
3607 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003608 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08003609 } finally {
3610 IoUtils.closeQuietly(info.fd);
3611 StrictMode.setThreadPolicy(oldPolicy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003612 }
3613 }
3614
Dianne Hackborn625ac272010-09-17 18:29:22 -07003615 private void handleDumpActivity(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08003616 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3617 try {
3618 ActivityClientRecord r = mActivities.get(info.token);
3619 if (r != null && r.activity != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07003620 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
3621 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08003622 r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
3623 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07003624 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08003625 } finally {
3626 IoUtils.closeQuietly(info.fd);
3627 StrictMode.setThreadPolicy(oldPolicy);
Dianne Hackborn625ac272010-09-17 18:29:22 -07003628 }
3629 }
3630
Marco Nelissen18cb2872011-11-15 11:19:53 -08003631 private void handleDumpProvider(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08003632 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3633 try {
3634 ProviderClientRecord r = mLocalProviders.get(info.token);
3635 if (r != null && r.mLocalProvider != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07003636 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
3637 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08003638 r.mLocalProvider.dump(info.fd.getFileDescriptor(), pw, info.args);
3639 pw.flush();
Marco Nelissen18cb2872011-11-15 11:19:53 -08003640 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08003641 } finally {
3642 IoUtils.closeQuietly(info.fd);
3643 StrictMode.setThreadPolicy(oldPolicy);
Marco Nelissen18cb2872011-11-15 11:19:53 -08003644 }
3645 }
3646
Romain Guy65b345f2011-07-27 18:51:50 -07003647 private void handleServiceArgs(ServiceArgsData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003648 Service s = mServices.get(data.token);
3649 if (s != null) {
3650 try {
3651 if (data.args != null) {
3652 data.args.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003653 data.args.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003655 int res;
3656 if (!data.taskRemoved) {
3657 res = s.onStartCommand(data.args, data.flags, data.startId);
3658 } else {
3659 s.onTaskRemoved(data.args);
3660 res = Service.START_TASK_REMOVED_COMPLETE;
3661 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003662
3663 QueuedWork.waitToFinish();
3664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003665 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003666 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003667 data.token, SERVICE_DONE_EXECUTING_START, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003669 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003670 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003671 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003672 } catch (Exception e) {
3673 if (!mInstrumentation.onException(s, e)) {
3674 throw new RuntimeException(
3675 "Unable to start service " + s
3676 + " with " + data.args + ": " + e.toString(), e);
3677 }
3678 }
3679 }
3680 }
3681
Romain Guy65b345f2011-07-27 18:51:50 -07003682 private void handleStopService(IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 Service s = mServices.remove(token);
3684 if (s != null) {
3685 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003686 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687 s.onDestroy();
Amith Yamasani75928252017-05-22 15:10:47 -07003688 s.detachAndCleanUp();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003689 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08003690 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003691 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08003692 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003693 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003694
3695 QueuedWork.waitToFinish();
3696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003697 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003698 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003699 token, SERVICE_DONE_EXECUTING_STOP, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003700 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003701 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003702 }
3703 } catch (Exception e) {
3704 if (!mInstrumentation.onException(s, e)) {
3705 throw new RuntimeException(
3706 "Unable to stop service " + s
3707 + ": " + e.toString(), e);
3708 }
Craig Mautner66c4a822015-01-16 12:48:16 -08003709 Slog.i(TAG, "handleStopService: exception for " + token, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 }
Craig Mautner9776ad42015-01-15 14:38:39 -08003711 } else {
3712 Slog.i(TAG, "handleStopService: token=" + token + " not found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003713 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003714 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 }
3716
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003717 ActivityClientRecord performResumeActivity(IBinder token, boolean clearHide, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003718 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003719 if (localLOGV) Slog.v(TAG, "Performing resume of " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720 + " finished=" + r.activity.mFinished);
3721 if (r != null && !r.activity.mFinished) {
3722 if (clearHide) {
3723 r.hideForNow = false;
3724 r.activity.mStartedActivity = false;
3725 }
3726 try {
Dianne Hackborn6bdd3a12015-08-05 15:01:28 -07003727 r.activity.onStateNotSaved();
Dianne Hackborn689586d2012-10-01 18:23:04 -07003728 r.activity.mFragments.noteStateNotSaved();
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07003729 checkAndBlockForNetworkAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730 if (r.pendingIntents != null) {
3731 deliverNewIntents(r, r.pendingIntents);
3732 r.pendingIntents = null;
3733 }
3734 if (r.pendingResults != null) {
3735 deliverResults(r, r.pendingResults);
3736 r.pendingResults = null;
3737 }
Dake Gu67decfa2017-12-27 11:48:08 -08003738 r.activity.performResume(r.startsNotResumed);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003739
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08003740 EventLog.writeEvent(LOG_AM_ON_RESUME_CALLED, UserHandle.myUserId(),
3741 r.activity.getComponentName().getClassName(), reason);
Bob Leee5408332009-09-04 18:31:17 -07003742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003743 r.state = null;
Craig Mautnera0026042014-04-23 11:45:37 -07003744 r.persistentState = null;
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003745 r.setState(ON_RESUME);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 } catch (Exception e) {
3747 if (!mInstrumentation.onException(r.activity, e)) {
3748 throw new RuntimeException(
3749 "Unable to resume activity "
3750 + r.intent.getComponent().toShortString()
3751 + ": " + e.toString(), e);
3752 }
3753 }
3754 }
3755 return r;
3756 }
3757
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003758 static final void cleanUpPendingRemoveWindows(ActivityClientRecord r, boolean force) {
3759 if (r.mPreserveWindow && !force) {
3760 return;
3761 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003762 if (r.mPendingRemoveWindow != null) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003763 r.mPendingRemoveWindowManager.removeViewImmediate(
3764 r.mPendingRemoveWindow.getDecorView());
3765 IBinder wtoken = r.mPendingRemoveWindow.getDecorView().getWindowToken();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003766 if (wtoken != null) {
Jeff Brown98365d72012-08-19 20:30:52 -07003767 WindowManagerGlobal.getInstance().closeAll(wtoken,
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003768 r.activity.getClass().getName(), "Activity");
3769 }
3770 }
3771 r.mPendingRemoveWindow = null;
3772 r.mPendingRemoveWindowManager = null;
3773 }
3774
Andrii Kulian446e8242017-10-26 15:17:29 -07003775 @Override
3776 public void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward,
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003777 String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 // If we are getting ready to gc after going to the background, well
3779 // we are back active so skip it.
3780 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003781 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003782
Adam Powellcfbe9be2013-11-06 14:58:58 -08003783 // TODO Push resumeArgs into the activity for consideration
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003784 final ActivityClientRecord r = performResumeActivity(token, clearHide, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003785
3786 if (r != null) {
3787 final Activity a = r.activity;
3788
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003789 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790 TAG, "Resume " + r + " started activity: " +
3791 a.mStartedActivity + ", hideForNow: " + r.hideForNow
3792 + ", finished: " + a.mFinished);
3793
3794 final int forwardBit = isForward ?
3795 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07003796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003797 // If the window hasn't yet been added to the window manager,
3798 // and this guy didn't finish itself or start another activity,
3799 // then go ahead and add the window.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003800 boolean willBeVisible = !a.mStartedActivity;
3801 if (!willBeVisible) {
3802 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003803 willBeVisible = ActivityManager.getService().willActivityBeVisible(
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003804 a.getActivityToken());
3805 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003806 throw e.rethrowFromSystemServer();
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003807 }
3808 }
3809 if (r.window == null && !a.mFinished && willBeVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810 r.window = r.activity.getWindow();
3811 View decor = r.window.getDecorView();
3812 decor.setVisibility(View.INVISIBLE);
3813 ViewManager wm = a.getWindowManager();
3814 WindowManager.LayoutParams l = r.window.getAttributes();
3815 a.mDecor = decor;
3816 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
3817 l.softInputMode |= forwardBit;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003818 if (r.mPreserveWindow) {
3819 a.mWindowAdded = true;
3820 r.mPreserveWindow = false;
Robert Carrb2594852016-04-25 16:21:13 -07003821 // Normally the ViewRoot sets up callbacks with the Activity
3822 // in addView->ViewRootImpl#setView. If we are instead reusing
3823 // the decor view we have to notify the view root that the
3824 // callbacks may have changed.
3825 ViewRootImpl impl = decor.getViewRootImpl();
Robert Carr311ecba2016-04-27 12:59:45 -07003826 if (impl != null) {
3827 impl.notifyChildRebuilt();
3828 }
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003829 }
Bryce Lee4b51b322017-04-07 10:27:19 -07003830 if (a.mVisibleFromClient) {
3831 if (!a.mWindowAdded) {
3832 a.mWindowAdded = true;
3833 wm.addView(decor, l);
3834 } else {
3835 // The activity will get a callback for this {@link LayoutParams} change
3836 // earlier. However, at that time the decor will not be set (this is set
3837 // in this method), so no action will be taken. This call ensures the
3838 // callback occurs with the decor set.
3839 a.onWindowAttributesChanged(l);
3840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003841 }
3842
3843 // If the window has already been added, but during resume
3844 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003845 // window visible.
3846 } else if (!willBeVisible) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003847 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003848 TAG, "Launch " + r + " mStartedActivity set");
3849 r.hideForNow = true;
3850 }
3851
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003852 // Get rid of anything left hanging around.
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003853 cleanUpPendingRemoveWindows(r, false /* force */);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003855 // The window is now visible if it has been added, we are not
3856 // simply finishing, and we are not starting another activity.
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003857 if (!r.activity.mFinished && willBeVisible
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07003858 && r.activity.mDecor != null && !r.hideForNow) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 if (r.newConfig != null) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08003860 performConfigurationChangedForActivity(r, r.newConfig);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003861 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Resuming activity "
Adam Lesinski082614c2016-03-04 14:33:47 -08003862 + r.activityInfo.name + " with newConfig " + r.activity.mCurrentConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003863 r.newConfig = null;
3864 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003865 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 + isForward);
3867 WindowManager.LayoutParams l = r.window.getAttributes();
3868 if ((l.softInputMode
3869 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
3870 != forwardBit) {
3871 l.softInputMode = (l.softInputMode
3872 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
3873 | forwardBit;
Dianne Hackbornc1e605e2009-09-25 17:18:15 -07003874 if (r.activity.mVisibleFromClient) {
3875 ViewManager wm = a.getWindowManager();
3876 View decor = r.window.getDecorView();
3877 wm.updateViewLayout(decor, l);
3878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003879 }
Bryce Lee4b51b322017-04-07 10:27:19 -07003880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003881 r.activity.mVisibleFromServer = true;
3882 mNumVisibleActivities++;
3883 if (r.activity.mVisibleFromClient) {
3884 r.activity.makeVisible();
3885 }
3886 }
3887
Andrii Kulianb372da62018-01-18 10:46:24 -08003888 r.nextIdle = mNewActivities;
3889 mNewActivities = r;
3890 if (localLOGV) {
3891 Slog.v(TAG, "Scheduling idle handler for " + r);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003892 }
Andrii Kulianb372da62018-01-18 10:46:24 -08003893 Looper.myQueue().addIdleHandler(new Idler());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894 } else {
3895 // If an exception was thrown when trying to resume, then
3896 // just end this activity.
3897 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003898 ActivityManager.getService()
Wale Ogunwaleba7881c2015-08-01 19:28:29 -07003899 .finishActivity(token, Activity.RESULT_CANCELED, null,
3900 Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003902 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 }
3904 }
3905 }
3906
Andrii Kulian446e8242017-10-26 15:17:29 -07003907 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003908 public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
3909 int configChanges, boolean dontReport, PendingTransactionActions pendingActions) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003910 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003911 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 if (userLeaving) {
3913 performUserLeavingActivity(r);
3914 }
Bob Leee5408332009-09-04 18:31:17 -07003915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003916 r.activity.mConfigChangeFlags |= configChanges;
Andrii Kulian8ae79572018-01-26 15:36:06 -08003917 performPauseActivity(r, finished, "handlePauseActivity", pendingActions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07003919 // Make sure any pending writes are now committed.
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08003920 if (r.isPreHoneycomb()) {
3921 QueuedWork.waitToFinish();
3922 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07003923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 // Tell the activity manager we have paused.
Dianne Hackborna4e102e2014-09-04 22:52:27 -07003925 if (!dontReport) {
3926 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003927 ActivityManager.getService().activityPaused(token);
Dianne Hackborna4e102e2014-09-04 22:52:27 -07003928 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003929 throw ex.rethrowFromSystemServer();
Dianne Hackborna4e102e2014-09-04 22:52:27 -07003930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003932 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 }
3934 }
3935
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003936 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 mInstrumentation.callActivityOnUserLeaving(r.activity);
3938 }
3939
Andrii Kulian8ae79572018-01-26 15:36:06 -08003940 final Bundle performPauseActivity(IBinder token, boolean finished, String reason,
3941 PendingTransactionActions pendingActions) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003942 ActivityClientRecord r = mActivities.get(token);
Andrii Kulian8ae79572018-01-26 15:36:06 -08003943 return r != null ? performPauseActivity(r, finished, reason, pendingActions) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003944 }
3945
Andrii Kulian8ae79572018-01-26 15:36:06 -08003946 /**
3947 * Pause the activity.
3948 * @return Saved instance state for pre-Honeycomb apps if it was saved, {@code null} otherwise.
3949 */
3950 private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
3951 PendingTransactionActions pendingActions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 if (r.paused) {
3953 if (r.activity.mFinished) {
3954 // If we are finishing, we won't call onResume() in certain cases.
3955 // So here we likewise don't want to call onPause() if the activity
3956 // isn't resumed.
3957 return null;
3958 }
3959 RuntimeException e = new RuntimeException(
3960 "Performing pause of activity that is not resumed: "
3961 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003962 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964 if (finished) {
3965 r.activity.mFinished = true;
3966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003967
Andrii Kulian8ae79572018-01-26 15:36:06 -08003968 // Pre-Honeycomb apps always save their state before pausing
3969 final boolean shouldSaveState = !r.activity.mFinished && r.isPreHoneycomb();
3970 if (shouldSaveState) {
3971 callActivityOnSaveInstanceState(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003972 }
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07003973
3974 performPauseActivityIfNeeded(r, reason);
Jeff Hamilton52d32032011-01-08 15:31:26 -06003975
3976 // Notify any outstanding on paused listeners
3977 ArrayList<OnActivityPausedListener> listeners;
3978 synchronized (mOnPauseListeners) {
3979 listeners = mOnPauseListeners.remove(r.activity);
3980 }
3981 int size = (listeners != null ? listeners.size() : 0);
3982 for (int i = 0; i < size; i++) {
3983 listeners.get(i).onPaused(r.activity);
3984 }
3985
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003986 final Bundle oldState = pendingActions != null ? pendingActions.getOldState() : null;
3987 if (oldState != null) {
3988 // We need to keep around the original state, in case we need to be created again.
3989 // But we only do this for pre-Honeycomb apps, which always save their state when
3990 // pausing, so we can not have them save their state when restarting from a paused
3991 // state. For HC and later, we want to (and can) let the state be saved as the
3992 // normal part of stopping the activity.
3993 if (r.isPreHoneycomb()) {
3994 r.state = oldState;
3995 }
3996 }
3997
Andrii Kulian8ae79572018-01-26 15:36:06 -08003998 return shouldSaveState ? r.state : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 }
4000
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004001 private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
4002 if (r.paused) {
4003 // You are already paused silly...
4004 return;
4005 }
4006
4007 try {
4008 r.activity.mCalled = false;
4009 mInstrumentation.callActivityOnPause(r.activity);
4010 EventLog.writeEvent(LOG_AM_ON_PAUSE_CALLED, UserHandle.myUserId(),
4011 r.activity.getComponentName().getClassName(), reason);
4012 if (!r.activity.mCalled) {
4013 throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
4014 + " did not call through to super.onPause()");
4015 }
4016 } catch (SuperNotCalledException e) {
4017 throw e;
4018 } catch (Exception e) {
4019 if (!mInstrumentation.onException(r.activity, e)) {
4020 throw new RuntimeException("Unable to pause activity "
4021 + safeToComponentShortString(r.intent) + ": " + e.toString(), e);
4022 }
4023 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004024 r.setState(ON_PAUSE);
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004025 }
4026
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08004027 final void performStopActivity(IBinder token, boolean saveState, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004028 ActivityClientRecord r = mActivities.get(token);
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08004029 performStopActivityInner(r, null, false, saveState, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 }
4031
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004032 private static final class ProviderRefCount {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07004033 public final ContentProviderHolder holder;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004034 public final ProviderClientRecord client;
4035 public int stableCount;
4036 public int unstableCount;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004037
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004038 // When this is set, the stable and unstable ref counts are 0 and
4039 // we have a pending operation scheduled to remove the ref count
4040 // from the activity manager. On the activity manager we are still
4041 // holding an unstable ref, though it is not reflected in the counts
4042 // here.
4043 public boolean removePending;
4044
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07004045 ProviderRefCount(ContentProviderHolder inHolder,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004046 ProviderClientRecord inClient, int sCount, int uCount) {
4047 holder = inHolder;
4048 client = inClient;
4049 stableCount = sCount;
4050 unstableCount = uCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 }
4052 }
4053
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004054 /**
4055 * Core implementation of stopping an activity. Note this is a little
4056 * tricky because the server's meaning of stop is slightly different
4057 * than our client -- for the server, stop means to save state and give
4058 * it the result when it is done, but the window may still be visible.
4059 * For the client, we want to call onStop()/onStart() to indicate when
Wale Ogunwaleb5066fe2016-09-21 07:33:43 -07004060 * the activity's UI visibility changes.
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004061 */
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004062 private void performStopActivityInner(ActivityClientRecord r, StopInfo info, boolean keepShown,
4063 boolean saveState, String reason) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004064 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 if (r != null) {
4066 if (!keepShown && r.stopped) {
4067 if (r.activity.mFinished) {
4068 // If we are finishing, we won't call onResume() in certain
4069 // cases. So here we likewise don't want to call onStop()
4070 // if the activity isn't resumed.
4071 return;
4072 }
4073 RuntimeException e = new RuntimeException(
Andrii Kulian58178f22016-03-16 13:44:56 -07004074 "Performing stop of activity that is already stopped: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004075 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004076 Slog.e(TAG, e.getMessage(), e);
Andrii Kulian58178f22016-03-16 13:44:56 -07004077 Slog.e(TAG, r.getStateString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004078 }
4079
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004080 // One must first be paused before stopped...
4081 performPauseActivityIfNeeded(r, reason);
4082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004083 if (info != null) {
4084 try {
4085 // First create a thumbnail for the activity...
Dianne Hackborn0500b3c2011-11-01 15:28:43 -07004086 // For now, don't create the thumbnail here; we are
4087 // doing that by doing a screen snapshot.
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004088 info.setDescription(r.activity.onCreateDescription());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004089 } catch (Exception e) {
4090 if (!mInstrumentation.onException(r.activity, e)) {
4091 throw new RuntimeException(
4092 "Unable to save state of activity "
4093 + r.intent.getComponent().toShortString()
4094 + ": " + e.toString(), e);
4095 }
4096 }
4097 }
4098
4099 if (!keepShown) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004100 callActivityOnStop(r, saveState, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 }
4103 }
4104
Andrii Kulian8ae79572018-01-26 15:36:06 -08004105 /**
4106 * Calls {@link Activity#onStop()} and {@link Activity#onSaveInstanceState(Bundle)}, and updates
4107 * the client record's state.
4108 * All calls to stop an activity must be done through this method to make sure that
4109 * {@link Activity#onSaveInstanceState(Bundle)} is also executed in the same call.
4110 */
4111 private void callActivityOnStop(ActivityClientRecord r, boolean saveState, String reason) {
Andrii Kulian391161f2018-01-29 10:50:02 -08004112 // Before P onSaveInstanceState was called before onStop, starting with P it's
4113 // called after. Before Honeycomb state was always saved before onPause.
Andrii Kulian8ae79572018-01-26 15:36:06 -08004114 final boolean shouldSaveState = saveState && !r.activity.mFinished && r.state == null
4115 && !r.isPreHoneycomb();
Andrii Kulian391161f2018-01-29 10:50:02 -08004116 final boolean isPreP = r.isPreP();
4117 if (shouldSaveState && isPreP) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004118 callActivityOnSaveInstanceState(r);
4119 }
4120
4121 try {
4122 r.activity.performStop(false /*preserveWindow*/);
4123 } catch (SuperNotCalledException e) {
4124 throw e;
4125 } catch (Exception e) {
4126 if (!mInstrumentation.onException(r.activity, e)) {
4127 throw new RuntimeException(
4128 "Unable to stop activity "
4129 + r.intent.getComponent().toShortString()
4130 + ": " + e.toString(), e);
4131 }
4132 }
4133 r.setState(ON_STOP);
4134 EventLog.writeEvent(LOG_AM_ON_STOP_CALLED, UserHandle.myUserId(),
4135 r.activity.getComponentName().getClassName(), reason);
Andrii Kulian391161f2018-01-29 10:50:02 -08004136
4137 if (shouldSaveState && !isPreP) {
4138 callActivityOnSaveInstanceState(r);
4139 }
Andrii Kulian8ae79572018-01-26 15:36:06 -08004140 }
4141
Romain Guy65b345f2011-07-27 18:51:50 -07004142 private void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143 View v = r.activity.mDecor;
4144 if (v != null) {
4145 if (show) {
4146 if (!r.activity.mVisibleFromServer) {
4147 r.activity.mVisibleFromServer = true;
4148 mNumVisibleActivities++;
4149 if (r.activity.mVisibleFromClient) {
4150 r.activity.makeVisible();
4151 }
4152 }
4153 if (r.newConfig != null) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004154 performConfigurationChangedForActivity(r, r.newConfig);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004155 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Adam Lesinski082614c2016-03-04 14:33:47 -08004156 + r.activityInfo.name + " with new config "
4157 + r.activity.mCurrentConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004158 r.newConfig = null;
4159 }
4160 } else {
4161 if (r.activity.mVisibleFromServer) {
4162 r.activity.mVisibleFromServer = false;
4163 mNumVisibleActivities--;
4164 v.setVisibility(View.INVISIBLE);
4165 }
4166 }
4167 }
4168 }
4169
Andrii Kulian446e8242017-10-26 15:17:29 -07004170 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004171 public void handleStopActivity(IBinder token, boolean show, int configChanges,
4172 PendingTransactionActions pendingActions) {
4173 final ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 r.activity.mConfigChangeFlags |= configChanges;
4175
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004176 final StopInfo stopInfo = new StopInfo();
4177 performStopActivityInner(r, stopInfo, show, true, "handleStopActivity");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004178
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004179 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 TAG, "Finishing stop of " + r + ": show=" + show
4181 + " win=" + r.window);
4182
4183 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07004184
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004185 // Make sure any pending writes are now committed.
4186 if (!r.isPreHoneycomb()) {
4187 QueuedWork.waitToFinish();
4188 }
4189
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004190 stopInfo.setActivity(r);
4191 stopInfo.setState(r.state);
4192 stopInfo.setPersistentState(r.persistentState);
4193 pendingActions.setStopInfo(stopInfo);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004194 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004195 }
4196
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004197 /**
4198 * Schedule the call to tell the activity manager we have stopped. We don't do this
4199 * immediately, because we want to have a chance for any other pending work (in particular
4200 * memory trim requests) to complete before you tell the activity manager to proceed and allow
4201 * us to go fully into the background.
4202 */
4203 @Override
4204 public void reportStop(PendingTransactionActions pendingActions) {
4205 mH.post(pendingActions.getStopInfo());
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07004206 }
4207
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004208 @Override
4209 public void performRestartActivity(IBinder token, boolean start) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004210 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 if (r.stopped) {
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004212 r.activity.performRestart(start);
4213 if (start) {
4214 r.setState(ON_START);
4215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216 }
4217 }
4218
Andrii Kulian446e8242017-10-26 15:17:29 -07004219 @Override
4220 public void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004221 ActivityClientRecord r = mActivities.get(token);
Tim Murraye1e6c662015-04-07 13:24:14 -07004222
Dianne Hackbornbfddc0f2010-12-14 11:28:01 -08004223 if (r == null) {
4224 Log.w(TAG, "handleWindowVisibility: no activity for token " + token);
4225 return;
4226 }
Tim Murraye1e6c662015-04-07 13:24:14 -07004227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004228 if (!show && !r.stopped) {
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08004229 performStopActivityInner(r, null, show, false, "handleWindowVisibility");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004230 } else if (show && r.stopped) {
4231 // If we are getting ready to gc after going to the background, well
4232 // we are back active so skip it.
4233 unscheduleGcIdler();
4234
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004235 r.activity.performRestart(true /* start */);
4236 r.setState(ON_START);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004237 }
4238 if (r.activity.mDecor != null) {
Joe Onorato43a17652011-04-06 19:22:23 -07004239 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004240 TAG, "Handle window " + r + " visibility: " + show);
4241 updateVisibility(r, show);
4242 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004243 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004244 }
4245
Wale Ogunwaleb5066fe2016-09-21 07:33:43 -07004246 // TODO: This method should be changed to use {@link #performStopActivityInner} to perform to
4247 // stop operation on the activity to reduce code duplication and the chance of fixing a bug in
4248 // one place and missing the other.
Romain Guy65b345f2011-07-27 18:51:50 -07004249 private void handleSleeping(IBinder token, boolean sleeping) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004250 ActivityClientRecord r = mActivities.get(token);
4251
4252 if (r == null) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08004253 Log.w(TAG, "handleSleeping: no activity for token " + token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004254 return;
4255 }
4256
4257 if (sleeping) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08004258 if (!r.stopped && !r.isPreHoneycomb()) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004259 callActivityOnStop(r, true /* saveState */, "sleeping");
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004260 }
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004261
4262 // Make sure any pending writes are now committed.
4263 if (!r.isPreHoneycomb()) {
4264 QueuedWork.waitToFinish();
4265 }
4266
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004267 // Tell activity manager we slept.
4268 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004269 ActivityManager.getService().activitySlept(r.token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004270 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004271 throw ex.rethrowFromSystemServer();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004272 }
4273 } else {
4274 if (r.stopped && r.activity.mVisibleFromServer) {
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004275 r.activity.performRestart(true /* start */);
4276 r.setState(ON_START);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004277 }
4278 }
4279 }
4280
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004281 private void handleSetCoreSettings(Bundle coreSettings) {
Craig Mautner88c05892013-06-28 09:47:45 -07004282 synchronized (mResourcesManager) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08004283 mCoreSettings = coreSettings;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004284 }
Jon Miranda836c0a82014-08-11 12:32:26 -07004285 onCoreSettingsChange();
4286 }
4287
4288 private void onCoreSettingsChange() {
4289 boolean debugViewAttributes =
4290 mCoreSettings.getInt(Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0;
4291 if (debugViewAttributes != View.mDebugViewAttributes) {
4292 View.mDebugViewAttributes = debugViewAttributes;
4293
4294 // request all activities to relaunch for the changes to take place
Fyodor Kupolovcb93d6f2017-05-04 17:27:16 -07004295 requestRelaunchAllActivities();
4296 }
4297 }
4298
4299 private void requestRelaunchAllActivities() {
4300 for (Map.Entry<IBinder, ActivityClientRecord> entry : mActivities.entrySet()) {
4301 final Activity activity = entry.getValue().activity;
4302 if (!activity.mFinished) {
4303 try {
4304 ActivityManager.getService().requestActivityRelaunch(entry.getKey());
4305 } catch (RemoteException e) {
4306 throw e.rethrowFromSystemServer();
4307 }
Jon Miranda836c0a82014-08-11 12:32:26 -07004308 }
4309 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004310 }
4311
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004312 private void handleUpdatePackageCompatibilityInfo(UpdateCompatibilityData data) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00004313 LoadedApk apk = peekPackageInfo(data.pkg, false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004314 if (apk != null) {
Craig Mautner48d0d182013-06-11 07:53:06 -07004315 apk.setCompatibilityInfo(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004316 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00004317 apk = peekPackageInfo(data.pkg, true);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004318 if (apk != null) {
Craig Mautner48d0d182013-06-11 07:53:06 -07004319 apk.setCompatibilityInfo(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004320 }
4321 handleConfigurationChanged(mConfiguration, data.info);
Jeff Brown98365d72012-08-19 20:30:52 -07004322 WindowManagerGlobal.getInstance().reportNewConfiguration(mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004323 }
4324
Romain Guy65b345f2011-07-27 18:51:50 -07004325 private void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004326 final int N = results.size();
4327 for (int i=0; i<N; i++) {
4328 ResultInfo ri = results.get(i);
4329 try {
4330 if (ri.mData != null) {
4331 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01004332 ri.mData.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004333 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004334 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07004335 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004336 r.activity.dispatchActivityResult(ri.mResultWho,
4337 ri.mRequestCode, ri.mResultCode, ri.mData);
4338 } catch (Exception e) {
4339 if (!mInstrumentation.onException(r.activity, e)) {
4340 throw new RuntimeException(
4341 "Failure delivering result " + ri + " to activity "
4342 + r.intent.getComponent().toShortString()
4343 + ": " + e.toString(), e);
4344 }
4345 }
4346 }
4347 }
4348
Andrii Kulian446e8242017-10-26 15:17:29 -07004349 @Override
4350 public void handleSendResult(IBinder token, List<ResultInfo> results) {
4351 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004352 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004353 if (r != null) {
4354 final boolean resumed = !r.paused;
4355 if (!r.activity.mFinished && r.activity.mDecor != null
4356 && r.hideForNow && resumed) {
4357 // We had hidden the activity because it started another
4358 // one... we have gotten a result back and we are not
4359 // paused, so make sure our window is visible.
4360 updateVisibility(r, true);
4361 }
4362 if (resumed) {
4363 try {
4364 // Now we are idle.
4365 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004366 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004367 mInstrumentation.callActivityOnPause(r.activity);
4368 if (!r.activity.mCalled) {
4369 throw new SuperNotCalledException(
4370 "Activity " + r.intent.getComponent().toShortString()
4371 + " did not call through to super.onPause()");
4372 }
4373 } catch (SuperNotCalledException e) {
4374 throw e;
4375 } catch (Exception e) {
4376 if (!mInstrumentation.onException(r.activity, e)) {
4377 throw new RuntimeException(
4378 "Unable to pause activity "
4379 + r.intent.getComponent().toShortString()
4380 + ": " + e.toString(), e);
4381 }
4382 }
4383 }
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07004384 checkAndBlockForNetworkAccess();
Andrii Kulian446e8242017-10-26 15:17:29 -07004385 deliverResults(r, results);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004386 if (resumed) {
Dake Gu67decfa2017-12-27 11:48:08 -08004387 r.activity.performResume(false);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004388 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004389 }
4390 }
4391 }
4392
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004393 /** Core implementation of activity destroy call. */
4394 ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
Bryce Leea33c13d2018-02-08 14:37:06 -08004395 int configChanges, boolean getNonConfigInstance, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004396 ActivityClientRecord r = mActivities.get(token);
Craig Mautner88c05892013-06-28 09:47:45 -07004397 Class<? extends Activity> activityClass = null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004398 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004399 if (r != null) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08004400 activityClass = r.activity.getClass();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004401 r.activity.mConfigChangeFlags |= configChanges;
4402 if (finishing) {
4403 r.activity.mFinished = true;
4404 }
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004405
4406 performPauseActivityIfNeeded(r, "destroy");
4407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004408 if (!r.stopped) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004409 callActivityOnStop(r, false /* saveState */, "destroy");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004410 }
4411 if (getNonConfigInstance) {
4412 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004413 r.lastNonConfigurationInstances
4414 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004415 } catch (Exception e) {
4416 if (!mInstrumentation.onException(r.activity, e)) {
4417 throw new RuntimeException(
4418 "Unable to retain activity "
4419 + r.intent.getComponent().toShortString()
4420 + ": " + e.toString(), e);
4421 }
4422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004423 }
4424 try {
4425 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004426 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004427 if (!r.activity.mCalled) {
4428 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004429 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004430 " did not call through to super.onDestroy()");
4431 }
4432 if (r.window != null) {
4433 r.window.closeAllPanels();
4434 }
4435 } catch (SuperNotCalledException e) {
4436 throw e;
4437 } catch (Exception e) {
4438 if (!mInstrumentation.onException(r.activity, e)) {
4439 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004440 "Unable to destroy activity " + safeToComponentShortString(r.intent)
4441 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004442 }
4443 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004444 r.setState(ON_DESTROY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004445 }
4446 mActivities.remove(token);
Bryce Leea33c13d2018-02-08 14:37:06 -08004447 mRecentDestroyedActivities.add(0, new DestroyedActivityInfo(token.hashCode(), reason));
4448
4449 final int recentDestroyedActivitiesSize = mRecentDestroyedActivities.size();
4450 if (recentDestroyedActivitiesSize > MAX_DESTROYED_ACTIVITIES) {
4451 mRecentDestroyedActivities.remove(recentDestroyedActivitiesSize - 1);
4452 }
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08004453 StrictMode.decrementExpectedActivityCount(activityClass);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004454 return r;
4455 }
4456
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004457 private static String safeToComponentShortString(Intent intent) {
4458 ComponentName component = intent.getComponent();
4459 return component == null ? "[Unknown]" : component.toShortString();
4460 }
4461
Andrii Kulian446e8242017-10-26 15:17:29 -07004462 @Override
4463 public void handleDestroyActivity(IBinder token, boolean finishing, int configChanges,
Bryce Leea33c13d2018-02-08 14:37:06 -08004464 boolean getNonConfigInstance, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004465 ActivityClientRecord r = performDestroyActivity(token, finishing,
Bryce Leea33c13d2018-02-08 14:37:06 -08004466 configChanges, getNonConfigInstance, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004467 if (r != null) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004468 cleanUpPendingRemoveWindows(r, finishing);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004469 WindowManager wm = r.activity.getWindowManager();
4470 View v = r.activity.mDecor;
4471 if (v != null) {
4472 if (r.activity.mVisibleFromServer) {
4473 mNumVisibleActivities--;
4474 }
4475 IBinder wtoken = v.getWindowToken();
4476 if (r.activity.mWindowAdded) {
Robert Carr77bdfb52016-05-02 18:18:31 -07004477 if (r.mPreserveWindow) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004478 // Hold off on removing this until the new activity's
4479 // window is being added.
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004480 r.mPendingRemoveWindow = r.window;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004481 r.mPendingRemoveWindowManager = wm;
Andrii Kulianeac0ea52016-05-11 15:50:24 -07004482 // We can only keep the part of the view hierarchy that we control,
4483 // everything else must be removed, because it might not be able to
4484 // behave properly when activity is relaunching.
4485 r.window.clearContentView();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004486 } else {
4487 wm.removeViewImmediate(v);
4488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004489 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004490 if (wtoken != null && r.mPendingRemoveWindow == null) {
Jeff Brown98365d72012-08-19 20:30:52 -07004491 WindowManagerGlobal.getInstance().closeAll(wtoken,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004492 r.activity.getClass().getName(), "Activity");
Andrii Kulianeac0ea52016-05-11 15:50:24 -07004493 } else if (r.mPendingRemoveWindow != null) {
4494 // We're preserving only one window, others should be closed so app views
4495 // will be detached before the final tear down. It should be done now because
4496 // some components (e.g. WebView) rely on detach callbacks to perform receiver
4497 // unregister and other cleanup.
4498 WindowManagerGlobal.getInstance().closeAllExceptView(token, v,
4499 r.activity.getClass().getName(), "Activity");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004500 }
4501 r.activity.mDecor = null;
4502 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004503 if (r.mPendingRemoveWindow == null) {
4504 // If we are delaying the removal of the activity window, then
4505 // we can't clean up all windows here. Note that we can't do
4506 // so later either, which means any windows that aren't closed
4507 // by the app will leak. Well we try to warning them a lot
4508 // about leaking windows, because that is a bug, so if they are
4509 // using this recreate facility then they get to live with leaks.
Jeff Brown98365d72012-08-19 20:30:52 -07004510 WindowManagerGlobal.getInstance().closeAll(token,
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004511 r.activity.getClass().getName(), "Activity");
4512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004513
4514 // Mocked out contexts won't be participating in the normal
4515 // process lifecycle, but if we're running with a proper
4516 // ApplicationContext we need to have it tear down things
4517 // cleanly.
4518 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08004519 if (c instanceof ContextImpl) {
4520 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004521 r.activity.getClass().getName(), "Activity");
4522 }
4523 }
4524 if (finishing) {
4525 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004526 ActivityManager.getService().activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004527 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004528 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004529 }
4530 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004531 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004532 }
4533
Andrii Kulianb372da62018-01-18 10:46:24 -08004534 @Override
4535 public ActivityClientRecord prepareRelaunchActivity(IBinder token,
Dianne Hackborn85d558c2014-11-04 10:31:54 -08004536 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
Andrii Kulianb372da62018-01-18 10:46:24 -08004537 int configChanges, MergedConfiguration config, boolean preserveWindow) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004538 ActivityClientRecord target = null;
Andrii Kulianb372da62018-01-18 10:46:24 -08004539 boolean scheduleRelaunch = false;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004540
Craig Mautner88c05892013-06-28 09:47:45 -07004541 synchronized (mResourcesManager) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004542 for (int i=0; i<mRelaunchingActivities.size(); i++) {
4543 ActivityClientRecord r = mRelaunchingActivities.get(i);
Filip Gruszczynskic3b61792016-01-22 16:43:48 -08004544 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: " + this + ", trying: " + r);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004545 if (r.token == token) {
4546 target = r;
4547 if (pendingResults != null) {
4548 if (r.pendingResults != null) {
4549 r.pendingResults.addAll(pendingResults);
4550 } else {
4551 r.pendingResults = pendingResults;
4552 }
4553 }
4554 if (pendingNewIntents != null) {
4555 if (r.pendingIntents != null) {
4556 r.pendingIntents.addAll(pendingNewIntents);
4557 } else {
4558 r.pendingIntents = pendingNewIntents;
4559 }
4560 }
4561 break;
4562 }
4563 }
4564
4565 if (target == null) {
Andrii Kulianb372da62018-01-18 10:46:24 -08004566 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: target is null");
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004567 target = new ActivityClientRecord();
4568 target.token = token;
4569 target.pendingResults = pendingResults;
4570 target.pendingIntents = pendingNewIntents;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004571 target.mPreserveWindow = preserveWindow;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004572 mRelaunchingActivities.add(target);
Andrii Kulianb372da62018-01-18 10:46:24 -08004573 scheduleRelaunch = true;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004574 }
Andrii Kulianb372da62018-01-18 10:46:24 -08004575 target.createdConfig = config.getGlobalConfiguration();
4576 target.overrideConfig = config.getOverrideConfiguration();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004577 target.pendingConfigChanges |= configChanges;
4578 }
Andrii Kulianb372da62018-01-18 10:46:24 -08004579
4580 return scheduleRelaunch ? target : null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004581 }
4582
Andrii Kulianb372da62018-01-18 10:46:24 -08004583 @Override
4584 public void handleRelaunchActivity(ActivityClientRecord tmp,
4585 PendingTransactionActions pendingActions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004586 // If we are getting ready to gc after going to the background, well
4587 // we are back active so skip it.
4588 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004589 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004590
4591 Configuration changedConfig = null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004592 int configChanges = 0;
Bob Leee5408332009-09-04 18:31:17 -07004593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004594 // First: make sure we have the most recent configuration and most
4595 // recent version of the activity, or skip it if some previous call
4596 // had taken a more recent version.
Craig Mautner88c05892013-06-28 09:47:45 -07004597 synchronized (mResourcesManager) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004598 int N = mRelaunchingActivities.size();
4599 IBinder token = tmp.token;
4600 tmp = null;
4601 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004602 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004603 if (r.token == token) {
4604 tmp = r;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004605 configChanges |= tmp.pendingConfigChanges;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004606 mRelaunchingActivities.remove(i);
4607 i--;
4608 N--;
4609 }
4610 }
Bob Leee5408332009-09-04 18:31:17 -07004611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004612 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004613 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004614 return;
4615 }
Bob Leee5408332009-09-04 18:31:17 -07004616
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004617 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
4618 + tmp.token + " with configChanges=0x"
4619 + Integer.toHexString(configChanges));
4620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004621 if (mPendingConfiguration != null) {
4622 changedConfig = mPendingConfiguration;
4623 mPendingConfiguration = null;
4624 }
4625 }
Bob Leee5408332009-09-04 18:31:17 -07004626
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08004627 if (tmp.createdConfig != null) {
4628 // If the activity manager is passing us its current config,
4629 // assume that is really what we want regardless of what we
4630 // may have pending.
4631 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004632 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
4633 && mConfiguration.diff(tmp.createdConfig) != 0)) {
4634 if (changedConfig == null
4635 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
4636 changedConfig = tmp.createdConfig;
4637 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08004638 }
4639 }
Tim Murraye1e6c662015-04-07 13:24:14 -07004640
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004641 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004642 + tmp.token + ": changedConfig=" + changedConfig);
Tim Murraye1e6c662015-04-07 13:24:14 -07004643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004644 // If there was a pending configuration change, execute it first.
4645 if (changedConfig != null) {
Dianne Hackborn908aecc2012-07-31 16:37:34 -07004646 mCurDefaultDisplayDpi = changedConfig.densityDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -07004647 updateDefaultDensity();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004648 handleConfigurationChanged(changedConfig, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004649 }
Bob Leee5408332009-09-04 18:31:17 -07004650
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004651 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004652 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004653 if (r == null) {
4654 return;
4655 }
Bob Leee5408332009-09-04 18:31:17 -07004656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004657 r.activity.mConfigChangeFlags |= configChanges;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004658 r.mPreserveWindow = tmp.mPreserveWindow;
Bob Leee5408332009-09-04 18:31:17 -07004659
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004660 r.activity.mChangingConfigurations = true;
4661
Robert Carr23fa16b2016-01-13 13:19:58 -08004662 // If we are preserving the main window across relaunches we would also like to preserve
4663 // the children. However the client side view system does not support preserving
4664 // the child views so we notify the window manager to expect these windows to
4665 // be replaced and defer requests to destroy or hide them. This way we can achieve
4666 // visual continuity. It's important that we do this here prior to pause and destroy
4667 // as that is when we may hide or remove the child views.
Robert Carr77bdfb52016-05-02 18:18:31 -07004668 //
4669 // There is another scenario, if we have decided locally to relaunch the app from a
4670 // call to recreate, then none of the windows will be prepared for replacement or
4671 // preserved by the server, so we want to notify it that we are preparing to replace
4672 // everything
Robert Carr23fa16b2016-01-13 13:19:58 -08004673 try {
Andrii Kulianb372da62018-01-18 10:46:24 -08004674 if (r.mPreserveWindow) {
Robert Carr77bdfb52016-05-02 18:18:31 -07004675 WindowManagerGlobal.getWindowSession().prepareToReplaceWindows(
Andrii Kulianb372da62018-01-18 10:46:24 -08004676 r.token, true /* childrenOnly */);
Robert Carr23fa16b2016-01-13 13:19:58 -08004677 }
4678 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004679 throw e.rethrowFromSystemServer();
Robert Carr23fa16b2016-01-13 13:19:58 -08004680 }
4681
Dianne Hackborne2b04802010-12-09 09:24:55 -08004682 // Need to ensure state is saved.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004683 if (!r.paused) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004684 performPauseActivity(r, false, "handleRelaunchActivity",
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004685 null /* pendingActions */);
Dianne Hackborne2b04802010-12-09 09:24:55 -08004686 }
Andrii Kulian8ae79572018-01-26 15:36:06 -08004687 if (!r.stopped) {
4688 callActivityOnStop(r, true /* saveState */, "handleRelaunchActivity");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004689 }
Bob Leee5408332009-09-04 18:31:17 -07004690
Bryce Leea33c13d2018-02-08 14:37:06 -08004691 handleDestroyActivity(r.token, false, configChanges, true, "handleRelaunchActivity");
Bob Leee5408332009-09-04 18:31:17 -07004692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004693 r.activity = null;
4694 r.window = null;
4695 r.hideForNow = false;
4696 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07004697 // Merge any pending results and pending intents; don't just replace them
4698 if (tmp.pendingResults != null) {
4699 if (r.pendingResults == null) {
4700 r.pendingResults = tmp.pendingResults;
4701 } else {
4702 r.pendingResults.addAll(tmp.pendingResults);
4703 }
4704 }
4705 if (tmp.pendingIntents != null) {
4706 if (r.pendingIntents == null) {
4707 r.pendingIntents = tmp.pendingIntents;
4708 } else {
4709 r.pendingIntents.addAll(tmp.pendingIntents);
4710 }
4711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004712 r.startsNotResumed = tmp.startsNotResumed;
Wale Ogunwale60454db2015-01-23 16:05:07 -08004713 r.overrideConfig = tmp.overrideConfig;
Bob Leee5408332009-09-04 18:31:17 -07004714
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004715 handleLaunchActivity(r, pendingActions);
Andrii Kulianb372da62018-01-18 10:46:24 -08004716 // Only report a successful relaunch to WindowManager.
4717 pendingActions.setReportRelaunchToWindowManager(true);
4718 }
Jorim Jaggife89d122015-12-22 16:28:44 +01004719
Andrii Kulianb372da62018-01-18 10:46:24 -08004720 @Override
4721 public void reportRelaunch(IBinder token, PendingTransactionActions pendingActions) {
4722 try {
4723 ActivityManager.getService().activityRelaunched(token);
4724 final ActivityClientRecord r = mActivities.get(token);
4725 if (pendingActions.shouldReportRelaunchToWindowManager() && r != null
4726 && r.window != null) {
4727 r.window.reportActivityRelaunched();
Jorim Jaggife89d122015-12-22 16:28:44 +01004728 }
Andrii Kulianb372da62018-01-18 10:46:24 -08004729 } catch (RemoteException e) {
4730 throw e.rethrowFromSystemServer();
Jorim Jaggife89d122015-12-22 16:28:44 +01004731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004732 }
4733
Andrii Kulian8ae79572018-01-26 15:36:06 -08004734 private void callActivityOnSaveInstanceState(ActivityClientRecord r) {
Craig Mautnera0026042014-04-23 11:45:37 -07004735 r.state = new Bundle();
4736 r.state.setAllowFds(false);
4737 if (r.isPersistable()) {
4738 r.persistentState = new PersistableBundle();
4739 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state,
4740 r.persistentState);
4741 } else {
4742 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
4743 }
4744 }
4745
Dianne Hackborn73c14162012-09-19 15:45:06 -07004746 ArrayList<ComponentCallbacks2> collectComponentCallbacks(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004747 boolean allActivities, Configuration newConfig) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07004748 ArrayList<ComponentCallbacks2> callbacks
4749 = new ArrayList<ComponentCallbacks2>();
Bob Leee5408332009-09-04 18:31:17 -07004750
Craig Mautner88c05892013-06-28 09:47:45 -07004751 synchronized (mResourcesManager) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004752 final int NAPP = mAllApplications.size();
4753 for (int i=0; i<NAPP; i++) {
Dianne Hackborn73c14162012-09-19 15:45:06 -07004754 callbacks.add(mAllApplications.get(i));
4755 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004756 final int NACT = mActivities.size();
4757 for (int i=0; i<NACT; i++) {
4758 ActivityClientRecord ar = mActivities.valueAt(i);
4759 Activity a = ar.activity;
4760 if (a != null) {
4761 Configuration thisConfig = applyConfigCompatMainThread(
4762 mCurDefaultDisplayDpi, newConfig,
Todd Kennedy233a0b12018-01-29 20:30:24 +00004763 ar.packageInfo.getCompatibilityInfo());
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004764 if (!ar.activity.mFinished && (allActivities || !ar.paused)) {
4765 // If the activity is currently resumed, its configuration
4766 // needs to change right now.
4767 callbacks.add(a);
4768 } else if (thisConfig != null) {
4769 // Otherwise, we will tell it about the change
4770 // the next time it is resumed or shown. Note that
4771 // the activity manager may, before then, decide the
4772 // activity needs to be destroyed to handle its new
4773 // configuration.
4774 if (DEBUG_CONFIGURATION) {
4775 Slog.v(TAG, "Setting activity "
4776 + ar.activityInfo.name + " newConfig=" + thisConfig);
Romain Guya998dff2012-03-23 18:58:36 -07004777 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004778 ar.newConfig = thisConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004779 }
4780 }
4781 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004782 final int NSVC = mServices.size();
4783 for (int i=0; i<NSVC; i++) {
4784 callbacks.add(mServices.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004785 }
4786 }
4787 synchronized (mProviderMap) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004788 final int NPRV = mLocalProviders.size();
4789 for (int i=0; i<NPRV; i++) {
4790 callbacks.add(mLocalProviders.valueAt(i).mLocalProvider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004791 }
4792 }
Bob Leee5408332009-09-04 18:31:17 -07004793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004794 return callbacks;
4795 }
Bob Leee5408332009-09-04 18:31:17 -07004796
Adam Lesinski082614c2016-03-04 14:33:47 -08004797 /**
4798 * Updates the configuration for an Activity. The ActivityClientRecord's
4799 * {@link ActivityClientRecord#overrideConfig} is used to compute the final Configuration for
4800 * that Activity. {@link ActivityClientRecord#tmpConfig} is used as a temporary for delivering
4801 * the updated Configuration.
4802 * @param r ActivityClientRecord representing the Activity.
4803 * @param newBaseConfig The new configuration to use. This may be augmented with
4804 * {@link ActivityClientRecord#overrideConfig}.
Adam Lesinski082614c2016-03-04 14:33:47 -08004805 */
4806 private void performConfigurationChangedForActivity(ActivityClientRecord r,
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004807 Configuration newBaseConfig) {
4808 performConfigurationChangedForActivity(r, newBaseConfig,
4809 r.activity.getDisplay().getDisplayId(), false /* movedToDifferentDisplay */);
4810 }
4811
4812 /**
4813 * Updates the configuration for an Activity. The ActivityClientRecord's
4814 * {@link ActivityClientRecord#overrideConfig} is used to compute the final Configuration for
4815 * that Activity. {@link ActivityClientRecord#tmpConfig} is used as a temporary for delivering
4816 * the updated Configuration.
4817 * @param r ActivityClientRecord representing the Activity.
4818 * @param newBaseConfig The new configuration to use. This may be augmented with
4819 * {@link ActivityClientRecord#overrideConfig}.
4820 * @param displayId The id of the display where the Activity currently resides.
4821 * @param movedToDifferentDisplay Indicates if the activity was moved to different display.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004822 * @return {@link Configuration} instance sent to client, null if not sent.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004823 */
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004824 private Configuration performConfigurationChangedForActivity(ActivityClientRecord r,
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004825 Configuration newBaseConfig, int displayId, boolean movedToDifferentDisplay) {
Adam Lesinski082614c2016-03-04 14:33:47 -08004826 r.tmpConfig.setTo(newBaseConfig);
4827 if (r.overrideConfig != null) {
4828 r.tmpConfig.updateFrom(r.overrideConfig);
4829 }
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004830 final Configuration reportedConfig = performActivityConfigurationChanged(r.activity,
4831 r.tmpConfig, r.overrideConfig, displayId, movedToDifferentDisplay);
Adam Lesinski082614c2016-03-04 14:33:47 -08004832 freeTextLayoutCachesIfNeeded(r.activity.mCurrentConfig.diff(r.tmpConfig));
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004833 return reportedConfig;
Adam Lesinski082614c2016-03-04 14:33:47 -08004834 }
4835
4836 /**
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -07004837 * Creates a new Configuration only if override would modify base. Otherwise returns base.
4838 * @param base The base configuration.
4839 * @param override The update to apply to the base configuration. Can be null.
4840 * @return A Configuration representing base with override applied.
4841 */
4842 private static Configuration createNewConfigAndUpdateIfNotNull(@NonNull Configuration base,
4843 @Nullable Configuration override) {
4844 if (override == null) {
4845 return base;
4846 }
4847 Configuration newConfig = new Configuration(base);
4848 newConfig.updateFrom(override);
4849 return newConfig;
4850 }
4851
4852 /**
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004853 * Decides whether to update a component's configuration and whether to inform it.
Adam Lesinski082614c2016-03-04 14:33:47 -08004854 * @param cb The component callback to notify of configuration change.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004855 * @param newConfig The new configuration.
4856 */
4857 private void performConfigurationChanged(ComponentCallbacks2 cb, Configuration newConfig) {
4858 if (!REPORT_TO_ACTIVITY) {
4859 return;
4860 }
4861
4862 // ContextThemeWrappers may override the configuration for that context. We must check and
4863 // apply any overrides defined.
4864 Configuration contextThemeWrapperOverrideConfig = null;
4865 if (cb instanceof ContextThemeWrapper) {
4866 final ContextThemeWrapper contextThemeWrapper = (ContextThemeWrapper) cb;
4867 contextThemeWrapperOverrideConfig = contextThemeWrapper.getOverrideConfiguration();
4868 }
4869
4870 // Apply the ContextThemeWrapper override if necessary.
4871 // NOTE: Make sure the configurations are not modified, as they are treated as immutable
4872 // in many places.
4873 final Configuration configToReport = createNewConfigAndUpdateIfNotNull(
4874 newConfig, contextThemeWrapperOverrideConfig);
4875 cb.onConfigurationChanged(configToReport);
4876 }
4877
4878 /**
4879 * Decides whether to update an Activity's configuration and whether to inform it.
4880 * @param activity The activity to notify of configuration change.
Adam Lesinski082614c2016-03-04 14:33:47 -08004881 * @param newConfig The new configuration.
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -07004882 * @param amOverrideConfig The override config that differentiates the Activity's configuration
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004883 * from the base global configuration. This is supplied by
4884 * ActivityManager.
4885 * @param displayId Id of the display where activity currently resides.
4886 * @param movedToDifferentDisplay Indicates if the activity was moved to different display.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004887 * @return Configuration sent to client, null if no changes and not moved to different display.
Adam Lesinski082614c2016-03-04 14:33:47 -08004888 */
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004889 private Configuration performActivityConfigurationChanged(Activity activity,
4890 Configuration newConfig, Configuration amOverrideConfig, int displayId,
4891 boolean movedToDifferentDisplay) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004892 if (activity == null) {
4893 throw new IllegalArgumentException("No activity provided.");
4894 }
4895 final IBinder activityToken = activity.getActivityToken();
4896 if (activityToken == null) {
4897 throw new IllegalArgumentException("Activity token not set. Is the activity attached?");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004898 }
Bob Leee5408332009-09-04 18:31:17 -07004899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004900 boolean shouldChangeConfig = false;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004901 if (activity.mCurrentConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004902 shouldChangeConfig = true;
4903 } else {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004904 // If the new config is the same as the config this Activity is already running with and
4905 // the override config also didn't change, then don't bother calling
4906 // onConfigurationChanged.
Bryce Lee658d9842017-07-28 08:33:36 -07004907 final int diff = activity.mCurrentConfig.diffPublicOnly(newConfig);
4908
Andrii Kulian3b3c9142016-07-18 19:15:56 -07004909 if (diff != 0 || !mResourcesManager.isSameResourcesOverrideConfig(activityToken,
4910 amOverrideConfig)) {
Chong Zhang4951f9d2016-06-23 13:15:08 -07004911 // Always send the task-level config changes. For system-level configuration, if
4912 // this activity doesn't handle any of the config changes, then don't bother
4913 // calling onConfigurationChanged as we're going to destroy it.
4914 if (!mUpdatingSystemConfig
4915 || (~activity.mActivityInfo.getRealConfigChanged() & diff) == 0
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004916 || !REPORT_TO_ACTIVITY) {
Chong Zhang4951f9d2016-06-23 13:15:08 -07004917 shouldChangeConfig = true;
4918 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004919 }
4920 }
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004921 if (!shouldChangeConfig && !movedToDifferentDisplay) {
4922 // Nothing significant, don't proceed with updating and reporting.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004923 return null;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004924 }
4925
4926 // Propagate the configuration change to ResourcesManager and Activity.
4927
4928 // ContextThemeWrappers may override the configuration for that context. We must check and
4929 // apply any overrides defined.
4930 Configuration contextThemeWrapperOverrideConfig = activity.getOverrideConfiguration();
4931
4932 // We only update an Activity's configuration if this is not a global configuration change.
4933 // This must also be done before the callback, or else we violate the contract that the new
4934 // resources are available in ComponentCallbacks2#onConfigurationChanged(Configuration).
4935 // Also apply the ContextThemeWrapper override if necessary.
4936 // NOTE: Make sure the configurations are not modified, as they are treated as immutable in
4937 // many places.
4938 final Configuration finalOverrideConfig = createNewConfigAndUpdateIfNotNull(
4939 amOverrideConfig, contextThemeWrapperOverrideConfig);
4940 mResourcesManager.updateResourcesForActivity(activityToken, finalOverrideConfig,
4941 displayId, movedToDifferentDisplay);
4942
4943 activity.mConfigChangeFlags = 0;
4944 activity.mCurrentConfig = new Configuration(newConfig);
4945
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004946 // Apply the ContextThemeWrapper override if necessary.
4947 // NOTE: Make sure the configurations are not modified, as they are treated as immutable
4948 // in many places.
4949 final Configuration configToReport = createNewConfigAndUpdateIfNotNull(newConfig,
4950 contextThemeWrapperOverrideConfig);
4951
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004952 if (!REPORT_TO_ACTIVITY) {
4953 // Not configured to report to activity.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004954 return configToReport;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004955 }
4956
4957 if (movedToDifferentDisplay) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004958 activity.dispatchMovedToDisplay(displayId, configToReport);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004959 }
Bob Leee5408332009-09-04 18:31:17 -07004960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004961 if (shouldChangeConfig) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004962 activity.mCalled = false;
4963 activity.onConfigurationChanged(configToReport);
4964 if (!activity.mCalled) {
4965 throw new SuperNotCalledException("Activity " + activity.getLocalClassName() +
4966 " did not call through to super.onConfigurationChanged()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004967 }
4968 }
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004969
4970 return configToReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004971 }
4972
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07004973 public final void applyConfigurationToResources(Configuration config) {
Craig Mautner88c05892013-06-28 09:47:45 -07004974 synchronized (mResourcesManager) {
4975 mResourcesManager.applyConfigurationToResourcesLocked(config, null);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07004976 }
4977 }
4978
Dianne Hackborn908aecc2012-07-31 16:37:34 -07004979 final Configuration applyCompatConfiguration(int displayDensity) {
Dianne Hackborn836e2622011-10-04 18:32:39 -07004980 Configuration config = mConfiguration;
4981 if (mCompatConfiguration == null) {
4982 mCompatConfiguration = new Configuration();
4983 }
4984 mCompatConfiguration.setTo(mConfiguration);
Adam Lesinski082614c2016-03-04 14:33:47 -08004985 if (mResourcesManager.applyCompatConfigurationLocked(displayDensity,
4986 mCompatConfiguration)) {
Dianne Hackborn836e2622011-10-04 18:32:39 -07004987 config = mCompatConfiguration;
4988 }
4989 return config;
4990 }
4991
Andrii Kulian446e8242017-10-26 15:17:29 -07004992 @Override
4993 public void handleConfigurationChanged(Configuration config) {
4994 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "configChanged");
4995 mCurDefaultDisplayDpi = config.densityDpi;
4996 mUpdatingSystemConfig = true;
4997 try {
4998 handleConfigurationChanged(config, null /* compat */);
4999 } finally {
5000 mUpdatingSystemConfig = false;
5001 }
5002 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
5003 }
5004
5005 private void handleConfigurationChanged(Configuration config, CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005006
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005007 int configDiff = 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005008
Bryce Lee658d9842017-07-28 08:33:36 -07005009 // This flag tracks whether the new configuration is fundamentally equivalent to the
5010 // existing configuration. This is necessary to determine whether non-activity
5011 // callbacks should receive notice when the only changes are related to non-public fields.
5012 // We do not gate calling {@link #performActivityConfigurationChanged} based on this flag
5013 // as that method uses the same check on the activity config override as well.
5014 final boolean equivalent = config != null && mConfiguration != null
5015 && (0 == mConfiguration.diffPublicOnly(config));
Todd Kennedy35a9a382018-01-25 13:25:37 -08005016 final Theme systemTheme = getSystemContext().getTheme();
5017 final Theme systemUiTheme = getSystemUiContext().getTheme();
Bryce Lee658d9842017-07-28 08:33:36 -07005018
Craig Mautner88c05892013-06-28 09:47:45 -07005019 synchronized (mResourcesManager) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005020 if (mPendingConfiguration != null) {
5021 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
5022 config = mPendingConfiguration;
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005023 mCurDefaultDisplayDpi = config.densityDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -07005024 updateDefaultDensity();
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005025 }
5026 mPendingConfiguration = null;
5027 }
5028
5029 if (config == null) {
5030 return;
5031 }
Tim Murraye1e6c662015-04-07 13:24:14 -07005032
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005033 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005034 + config);
Craig Mautner88c05892013-06-28 09:47:45 -07005035
5036 mResourcesManager.applyConfigurationToResourcesLocked(config, compat);
Adam Lesinskib61e4052016-05-19 18:23:05 -07005037 updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
5038 mResourcesManager.getConfiguration().getLocales());
Craig Mautner88c05892013-06-28 09:47:45 -07005039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005040 if (mConfiguration == null) {
5041 mConfiguration = new Configuration();
5042 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04005043 if (!mConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005044 return;
5045 }
Alan Viverettee54d2452015-05-06 10:41:43 -07005046
5047 configDiff = mConfiguration.updateFrom(config);
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005048 config = applyCompatConfiguration(mCurDefaultDisplayDpi);
Alan Viverette395cd012015-08-11 17:27:04 -04005049
Alan Viverette395cd012015-08-11 17:27:04 -04005050 if ((systemTheme.getChangingConfigurations() & configDiff) != 0) {
5051 systemTheme.rebase();
5052 }
Adam Lesinskia82b6262017-03-21 16:56:17 -07005053
Adam Lesinskia82b6262017-03-21 16:56:17 -07005054 if ((systemUiTheme.getChangingConfigurations() & configDiff) != 0) {
5055 systemUiTheme.rebase();
5056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005057 }
Dianne Hackborn73c14162012-09-19 15:45:06 -07005058
5059 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(false, config);
5060
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005061 freeTextLayoutCachesIfNeeded(configDiff);
5062
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005063 if (callbacks != null) {
5064 final int N = callbacks.size();
5065 for (int i=0; i<N; i++) {
Andrii Kulian701214b2016-04-07 09:36:33 -07005066 ComponentCallbacks2 cb = callbacks.get(i);
5067 if (cb instanceof Activity) {
5068 // If callback is an Activity - call corresponding method to consider override
5069 // config and avoid onConfigurationChanged if it hasn't changed.
5070 Activity a = (Activity) cb;
5071 performConfigurationChangedForActivity(mActivities.get(a.getActivityToken()),
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005072 config);
Bryce Lee658d9842017-07-28 08:33:36 -07005073 } else if (!equivalent) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005074 performConfigurationChanged(cb, config);
Andrii Kulian701214b2016-04-07 09:36:33 -07005075 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005077 }
5078 }
5079
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005080 void handleApplicationInfoChanged(@NonNull final ApplicationInfo ai) {
Adam Lesinskid33ef562017-01-19 14:49:59 -08005081 // Updates triggered by package installation go through a package update
5082 // receiver. Here we try to capture ApplicationInfo changes that are
5083 // caused by other sources, such as overlays. That means we want to be as conservative
5084 // about code changes as possible. Take the diff of the old ApplicationInfo and the new
5085 // to see if anything needs to change.
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005086 LoadedApk apk;
5087 LoadedApk resApk;
5088 // Update all affected loaded packages with new package information
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005089 synchronized (mResourcesManager) {
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005090 WeakReference<LoadedApk> ref = mPackages.get(ai.packageName);
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005091 apk = ref != null ? ref.get() : null;
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005092 ref = mResourcePackages.get(ai.packageName);
5093 resApk = ref != null ? ref.get() : null;
5094 }
5095 if (apk != null) {
5096 final ArrayList<String> oldPaths = new ArrayList<>();
5097 LoadedApk.makePaths(this, apk.getApplicationInfo(), oldPaths);
5098 apk.updateApplicationInfo(ai, oldPaths);
5099 }
5100 if (resApk != null) {
5101 final ArrayList<String> oldPaths = new ArrayList<>();
5102 LoadedApk.makePaths(this, resApk.getApplicationInfo(), oldPaths);
5103 resApk.updateApplicationInfo(ai, oldPaths);
5104 }
5105 synchronized (mResourcesManager) {
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005106 // Update all affected Resources objects to use new ResourcesImpl
5107 mResourcesManager.applyNewResourceDirsLocked(ai.sourceDir, ai.resourceDirs);
5108 }
5109
5110 ApplicationPackageManager.configurationChanged();
5111
5112 // Trigger a regular Configuration change event, only with a different assetsSeq number
5113 // so that we actually call through to all components.
Adam Lesinskia82b6262017-03-21 16:56:17 -07005114 // TODO(adamlesinski): Change this to make use of ActivityManager's upcoming ability to
5115 // store configurations per-process.
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005116 Configuration newConfig = new Configuration();
Adam Lesinskia82b6262017-03-21 16:56:17 -07005117 newConfig.assetsSeq = (mConfiguration != null ? mConfiguration.assetsSeq : 0) + 1;
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005118 handleConfigurationChanged(newConfig, null);
5119
Fyodor Kupolovcb93d6f2017-05-04 17:27:16 -07005120 requestRelaunchAllActivities();
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005121 }
5122
Romain Guy46bfc482013-08-16 18:38:29 -07005123 static void freeTextLayoutCachesIfNeeded(int configDiff) {
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005124 if (configDiff != 0) {
5125 // Ask text layout engine to free its caches if there is a locale change
5126 boolean hasLocaleConfigChange = ((configDiff & ActivityInfo.CONFIG_LOCALE) != 0);
5127 if (hasLocaleConfigChange) {
5128 Canvas.freeTextLayoutCaches();
5129 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Cleared TextLayout Caches");
5130 }
5131 }
5132 }
5133
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005134 /**
5135 * Handle new activity configuration and/or move to a different display.
Andrii Kulian446e8242017-10-26 15:17:29 -07005136 * @param activityToken Target activity token.
5137 * @param overrideConfig Activity override config.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005138 * @param displayId Id of the display where activity was moved to, -1 if there was no move and
5139 * value didn't change.
5140 */
Andrii Kulian446e8242017-10-26 15:17:29 -07005141 @Override
5142 public void handleActivityConfigurationChanged(IBinder activityToken,
5143 Configuration overrideConfig, int displayId) {
5144 ActivityClientRecord r = mActivities.get(activityToken);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005145 // Check input params.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005146 if (r == null || r.activity == null) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005147 if (DEBUG_CONFIGURATION) Slog.w(TAG, "Not found target activity to report to: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005148 return;
5149 }
Andrii Kulian51c1b672017-04-07 18:39:32 -07005150 final boolean movedToDifferentDisplay = displayId != INVALID_DISPLAY
5151 && displayId != r.activity.getDisplay().getDisplayId();
Bob Leee5408332009-09-04 18:31:17 -07005152
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005153 // Perform updates.
Andrii Kulian446e8242017-10-26 15:17:29 -07005154 r.overrideConfig = overrideConfig;
Stephen Kiazykf903b732017-03-20 16:23:45 -07005155 final ViewRootImpl viewRoot = r.activity.mDecor != null
5156 ? r.activity.mDecor.getViewRootImpl() : null;
5157
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005158 if (movedToDifferentDisplay) {
5159 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity moved to display, activity:"
5160 + r.activityInfo.name + ", displayId=" + displayId
Andrii Kulian446e8242017-10-26 15:17:29 -07005161 + ", config=" + overrideConfig);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005162
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005163 final Configuration reportedConfig = performConfigurationChangedForActivity(r,
5164 mCompatConfiguration, displayId, true /* movedToDifferentDisplay */);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005165 if (viewRoot != null) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005166 viewRoot.onMovedToDisplay(displayId, reportedConfig);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005167 }
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005168 } else {
5169 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Andrii Kulian446e8242017-10-26 15:17:29 -07005170 + r.activityInfo.name + ", config=" + overrideConfig);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005171 performConfigurationChangedForActivity(r, mCompatConfiguration);
5172 }
Andrii Kulian44607962017-03-16 11:06:24 -07005173 // Notify the ViewRootImpl instance about configuration changes. It may have initiated this
5174 // update to make sure that resources are updated before updating itself.
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005175 if (viewRoot != null) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005176 viewRoot.updateConfiguration(displayId);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005177 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07005178 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005179 }
5180
Jeff Hao1b012d32014-08-20 10:35:34 -07005181 final void handleProfilerControl(boolean start, ProfilerInfo profilerInfo, int profileType) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005182 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005183 try {
Romain Guy7eabe552011-07-21 14:56:34 -07005184 switch (profileType) {
Jeff Hao1b012d32014-08-20 10:35:34 -07005185 default:
5186 mProfiler.setProfiler(profilerInfo);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005187 mProfiler.startProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07005188 break;
5189 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005190 } catch (RuntimeException e) {
Jeff Hao1b012d32014-08-20 10:35:34 -07005191 Slog.w(TAG, "Profiling failed on path " + profilerInfo.profileFile
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005192 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07005193 } finally {
Andreas Gampe2b073a02017-06-22 17:28:57 -07005194 profilerInfo.closeFd();
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005195 }
5196 } else {
Romain Guy7eabe552011-07-21 14:56:34 -07005197 switch (profileType) {
Romain Guy7eabe552011-07-21 14:56:34 -07005198 default:
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005199 mProfiler.stopProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07005200 break;
Romain Guy7eabe552011-07-21 14:56:34 -07005201 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005202 }
5203 }
Bob Leee5408332009-09-04 18:31:17 -07005204
Andreas Gampe4c79fea2016-01-28 20:11:41 -08005205 /**
5206 * Public entrypoint to stop profiling. This is required to end profiling when the app crashes,
5207 * so that profiler data won't be lost.
5208 *
5209 * @hide
5210 */
5211 public void stopProfiling() {
Amith Yamasanib1684432017-01-26 14:57:20 -08005212 if (mProfiler != null) {
5213 mProfiler.stopProfiling();
5214 }
Andreas Gampe4c79fea2016-01-28 20:11:41 -08005215 }
5216
Christopher Ferris8d652f82017-04-11 16:29:18 -07005217 static void handleDumpHeap(DumpHeapData dhd) {
Makoto Onuki4556b7b2017-07-07 14:58:58 -07005218 if (dhd.runGc) {
5219 System.gc();
5220 System.runFinalization();
5221 System.gc();
5222 }
Christopher Ferris8d652f82017-04-11 16:29:18 -07005223 if (dhd.managed) {
Andy McFadden824c5102010-07-09 16:26:57 -07005224 try {
5225 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
5226 } catch (IOException e) {
5227 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
5228 + " -- can the process access this path?");
5229 } finally {
5230 try {
5231 dhd.fd.close();
5232 } catch (IOException e) {
5233 Slog.w(TAG, "Failure closing profile fd", e);
5234 }
5235 }
Christopher Ferris8d652f82017-04-11 16:29:18 -07005236 } else if (dhd.mallocInfo) {
5237 Debug.dumpNativeMallocInfo(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07005238 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07005239 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07005240 }
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005241 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005242 ActivityManager.getService().dumpHeapFinished(dhd.path);
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005243 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005244 throw e.rethrowFromSystemServer();
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005245 }
Andy McFadden824c5102010-07-09 16:26:57 -07005246 }
5247
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005248 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005249 boolean hasPkgInfo = false;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005250 switch (cmd) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005251 case ApplicationThreadConstants.PACKAGE_REMOVED:
5252 case ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL:
Todd Kennedy39bfee52016-02-24 10:28:21 -08005253 {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005254 final boolean killApp = cmd == ApplicationThreadConstants.PACKAGE_REMOVED;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005255 if (packages == null) {
5256 break;
5257 }
5258 synchronized (mResourcesManager) {
5259 for (int i = packages.length - 1; i >= 0; i--) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005260 if (!hasPkgInfo) {
Todd Kennedy39bfee52016-02-24 10:28:21 -08005261 WeakReference<LoadedApk> ref = mPackages.get(packages[i]);
5262 if (ref != null && ref.get() != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005263 hasPkgInfo = true;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005264 } else {
5265 ref = mResourcePackages.get(packages[i]);
5266 if (ref != null && ref.get() != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005267 hasPkgInfo = true;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005268 }
5269 }
5270 }
5271 if (killApp) {
5272 mPackages.remove(packages[i]);
5273 mResourcePackages.remove(packages[i]);
5274 }
5275 }
5276 }
5277 break;
5278 }
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005279 case ApplicationThreadConstants.PACKAGE_REPLACED:
Todd Kennedy39bfee52016-02-24 10:28:21 -08005280 {
5281 if (packages == null) {
5282 break;
5283 }
5284 synchronized (mResourcesManager) {
5285 for (int i = packages.length - 1; i >= 0; i--) {
5286 WeakReference<LoadedApk> ref = mPackages.get(packages[i]);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005287 LoadedApk pkgInfo = ref != null ? ref.get() : null;
5288 if (pkgInfo != null) {
5289 hasPkgInfo = true;
mark_chen89764e32014-12-12 15:38:48 +08005290 } else {
5291 ref = mResourcePackages.get(packages[i]);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005292 pkgInfo = ref != null ? ref.get() : null;
5293 if (pkgInfo != null) {
5294 hasPkgInfo = true;
mark_chen89764e32014-12-12 15:38:48 +08005295 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005296 }
Todd Kennedy39bfee52016-02-24 10:28:21 -08005297 // If the package is being replaced, yet it still has a valid
5298 // LoadedApk object, the package was updated with _DONT_KILL.
5299 // Adjust it's internal references to the application info and
5300 // resources.
Todd Kennedy233a0b12018-01-29 20:30:24 +00005301 if (pkgInfo != null) {
Todd Kennedy39bfee52016-02-24 10:28:21 -08005302 try {
5303 final String packageName = packages[i];
5304 final ApplicationInfo aInfo =
5305 sPackageManager.getApplicationInfo(
5306 packageName,
Svet Ganov6ce92392017-09-27 16:04:10 -07005307 PackageManager.GET_SHARED_LIBRARY_FILES,
Todd Kennedy39bfee52016-02-24 10:28:21 -08005308 UserHandle.myUserId());
5309
5310 if (mActivities.size() > 0) {
5311 for (ActivityClientRecord ar : mActivities.values()) {
5312 if (ar.activityInfo.applicationInfo.packageName
5313 .equals(packageName)) {
5314 ar.activityInfo.applicationInfo = aInfo;
Todd Kennedy233a0b12018-01-29 20:30:24 +00005315 ar.packageInfo = pkgInfo;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005316 }
5317 }
5318 }
5319 final List<String> oldPaths =
5320 sPackageManager.getPreviousCodePaths(packageName);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005321 pkgInfo.updateApplicationInfo(aInfo, oldPaths);
Todd Kennedy39bfee52016-02-24 10:28:21 -08005322 } catch (RemoteException e) {
5323 }
5324 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005325 }
5326 }
Todd Kennedy39bfee52016-02-24 10:28:21 -08005327 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005328 }
5329 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00005330 ApplicationPackageManager.handlePackageBroadcast(cmd, packages, hasPkgInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005331 }
Tim Murraye1e6c662015-04-07 13:24:14 -07005332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005333 final void handleLowMemory() {
Dianne Hackborn73c14162012-09-19 15:45:06 -07005334 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(true, null);
Bob Leee5408332009-09-04 18:31:17 -07005335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005336 final int N = callbacks.size();
5337 for (int i=0; i<N; i++) {
5338 callbacks.get(i).onLowMemory();
5339 }
5340
Chris Tatece229052009-03-25 16:44:52 -07005341 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
5342 if (Process.myUid() != Process.SYSTEM_UID) {
5343 int sqliteReleased = SQLiteDatabase.releaseMemory();
5344 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
5345 }
Bob Leee5408332009-09-04 18:31:17 -07005346
Mike Reedcaf0df12009-04-27 14:32:05 -04005347 // Ask graphics to free up as much as possible (font/image caches)
5348 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005349
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005350 // Ask text layout engine to free also as much as possible
5351 Canvas.freeTextLayoutCaches();
5352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005353 BinderInternal.forceGc("mem");
5354 }
5355
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005356 final void handleTrimMemory(int level) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07005357 if (DEBUG_MEMORY_TRIM) Slog.v(TAG, "Trimming memory to level: " + level);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005358
Dianne Hackborn73c14162012-09-19 15:45:06 -07005359 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(true, null);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005360
5361 final int N = callbacks.size();
Romain Guya998dff2012-03-23 18:58:36 -07005362 for (int i = 0; i < N; i++) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005363 callbacks.get(i).onTrimMemory(level);
5364 }
Romain Guy19f86e82012-04-23 15:19:07 -07005365
John Reckf47a5942014-06-30 16:20:04 -07005366 WindowManagerGlobal.getInstance().trimMemory(level);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005367 }
5368
Jesse Hall317fa5a2017-05-23 15:46:55 -07005369 private void setupGraphicsSupport(Context context) {
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005370 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setupGraphicsSupport");
Romain Guya9582652011-11-10 14:20:10 -08005371
Jesse Hall317fa5a2017-05-23 15:46:55 -07005372 // The system package doesn't have real data directories, so don't set up cache paths.
5373 if (!"android".equals(context.getPackageName())) {
5374 // This cache location probably points at credential-encrypted
5375 // storage which may not be accessible yet; assign it anyway instead
5376 // of pointing at device-encrypted storage.
5377 final File cacheDir = context.getCacheDir();
5378 if (cacheDir != null) {
5379 // Provide a usable directory for temporary files
5380 System.setProperty("java.io.tmpdir", cacheDir.getAbsolutePath());
5381 } else {
5382 Log.v(TAG, "Unable to initialize \"java.io.tmpdir\" property "
5383 + "due to missing cache directory");
Romain Guya9582652011-11-10 14:20:10 -08005384 }
Jesse Hall317fa5a2017-05-23 15:46:55 -07005385
5386 // Setup a location to store generated/compiled graphics code.
5387 final Context deviceContext = context.createDeviceProtectedStorageContext();
5388 final File codeCacheDir = deviceContext.getCodeCacheDir();
5389 if (codeCacheDir != null) {
5390 try {
5391 int uid = Process.myUid();
5392 String[] packages = getPackageManager().getPackagesForUid(uid);
5393 if (packages != null) {
Romain Guycecbe072017-07-18 15:42:06 -07005394 ThreadedRenderer.setupDiskCache(codeCacheDir);
5395 RenderScriptCacheDir.setupDiskCache(codeCacheDir);
Jesse Hall317fa5a2017-05-23 15:46:55 -07005396 }
5397 } catch (RemoteException e) {
5398 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
5399 throw e.rethrowFromSystemServer();
5400 }
5401 } else {
5402 Log.w(TAG, "Unable to use shader/script cache: missing code-cache directory");
5403 }
Romain Guya9582652011-11-10 14:20:10 -08005404 }
Jesse Hall317fa5a2017-05-23 15:46:55 -07005405
Cody Northrop86cedcb2017-10-20 09:03:13 -06005406 GraphicsEnvironment.getInstance().setup(context);
Jesse Hall317fa5a2017-05-23 15:46:55 -07005407 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborndde331c2012-08-03 14:01:57 -07005408 }
5409
5410 private void updateDefaultDensity() {
Alan Viverette2ac46f12016-02-04 16:58:14 -05005411 final int densityDpi = mCurDefaultDisplayDpi;
5412 if (!mDensityCompatMode
5413 && densityDpi != Configuration.DENSITY_DPI_UNDEFINED
5414 && densityDpi != DisplayMetrics.DENSITY_DEVICE) {
5415 DisplayMetrics.DENSITY_DEVICE = densityDpi;
5416 Bitmap.setDefaultDensity(densityDpi);
Dianne Hackborndde331c2012-08-03 14:01:57 -07005417 }
5418 }
5419
Todd Kennedye713efc2016-05-10 13:45:40 -07005420 /**
5421 * Returns the correct library directory for the current ABI.
5422 * <p>
5423 * If we're dealing with a multi-arch application that has both 32 and 64 bit shared
5424 * libraries, we might need to choose the secondary depending on what the current
5425 * runtime's instruction set is.
5426 */
5427 private String getInstrumentationLibrary(ApplicationInfo appInfo, InstrumentationInfo insInfo) {
5428 if (appInfo.primaryCpuAbi != null && appInfo.secondaryCpuAbi != null) {
5429 // Get the instruction set supported by the secondary ABI. In the presence
5430 // of a native bridge this might be different than the one secondary ABI used.
5431 String secondaryIsa =
5432 VMRuntime.getInstructionSet(appInfo.secondaryCpuAbi);
5433 final String secondaryDexCodeIsa =
5434 SystemProperties.get("ro.dalvik.vm.isa." + secondaryIsa);
5435 secondaryIsa = secondaryDexCodeIsa.isEmpty() ? secondaryIsa : secondaryDexCodeIsa;
5436
5437 final String runtimeIsa = VMRuntime.getRuntime().vmInstructionSet();
5438 if (runtimeIsa.equals(secondaryIsa)) {
5439 return insInfo.secondaryNativeLibraryDir;
5440 }
5441 }
5442 return insInfo.nativeLibraryDir;
5443 }
5444
Adam Lesinskib61e4052016-05-19 18:23:05 -07005445 /**
5446 * The LocaleList set for the app's resources may have been shuffled so that the preferred
5447 * Locale is at position 0. We must find the index of this preferred Locale in the
5448 * original LocaleList.
5449 */
5450 private void updateLocaleListFromAppContext(Context context, LocaleList newLocaleList) {
5451 final Locale bestLocale = context.getResources().getConfiguration().getLocales().get(0);
5452 final int newLocaleListSize = newLocaleList.size();
5453 for (int i = 0; i < newLocaleListSize; i++) {
5454 if (bestLocale.equals(newLocaleList.get(i))) {
5455 LocaleList.setDefault(newLocaleList, i);
5456 return;
5457 }
5458 }
Adam Lesinski27d30162016-05-25 16:45:14 -07005459
5460 // The app may have overridden the LocaleList with its own Locale
5461 // (not present in the available list). Push the chosen Locale
5462 // to the front of the list.
5463 LocaleList.setDefault(new LocaleList(bestLocale, newLocaleList));
Adam Lesinskib61e4052016-05-19 18:23:05 -07005464 }
5465
Romain Guy65b345f2011-07-27 18:51:50 -07005466 private void handleBindApplication(AppBindData data) {
Calin Juravle8f5770d2016-04-12 14:12:04 +01005467 // Register the UI Thread as a sensitive thread to the runtime.
5468 VMRuntime.registerSensitiveThread();
Man Caocfa78b22015-06-11 20:14:34 -07005469 if (data.trackAllocation) {
5470 DdmVmInternal.enableRecentAllocations(true);
5471 }
5472
Dianne Hackbornd98885c2016-03-01 17:13:03 -08005473 // Note when this process has started.
5474 Process.setStartTimes(SystemClock.elapsedRealtime(), SystemClock.uptimeMillis());
5475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005476 mBoundApplication = data;
5477 mConfiguration = new Configuration(data.config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07005478 mCompatConfiguration = new Configuration(data.config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005480 mProfiler = new Profiler();
Andreas Gampeab8a63b2018-01-05 13:55:15 -08005481 String agent = null;
Jeff Hao1b012d32014-08-20 10:35:34 -07005482 if (data.initProfilerInfo != null) {
5483 mProfiler.profileFile = data.initProfilerInfo.profileFile;
5484 mProfiler.profileFd = data.initProfilerInfo.profileFd;
5485 mProfiler.samplingInterval = data.initProfilerInfo.samplingInterval;
5486 mProfiler.autoStopProfiler = data.initProfilerInfo.autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -08005487 mProfiler.streamingOutput = data.initProfilerInfo.streamingOutput;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08005488 if (data.initProfilerInfo.attachAgentDuringBind) {
5489 agent = data.initProfilerInfo.agent;
5490 }
Jeff Hao1b012d32014-08-20 10:35:34 -07005491 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005493 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08005494 Process.setArgV0(data.processName);
Siva Velusamyd693dfa2012-09-10 14:36:58 -07005495 android.ddm.DdmHandleAppName.setAppName(data.processName,
5496 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005497
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005498 if (mProfiler.profileFd != null) {
5499 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07005500 }
5501
Joe Onoratod630f102011-03-17 18:42:26 -07005502 // If the app is Honeycomb MR1 or earlier, switch its AsyncTask
5503 // implementation to use the pool executor. Normally, we use the
5504 // serialized executor as the default. This has to happen in the
5505 // main thread so the main looper is set right.
Dianne Hackborn81e92762011-10-09 16:00:21 -07005506 if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
Joe Onoratod630f102011-03-17 18:42:26 -07005507 AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
5508 }
5509
Dianne Hackborn7895bc22014-09-05 15:09:03 -07005510 Message.updateCheckRecycle(data.appInfo.targetSdkVersion);
5511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512 /*
5513 * Before spawning a new process, reset the time zone to be the system time zone.
5514 * This needs to be done because the system time zone could have changed after the
5515 * the spawning of this process. Without doing this this process would have the incorrect
5516 * system time zone.
5517 */
5518 TimeZone.setDefault(null);
5519
Adam Lesinskib61e4052016-05-19 18:23:05 -07005520 /*
5521 * Set the LocaleList. This may change once we create the App Context.
5522 */
5523 LocaleList.setDefault(data.config.getLocales());
5524
5525 synchronized (mResourcesManager) {
5526 /*
5527 * Update the system configuration since its preloaded and might not
5528 * reflect configuration changes. The configuration object passed
5529 * in AppBindData can be safely assumed to be up to date
5530 */
5531 mResourcesManager.applyConfigurationToResourcesLocked(data.config, data.compatInfo);
5532 mCurDefaultDisplayDpi = data.config.densityDpi;
5533
5534 // This calls mResourcesManager so keep it within the synchronized block.
5535 applyCompatConfiguration(mCurDefaultDisplayDpi);
5536 }
5537
Todd Kennedy233a0b12018-01-29 20:30:24 +00005538 data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539
Andreas Gampeab8a63b2018-01-05 13:55:15 -08005540 if (agent != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005541 handleAttachAgent(agent, data.info);
Andreas Gampeab8a63b2018-01-05 13:55:15 -08005542 }
5543
Dianne Hackborndde331c2012-08-03 14:01:57 -07005544 /**
5545 * Switch this process to density compatibility mode if needed.
5546 */
5547 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
5548 == 0) {
5549 mDensityCompatMode = true;
5550 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
5551 }
5552 updateDefaultDensity();
5553
Neil Fullerc66ec402016-11-14 16:06:42 +00005554 final String use24HourSetting = mCoreSettings.getString(Settings.System.TIME_12_24);
5555 Boolean is24Hr = null;
5556 if (use24HourSetting != null) {
5557 is24Hr = "24".equals(use24HourSetting) ? Boolean.TRUE : Boolean.FALSE;
5558 }
5559 // null : use locale default for 12/24 hour formatting,
5560 // false : use 12 hour format,
5561 // true : use 24 hour format.
Narayan Kamathccb2a0862013-12-19 14:49:36 +00005562 DateFormat.set24HourTimePref(is24Hr);
5563
Jon Miranda836c0a82014-08-11 12:32:26 -07005564 View.mDebugViewAttributes =
5565 mCoreSettings.getInt(Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0;
5566
Jeff Sharkey89182982017-11-01 19:02:56 -06005567 StrictMode.initThreadDefaults(data.appInfo);
5568 StrictMode.initVmDefaults(data.appInfo);
Jeff Sharkey344744b2016-01-28 19:03:30 -07005569
Svet Ganov37e43272016-09-09 16:01:32 -07005570 // We deprecated Build.SERIAL and only apps that target pre NMR1
5571 // SDK can see it. Since access to the serial is now behind a
5572 // permission we push down the value and here we fix it up
5573 // before any app code has been loaded.
5574 try {
5575 Field field = Build.class.getDeclaredField("SERIAL");
5576 field.setAccessible(true);
5577 field.set(Build.class, data.buildSerial);
5578 } catch (NoSuchFieldException | IllegalAccessException e) {
5579 /* ignore */
5580 }
5581
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005582 if (data.debugMode != ApplicationThreadConstants.DEBUG_OFF) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005583 // XXX should have option to change the port.
5584 Debug.changeDebugPort(8100);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005585 if (data.debugMode == ApplicationThreadConstants.DEBUG_WAIT) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005586 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005587 + " is waiting for the debugger on port 8100...");
5588
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005589 IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005590 try {
5591 mgr.showWaitingForDebugger(mAppThread, true);
5592 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005593 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005594 }
5595
5596 Debug.waitForDebugger();
5597
5598 try {
5599 mgr.showWaitingForDebugger(mAppThread, false);
5600 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005601 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 }
5603
5604 } else {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005605 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005606 + " can be debugged on port 8100...");
5607 }
5608 }
5609
Jamie Gennisf9c7d6b2013-03-25 14:18:25 -07005610 // Allow application-generated systrace messages if we're debuggable.
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04005611 boolean isAppDebuggable = (data.appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
5612 Trace.setAppTracingAllowed(isAppDebuggable);
5613 if (isAppDebuggable && data.enableBinderTracking) {
5614 Binder.enableTracing();
5615 }
Jamie Gennisf9c7d6b2013-03-25 14:18:25 -07005616
Robert Greenwalt434203a2010-10-11 16:00:27 -07005617 /**
5618 * Initialize the default http proxy in this process for the reasons we set the time zone.
5619 */
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005620 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Setup proxies");
Alan Viverettebe64eae2015-09-03 14:56:04 -04005621 final IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08005622 if (b != null) {
5623 // In pre-boot mode (doing initial launch to collect password), not
5624 // all system is up. This includes the connectivity service, so don't
5625 // crash if we can't get it.
Alan Viverettebe64eae2015-09-03 14:56:04 -04005626 final IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08005627 try {
Paul Jensencee9b512015-05-06 07:32:40 -04005628 final ProxyInfo proxyInfo = service.getProxyForNetwork(null);
Jason Monk207900c2014-04-25 15:00:09 -04005629 Proxy.setHttpProxySystemProperty(proxyInfo);
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005630 } catch (RemoteException e) {
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005631 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005632 throw e.rethrowFromSystemServer();
5633 }
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08005634 }
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005635 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Robert Greenwalt434203a2010-10-11 16:00:27 -07005636
Alan Viverette2107d692015-09-03 14:55:27 -04005637 // Instrumentation info affects the class loader, so load it before
5638 // setting up the app context.
5639 final InstrumentationInfo ii;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005640 if (data.instrumentationName != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005641 try {
Alan Viverette2107d692015-09-03 14:55:27 -04005642 ii = new ApplicationPackageManager(null, getPackageManager())
5643 .getInstrumentationInfo(data.instrumentationName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005644 } catch (PackageManager.NameNotFoundException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005645 throw new RuntimeException(
Alan Viverette2107d692015-09-03 14:55:27 -04005646 "Unable to find instrumentation info for: " + data.instrumentationName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005647 }
5648
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07005649 mInstrumentationPackageName = ii.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005650 mInstrumentationAppDir = ii.sourceDir;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07005651 mInstrumentationSplitAppDirs = ii.splitSourceDirs;
Todd Kennedye713efc2016-05-10 13:45:40 -07005652 mInstrumentationLibDir = getInstrumentationLibrary(data.appInfo, ii);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005653 mInstrumentedAppDir = data.info.getAppDir();
5654 mInstrumentedSplitAppDirs = data.info.getSplitAppDirs();
5655 mInstrumentedLibDir = data.info.getLibDir();
Alan Viverette2107d692015-09-03 14:55:27 -04005656 } else {
5657 ii = null;
5658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005659
Todd Kennedy233a0b12018-01-29 20:30:24 +00005660 final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
Adam Lesinskib61e4052016-05-19 18:23:05 -07005661 updateLocaleListFromAppContext(appContext,
5662 mResourcesManager.getConfiguration().getLocales());
Seigo Nonakac14dd782016-03-30 23:09:16 +09005663
Jesse Hall317fa5a2017-05-23 15:46:55 -07005664 if (!Process.isIsolated()) {
Jeff Sharkey89182982017-11-01 19:02:56 -06005665 final int oldMask = StrictMode.allowThreadDiskWritesMask();
5666 try {
5667 setupGraphicsSupport(appContext);
5668 } finally {
5669 StrictMode.setThreadPolicyMask(oldMask);
5670 }
Michael Lentine2ba303f2016-02-01 20:44:34 -06005671 }
Michael Lentine03d8f7682016-01-31 15:37:11 -06005672
Calin Juravle37dfc8e2017-03-13 19:02:32 -07005673 // If we use profiles, setup the dex reporter to notify package manager
5674 // of any relevant dex loads. The idle maintenance job will use the information
5675 // reported to optimize the loaded dex files.
5676 // Note that we only need one global reporter per app.
5677 // Make sure we do this before calling onCreate so that we can capture the
5678 // complete application startup.
5679 if (SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false)) {
Calin Juravlef5a7bfc2017-03-13 23:30:30 -07005680 BaseDexClassLoader.setReporter(DexLoadReporter.getInstance());
Calin Juravle37dfc8e2017-03-13 19:02:32 -07005681 }
5682
Chad Brubaker78d47122015-11-17 22:26:58 -08005683 // Install the Network Security Config Provider. This must happen before the application
5684 // code is loaded to prevent issues with instances of TLS objects being created before
5685 // the provider is installed.
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005686 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "NetworkSecurityConfigProvider.install");
Chad Brubaker276ee962016-06-08 12:57:46 -07005687 NetworkSecurityConfigProvider.install(appContext);
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005688 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Chad Brubaker78d47122015-11-17 22:26:58 -08005689
Alan Viverette2107d692015-09-03 14:55:27 -04005690 // Continue loading instrumentation.
5691 if (ii != null) {
Dianne Hackbornf4ef6eb2017-12-07 13:57:21 -08005692 ApplicationInfo instrApp;
5693 try {
5694 instrApp = getPackageManager().getApplicationInfo(ii.packageName, 0,
5695 UserHandle.myUserId());
5696 } catch (RemoteException e) {
5697 instrApp = null;
5698 }
5699 if (instrApp == null) {
5700 instrApp = new ApplicationInfo();
5701 }
Jeff Sharkey15447792015-11-05 16:18:51 -08005702 ii.copyTo(instrApp);
Fyodor Kupolovaf38b8e2015-12-02 16:16:07 -08005703 instrApp.initForUser(UserHandle.myUserId());
Todd Kennedy233a0b12018-01-29 20:30:24 +00005704 final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07005705 appContext.getClassLoader(), false, true, false);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005706 final ContextImpl instrContext = ContextImpl.createAppContext(this, pi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005707
5708 try {
Alan Viverettebe64eae2015-09-03 14:56:04 -04005709 final ClassLoader cl = instrContext.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04005710 mInstrumentation = (Instrumentation)
5711 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005712 } catch (Exception e) {
5713 throw new RuntimeException(
5714 "Unable to instantiate instrumentation "
5715 + data.instrumentationName + ": " + e.toString(), e);
5716 }
5717
Alan Viverettebe64eae2015-09-03 14:56:04 -04005718 final ComponentName component = new ComponentName(ii.packageName, ii.name);
5719 mInstrumentation.init(this, instrContext, appContext, component,
5720 data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005722 if (mProfiler.profileFile != null && !ii.handleProfiling
5723 && mProfiler.profileFd == null) {
5724 mProfiler.handlingProfiling = true;
Alan Viverettebe64eae2015-09-03 14:56:04 -04005725 final File file = new File(mProfiler.profileFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 file.getParentFile().mkdirs();
5727 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
5728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005729 } else {
5730 mInstrumentation = new Instrumentation();
Jason Monka80bfb52017-11-16 17:15:37 -05005731 mInstrumentation.basicInit(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005732 }
5733
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08005734 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
Dianne Hackbornde398512011-01-18 18:45:21 -08005735 dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
Mathieu Chartier24cee072015-01-08 14:42:20 -08005736 } else {
5737 // Small heap, clamp to the current growth limit and let the heap release
5738 // pages after the growth limit to the non growth limit capacity. b/18387825
5739 dalvik.system.VMRuntime.getRuntime().clampGrowthLimit();
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08005740 }
5741
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005742 // Allow disk access during application and provider setup. This could
Jeff Sharkey7c501672012-02-28 12:08:37 -08005743 // block processing ordered broadcasts, but later processing would
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005744 // probably end up doing the same disk access.
Kurt Nelson5e154362017-06-29 17:20:56 -07005745 Application app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08005746 final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
Kurt Nelson571c3f62017-07-10 11:09:04 -07005747 final StrictMode.ThreadPolicy writesAllowedPolicy = StrictMode.getThreadPolicy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748 try {
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005749 // If the app is being launched for full backup or restore, bring it up in
5750 // a restricted environment with the base application class.
Todd Kennedy233a0b12018-01-29 20:30:24 +00005751 app = data.info.makeApplication(data.restrictedBackupMode, null);
Svetoslav Ganov24c90452017-12-27 15:17:14 -08005752
5753 // Propagate autofill compat state
5754 app.setAutofillCompatibilityEnabled(data.autofillCompatibilityEnabled);
5755
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005756 mInitialApplication = app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08005757
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005758 // don't bring up providers in restricted mode; they may depend on the
5759 // app's custom Application class
5760 if (!data.restrictedBackupMode) {
Jeff Sharkey3e195892016-03-05 19:48:59 -07005761 if (!ArrayUtils.isEmpty(data.providers)) {
5762 installContentProviders(app, data.providers);
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005763 // For process that contains content providers, we want to
5764 // ensure that the JIT is enabled "at some point".
5765 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
5766 }
5767 }
5768
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005769 // Do this after providers, since instrumentation tests generally start their
5770 // test thread at this point, and we don't want that racing.
5771 try {
5772 mInstrumentation.onCreate(data.instrumentationArgs);
5773 }
5774 catch (Exception e) {
5775 throw new RuntimeException(
5776 "Exception thrown in onCreate() of "
5777 + data.instrumentationName + ": " + e.toString(), e);
5778 }
Kurt Nelson571c3f62017-07-10 11:09:04 -07005779 try {
5780 mInstrumentation.callApplicationOnCreate(app);
5781 } catch (Exception e) {
5782 if (!mInstrumentation.onException(app, e)) {
5783 throw new RuntimeException(
5784 "Unable to create application " + app.getClass().getName()
5785 + ": " + e.toString(), e);
5786 }
5787 }
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005788 } finally {
Kurt Nelson571c3f62017-07-10 11:09:04 -07005789 // If the app targets < O-MR1, or doesn't change the thread policy
5790 // during startup, clobber the policy to maintain behavior of b/36951662
5791 if (data.appInfo.targetSdkVersion <= Build.VERSION_CODES.O
5792 || StrictMode.getThreadPolicy().equals(writesAllowedPolicy)) {
5793 StrictMode.setThreadPolicy(savedPolicy);
Kurt Nelson5e154362017-06-29 17:20:56 -07005794 }
5795 }
5796
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00005797 // Preload fonts resources
Seigo Nonaka54084b62017-04-24 14:46:23 -07005798 FontsContract.setApplicationContextForResources(appContext);
Torne (Richard Coles)85ecae52018-01-30 18:13:00 -05005799 if (!Process.isIsolated()) {
5800 try {
5801 final ApplicationInfo info =
5802 getPackageManager().getApplicationInfo(
5803 data.appInfo.packageName,
5804 PackageManager.GET_META_DATA /*flags*/,
5805 UserHandle.myUserId());
5806 if (info.metaData != null) {
5807 final int preloadedFontsResource = info.metaData.getInt(
5808 ApplicationInfo.METADATA_PRELOADED_FONTS, 0);
5809 if (preloadedFontsResource != 0) {
5810 data.info.getResources().preloadFonts(preloadedFontsResource);
5811 }
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00005812 }
Torne (Richard Coles)85ecae52018-01-30 18:13:00 -05005813 } catch (RemoteException e) {
5814 throw e.rethrowFromSystemServer();
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00005815 }
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00005816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005817 }
5818
5819 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005820 IActivityManager am = ActivityManager.getService();
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005821 if (mProfiler.profileFile != null && mProfiler.handlingProfiling
5822 && mProfiler.profileFd == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005823 Debug.stopMethodTracing();
5824 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005825 //Slog.i(TAG, "am: " + ActivityManager.getService()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005826 // + ", app thr: " + mAppThread);
5827 try {
5828 am.finishInstrumentation(mAppThread, resultCode, results);
5829 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005830 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005831 }
5832 }
5833
Romain Guy65b345f2011-07-27 18:51:50 -07005834 private void installContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005835 Context context, List<ProviderInfo> providers) {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07005836 final ArrayList<ContentProviderHolder> results = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005837
Romain Guya998dff2012-03-23 18:58:36 -07005838 for (ProviderInfo cpi : providers) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08005839 if (DEBUG_PROVIDER) {
5840 StringBuilder buf = new StringBuilder(128);
5841 buf.append("Pub ");
5842 buf.append(cpi.authority);
5843 buf.append(": ");
5844 buf.append(cpi.name);
5845 Log.i(TAG, buf.toString());
5846 }
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07005847 ContentProviderHolder cph = installProvider(context, null, cpi,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005848 false /*noisy*/, true /*noReleaseNeeded*/, true /*stable*/);
5849 if (cph != null) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005850 cph.noReleaseNeeded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005851 results.add(cph);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005852 }
5853 }
5854
5855 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005856 ActivityManager.getService().publishContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005857 getApplicationThread(), results);
5858 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005859 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005860 }
5861 }
5862
Jeff Sharkey6d515712012-09-20 16:06:08 -07005863 public final IContentProvider acquireProvider(
5864 Context c, String auth, int userId, boolean stable) {
Wale Ogunwale1d646122015-04-24 14:45:14 -07005865 final IContentProvider provider = acquireExistingProvider(c, auth, userId, stable);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005866 if (provider != null) {
5867 return provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005868 }
5869
Wale Ogunwale1d646122015-04-24 14:45:14 -07005870 // There is a possible race here. Another thread may try to acquire
5871 // the same provider at the same time. When this happens, we want to ensure
5872 // that the first one wins.
5873 // Note that we cannot hold the lock while acquiring and installing the
5874 // provider since it might take a long time to run and it could also potentially
5875 // be re-entrant in the case where the provider is in the same process.
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07005876 ContentProviderHolder holder = null;
Wale Ogunwale1d646122015-04-24 14:45:14 -07005877 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005878 holder = ActivityManager.getService().getContentProvider(
Wale Ogunwale1d646122015-04-24 14:45:14 -07005879 getApplicationThread(), auth, userId, stable);
5880 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005881 throw ex.rethrowFromSystemServer();
Wale Ogunwale67fe0a42015-04-24 14:44:54 -07005882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005883 if (holder == null) {
Jeff Sharkey6d515712012-09-20 16:06:08 -07005884 Slog.e(TAG, "Failed to find provider info for " + auth);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005885 return null;
5886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005887
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005888 // Install provider will increment the reference count for us, and break
5889 // any ties in the race.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005890 holder = installProvider(c, holder, holder.info,
5891 true /*noisy*/, holder.noReleaseNeeded, stable);
5892 return holder.provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005893 }
5894
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005895 private final void incProviderRefLocked(ProviderRefCount prc, boolean stable) {
5896 if (stable) {
5897 prc.stableCount += 1;
5898 if (prc.stableCount == 1) {
5899 // We are acquiring a new stable reference on the provider.
5900 int unstableDelta;
5901 if (prc.removePending) {
5902 // We have a pending remove operation, which is holding the
5903 // last unstable reference. At this point we are converting
5904 // that unstable reference to our new stable reference.
5905 unstableDelta = -1;
5906 // Cancel the removal of the provider.
5907 if (DEBUG_PROVIDER) {
5908 Slog.v(TAG, "incProviderRef: stable "
5909 + "snatched provider from the jaws of death");
5910 }
5911 prc.removePending = false;
Guobin Zhang9e3e52662013-03-21 13:57:11 +08005912 // There is a race! It fails to remove the message, which
5913 // will be handled in completeRemoveProvider().
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005914 mH.removeMessages(H.REMOVE_PROVIDER, prc);
5915 } else {
5916 unstableDelta = 0;
5917 }
5918 try {
5919 if (DEBUG_PROVIDER) {
5920 Slog.v(TAG, "incProviderRef Now stable - "
5921 + prc.holder.info.name + ": unstableDelta="
5922 + unstableDelta);
5923 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005924 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005925 prc.holder.connection, 1, unstableDelta);
5926 } catch (RemoteException e) {
5927 //do nothing content provider object is dead any way
5928 }
5929 }
5930 } else {
5931 prc.unstableCount += 1;
5932 if (prc.unstableCount == 1) {
5933 // We are acquiring a new unstable reference on the provider.
5934 if (prc.removePending) {
5935 // Oh look, we actually have a remove pending for the
5936 // provider, which is still holding the last unstable
5937 // reference. We just need to cancel that to take new
5938 // ownership of the reference.
5939 if (DEBUG_PROVIDER) {
5940 Slog.v(TAG, "incProviderRef: unstable "
5941 + "snatched provider from the jaws of death");
5942 }
5943 prc.removePending = false;
5944 mH.removeMessages(H.REMOVE_PROVIDER, prc);
5945 } else {
5946 // First unstable ref, increment our count in the
5947 // activity manager.
5948 try {
5949 if (DEBUG_PROVIDER) {
5950 Slog.v(TAG, "incProviderRef: Now unstable - "
5951 + prc.holder.info.name);
5952 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005953 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005954 prc.holder.connection, 0, 1);
5955 } catch (RemoteException e) {
5956 //do nothing content provider object is dead any way
5957 }
5958 }
5959 }
5960 }
5961 }
5962
Jeff Sharkey6d515712012-09-20 16:06:08 -07005963 public final IContentProvider acquireExistingProvider(
5964 Context c, String auth, int userId, boolean stable) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005965 synchronized (mProviderMap) {
Wale Ogunwale1d646122015-04-24 14:45:14 -07005966 final ProviderKey key = new ProviderKey(auth, userId);
Jeff Sharkey6d515712012-09-20 16:06:08 -07005967 final ProviderClientRecord pr = mProviderMap.get(key);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005968 if (pr == null) {
5969 return null;
5970 }
5971
5972 IContentProvider provider = pr.mProvider;
5973 IBinder jBinder = provider.asBinder();
Dianne Hackbornc428aae2012-10-03 16:38:22 -07005974 if (!jBinder.isBinderAlive()) {
5975 // The hosting process of the provider has died; we can't
5976 // use this one.
Wale Ogunwale1d646122015-04-24 14:45:14 -07005977 Log.i(TAG, "Acquiring provider " + auth + " for user " + userId
Dianne Hackbornc428aae2012-10-03 16:38:22 -07005978 + ": existing object's process dead");
5979 handleUnstableProviderDiedLocked(jBinder, true);
5980 return null;
5981 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005982
5983 // Only increment the ref count if we have one. If we don't then the
5984 // provider is not reference counted and never needs to be released.
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07005985 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005986 if (prc != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005987 incProviderRefLocked(prc, stable);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005988 }
5989 return provider;
5990 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07005991 }
5992
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005993 public final boolean releaseProvider(IContentProvider provider, boolean stable) {
5994 if (provider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005995 return false;
5996 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005998 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005999 synchronized (mProviderMap) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006000 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006001 if (prc == null) {
6002 // The provider has no ref count, no release is needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006003 return false;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006004 }
6005
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006006 boolean lastRef = false;
6007 if (stable) {
6008 if (prc.stableCount == 0) {
6009 if (DEBUG_PROVIDER) Slog.v(TAG,
6010 "releaseProvider: stable ref count already 0, how?");
6011 return false;
6012 }
6013 prc.stableCount -= 1;
6014 if (prc.stableCount == 0) {
6015 // What we do at this point depends on whether there are
6016 // any unstable refs left: if there are, we just tell the
6017 // activity manager to decrement its stable count; if there
6018 // aren't, we need to enqueue this provider to be removed,
6019 // and convert to holding a single unstable ref while
6020 // doing so.
6021 lastRef = prc.unstableCount == 0;
6022 try {
6023 if (DEBUG_PROVIDER) {
6024 Slog.v(TAG, "releaseProvider: No longer stable w/lastRef="
6025 + lastRef + " - " + prc.holder.info.name);
6026 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006027 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006028 prc.holder.connection, -1, lastRef ? 1 : 0);
6029 } catch (RemoteException e) {
6030 //do nothing content provider object is dead any way
6031 }
6032 }
6033 } else {
6034 if (prc.unstableCount == 0) {
6035 if (DEBUG_PROVIDER) Slog.v(TAG,
6036 "releaseProvider: unstable ref count already 0, how?");
6037 return false;
6038 }
6039 prc.unstableCount -= 1;
6040 if (prc.unstableCount == 0) {
6041 // If this is the last reference, we need to enqueue
6042 // this provider to be removed instead of telling the
6043 // activity manager to remove it at this point.
6044 lastRef = prc.stableCount == 0;
6045 if (!lastRef) {
6046 try {
6047 if (DEBUG_PROVIDER) {
6048 Slog.v(TAG, "releaseProvider: No longer unstable - "
6049 + prc.holder.info.name);
6050 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006051 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006052 prc.holder.connection, 0, -1);
6053 } catch (RemoteException e) {
6054 //do nothing content provider object is dead any way
6055 }
6056 }
6057 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006058 }
6059
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006060 if (lastRef) {
6061 if (!prc.removePending) {
6062 // Schedule the actual remove asynchronously, since we don't know the context
6063 // this will be called in.
6064 // TODO: it would be nice to post a delayed message, so
6065 // if we come back and need the same provider quickly
6066 // we will still have it available.
6067 if (DEBUG_PROVIDER) {
6068 Slog.v(TAG, "releaseProvider: Enqueueing pending removal - "
6069 + prc.holder.info.name);
6070 }
6071 prc.removePending = true;
6072 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, prc);
6073 mH.sendMessage(msg);
6074 } else {
6075 Slog.w(TAG, "Duplicate remove pending of provider " + prc.holder.info.name);
6076 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006077 }
6078 return true;
6079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006080 }
6081
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006082 final void completeRemoveProvider(ProviderRefCount prc) {
6083 synchronized (mProviderMap) {
6084 if (!prc.removePending) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006085 // There was a race! Some other client managed to acquire
6086 // the provider before the removal was completed.
6087 // Abort the removal. We will do it later.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006088 if (DEBUG_PROVIDER) Slog.v(TAG, "completeRemoveProvider: lost the race, "
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006089 + "provider still in use");
6090 return;
6091 }
6092
Guobin Zhang9e3e52662013-03-21 13:57:11 +08006093 // More complicated race!! Some client managed to acquire the
6094 // provider and release it before the removal was completed.
6095 // Continue the removal, and abort the next remove message.
6096 prc.removePending = false;
6097
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006098 final IBinder jBinder = prc.holder.provider.asBinder();
6099 ProviderRefCount existingPrc = mProviderRefCountMap.get(jBinder);
6100 if (existingPrc == prc) {
6101 mProviderRefCountMap.remove(jBinder);
6102 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006103
Dianne Hackbornadd005c2013-07-17 18:43:12 -07006104 for (int i=mProviderMap.size()-1; i>=0; i--) {
6105 ProviderClientRecord pr = mProviderMap.valueAt(i);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006106 IBinder myBinder = pr.mProvider.asBinder();
6107 if (myBinder == jBinder) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07006108 mProviderMap.removeAt(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006109 }
6110 }
6111 }
6112
6113 try {
6114 if (DEBUG_PROVIDER) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006115 Slog.v(TAG, "removeProvider: Invoking ActivityManagerService."
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006116 + "removeContentProvider(" + prc.holder.info.name + ")");
6117 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006118 ActivityManager.getService().removeContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006119 prc.holder.connection, false);
6120 } catch (RemoteException e) {
6121 //do nothing content provider object is dead any way
6122 }
6123 }
6124
6125 final void handleUnstableProviderDied(IBinder provider, boolean fromClient) {
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006126 synchronized (mProviderMap) {
6127 handleUnstableProviderDiedLocked(provider, fromClient);
6128 }
6129 }
6130
6131 final void handleUnstableProviderDiedLocked(IBinder provider, boolean fromClient) {
6132 ProviderRefCount prc = mProviderRefCountMap.get(provider);
6133 if (prc != null) {
6134 if (DEBUG_PROVIDER) Slog.v(TAG, "Cleaning up dead provider "
6135 + provider + " " + prc.holder.info.name);
6136 mProviderRefCountMap.remove(provider);
You Kimbc74de62013-10-01 00:13:26 +09006137 for (int i=mProviderMap.size()-1; i>=0; i--) {
6138 ProviderClientRecord pr = mProviderMap.valueAt(i);
6139 if (pr != null && pr.mProvider.asBinder() == provider) {
6140 Slog.i(TAG, "Removing dead content provider:" + pr.mProvider.toString());
6141 mProviderMap.removeAt(i);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006142 }
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006143 }
You Kimbc74de62013-10-01 00:13:26 +09006144
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006145 if (fromClient) {
6146 // We found out about this due to execution in our client
6147 // code. Tell the activity manager about it now, to ensure
6148 // that the next time we go to do anything with the provider
6149 // it knows it is dead (so we don't race with its death
6150 // notification).
6151 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006152 ActivityManager.getService().unstableProviderDied(
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006153 prc.holder.connection);
6154 } catch (RemoteException e) {
6155 //do nothing content provider object is dead any way
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006156 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07006157 }
6158 }
6159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006160
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006161 final void appNotRespondingViaProvider(IBinder provider) {
6162 synchronized (mProviderMap) {
6163 ProviderRefCount prc = mProviderRefCountMap.get(provider);
6164 if (prc != null) {
6165 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006166 ActivityManager.getService()
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006167 .appNotRespondingViaProvider(prc.holder.connection);
6168 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006169 throw e.rethrowFromSystemServer();
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006170 }
6171 }
6172 }
6173 }
6174
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006175 private ProviderClientRecord installProviderAuthoritiesLocked(IContentProvider provider,
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006176 ContentProvider localProvider, ContentProviderHolder holder) {
Andreas Gampe18e99c12015-03-06 15:29:06 -08006177 final String auths[] = holder.info.authority.split(";");
Jeff Sharkey6d515712012-09-20 16:06:08 -07006178 final int userId = UserHandle.getUserId(holder.info.applicationInfo.uid);
6179
Jeff Sharkey0a17db12016-11-04 11:23:46 -06006180 if (provider != null) {
6181 // If this provider is hosted by the core OS and cannot be upgraded,
6182 // then I guess we're okay doing blocking calls to it.
6183 for (String auth : auths) {
6184 switch (auth) {
6185 case ContactsContract.AUTHORITY:
6186 case CallLog.AUTHORITY:
6187 case CallLog.SHADOW_AUTHORITY:
6188 case BlockedNumberContract.AUTHORITY:
6189 case CalendarContract.AUTHORITY:
6190 case Downloads.Impl.AUTHORITY:
Jeff Sharkeycb621622016-11-11 14:04:32 -07006191 case "telephony":
Jeff Sharkey0a17db12016-11-04 11:23:46 -06006192 Binder.allowBlocking(provider.asBinder());
6193 }
6194 }
6195 }
6196
Jeff Sharkey6d515712012-09-20 16:06:08 -07006197 final ProviderClientRecord pcr = new ProviderClientRecord(
6198 auths, provider, localProvider, holder);
6199 for (String auth : auths) {
6200 final ProviderKey key = new ProviderKey(auth, userId);
6201 final ProviderClientRecord existing = mProviderMap.get(key);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006202 if (existing != null) {
6203 Slog.w(TAG, "Content provider " + pcr.mHolder.info.name
Jeff Sharkey6d515712012-09-20 16:06:08 -07006204 + " already published as " + auth);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006205 } else {
Jeff Sharkey6d515712012-09-20 16:06:08 -07006206 mProviderMap.put(key, pcr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006207 }
6208 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006209 return pcr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210 }
6211
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006212 /**
6213 * Installs the provider.
6214 *
6215 * Providers that are local to the process or that come from the system server
6216 * may be installed permanently which is indicated by setting noReleaseNeeded to true.
6217 * Other remote providers are reference counted. The initial reference count
6218 * for all reference counted providers is one. Providers that are not reference
6219 * counted do not have a reference count (at all).
6220 *
6221 * This method detects when a provider has already been installed. When this happens,
6222 * it increments the reference count of the existing provider (if appropriate)
6223 * and returns the existing provider. This can happen due to concurrent
6224 * attempts to acquire the same provider.
6225 */
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006226 private ContentProviderHolder installProvider(Context context,
6227 ContentProviderHolder holder, ProviderInfo info,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006228 boolean noisy, boolean noReleaseNeeded, boolean stable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006229 ContentProvider localProvider = null;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006230 IContentProvider provider;
Dianne Hackborn5f48fca2012-05-30 11:06:31 -07006231 if (holder == null || holder.provider == null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006232 if (DEBUG_PROVIDER || noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006233 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006234 + info.name);
6235 }
6236 Context c = null;
6237 ApplicationInfo ai = info.applicationInfo;
6238 if (context.getPackageName().equals(ai.packageName)) {
6239 c = context;
6240 } else if (mInitialApplication != null &&
6241 mInitialApplication.getPackageName().equals(ai.packageName)) {
6242 c = mInitialApplication;
6243 } else {
6244 try {
6245 c = context.createPackageContext(ai.packageName,
6246 Context.CONTEXT_INCLUDE_CODE);
6247 } catch (PackageManager.NameNotFoundException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07006248 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006249 }
6250 }
6251 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08006252 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006253 ai.packageName +
6254 " while loading content provider " +
6255 info.name);
6256 return null;
6257 }
Adam Lesinski4e862812016-11-21 16:02:24 -08006258
6259 if (info.splitName != null) {
6260 try {
6261 c = c.createContextForSplit(info.splitName);
6262 } catch (NameNotFoundException e) {
6263 throw new RuntimeException(e);
6264 }
6265 }
6266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006267 try {
6268 final java.lang.ClassLoader cl = c.getClassLoader();
Todd Kennedy233a0b12018-01-29 20:30:24 +00006269 LoadedApk packageInfo = peekPackageInfo(ai.packageName, true);
6270 if (packageInfo == null) {
Jason Monka80bfb52017-11-16 17:15:37 -05006271 // System startup case.
Todd Kennedy233a0b12018-01-29 20:30:24 +00006272 packageInfo = getSystemContext().mPackageInfo;
Jason Monka80bfb52017-11-16 17:15:37 -05006273 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00006274 localProvider = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05006275 .instantiateProvider(cl, info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006276 provider = localProvider.getIContentProvider();
6277 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08006278 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 info.name + " from sourceDir " +
6280 info.applicationInfo.sourceDir);
6281 return null;
6282 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006283 if (DEBUG_PROVIDER) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 TAG, "Instantiating local provider " + info.name);
6285 // XXX Need to create the correct context for this provider.
6286 localProvider.attachInfo(c, info);
6287 } catch (java.lang.Exception e) {
6288 if (!mInstrumentation.onException(null, e)) {
6289 throw new RuntimeException(
6290 "Unable to get provider " + info.name
6291 + ": " + e.toString(), e);
6292 }
6293 return null;
6294 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006295 } else {
6296 provider = holder.provider;
6297 if (DEBUG_PROVIDER) Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006298 + info.name);
6299 }
6300
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006301 ContentProviderHolder retHolder;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006302
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006303 synchronized (mProviderMap) {
6304 if (DEBUG_PROVIDER) Slog.v(TAG, "Checking to add " + provider
6305 + " / " + info.name);
6306 IBinder jBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006307 if (localProvider != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006308 ComponentName cname = new ComponentName(info.packageName, info.name);
6309 ProviderClientRecord pr = mLocalProvidersByName.get(cname);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006310 if (pr != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006311 if (DEBUG_PROVIDER) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006312 Slog.v(TAG, "installProvider: lost the race, "
6313 + "using existing local provider");
6314 }
6315 provider = pr.mProvider;
6316 } else {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006317 holder = new ContentProviderHolder(info);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006318 holder.provider = provider;
6319 holder.noReleaseNeeded = true;
6320 pr = installProviderAuthoritiesLocked(provider, localProvider, holder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006321 mLocalProviders.put(jBinder, pr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006322 mLocalProvidersByName.put(cname, pr);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006323 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006324 retHolder = pr.mHolder;
6325 } else {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006326 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
6327 if (prc != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006328 if (DEBUG_PROVIDER) {
6329 Slog.v(TAG, "installProvider: lost the race, updating ref count");
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006330 }
Wale Ogunwale1d646122015-04-24 14:45:14 -07006331 // We need to transfer our new reference to the existing
6332 // ref count, releasing the old one... but only if
6333 // release is needed (that is, it is not running in the
6334 // system process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006335 if (!noReleaseNeeded) {
6336 incProviderRefLocked(prc, stable);
Wale Ogunwale1d646122015-04-24 14:45:14 -07006337 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006338 ActivityManager.getService().removeContentProvider(
Wale Ogunwale1d646122015-04-24 14:45:14 -07006339 holder.connection, stable);
6340 } catch (RemoteException e) {
6341 //do nothing content provider object is dead any way
6342 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006343 }
6344 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006345 ProviderClientRecord client = installProviderAuthoritiesLocked(
6346 provider, localProvider, holder);
6347 if (noReleaseNeeded) {
6348 prc = new ProviderRefCount(holder, client, 1000, 1000);
6349 } else {
6350 prc = stable
6351 ? new ProviderRefCount(holder, client, 1, 0)
6352 : new ProviderRefCount(holder, client, 0, 1);
6353 }
6354 mProviderRefCountMap.put(jBinder, prc);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006355 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006356 retHolder = prc.holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006357 }
6358 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006359 return retHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006360 }
6361
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04006362 private void handleRunIsolatedEntryPoint(String entryPoint, String[] entryPointArgs) {
6363 try {
6364 Method main = Class.forName(entryPoint).getMethod("main", String[].class);
6365 main.invoke(null, new Object[]{entryPointArgs});
6366 } catch (ReflectiveOperationException e) {
6367 throw new AndroidRuntimeException("runIsolatedEntryPoint failed", e);
6368 }
6369 // The process will be empty after this method returns; exit the VM now.
6370 System.exit(0);
6371 }
6372
Sudheer Shankaf6690102017-10-16 10:20:32 -07006373 private void attach(boolean system, long startSeq) {
Jeff Sharkey66a017b2013-01-17 18:18:22 -08006374 sCurrentActivityThread = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006375 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006376 if (!system) {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07006377 ViewRootImpl.addFirstDrawHandler(new Runnable() {
Craig Mautner88c05892013-06-28 09:47:45 -07006378 @Override
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08006379 public void run() {
6380 ensureJitEnabled();
6381 }
6382 });
Siva Velusamyd693dfa2012-09-10 14:36:58 -07006383 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
6384 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006385 RuntimeInit.setApplicationObject(mAppThread.asBinder());
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006386 final IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006387 try {
Sudheer Shankaf6690102017-10-16 10:20:32 -07006388 mgr.attachApplication(mAppThread, startSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006389 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006390 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006392 // Watch for getting close to heap limit.
6393 BinderInternal.addGcWatcher(new Runnable() {
6394 @Override public void run() {
6395 if (!mSomeActivitiesChanged) {
6396 return;
6397 }
6398 Runtime runtime = Runtime.getRuntime();
6399 long dalvikMax = runtime.maxMemory();
6400 long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
6401 if (dalvikUsed > ((3*dalvikMax)/4)) {
6402 if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
6403 + " total=" + (runtime.totalMemory()/1024)
6404 + " used=" + (dalvikUsed/1024));
6405 mSomeActivitiesChanged = false;
6406 try {
6407 mgr.releaseSomeActivities(mAppThread);
6408 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006409 throw e.rethrowFromSystemServer();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006410 }
6411 }
6412 }
6413 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006414 } else {
6415 // Don't set application object here -- if the system crashes,
6416 // we can't display an alert, we just want to die die die.
Siva Velusamyd693dfa2012-09-10 14:36:58 -07006417 android.ddm.DdmHandleAppName.setAppName("system_process",
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006418 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006419 try {
6420 mInstrumentation = new Instrumentation();
Jason Monka80bfb52017-11-16 17:15:37 -05006421 mInstrumentation.basicInit(this);
Jeff Browndefd4a62014-03-10 21:24:37 -07006422 ContextImpl context = ContextImpl.createAppContext(
Todd Kennedy233a0b12018-01-29 20:30:24 +00006423 this, getSystemContext().mPackageInfo);
6424 mInitialApplication = context.mPackageInfo.makeApplication(true, null);
Jeff Brown7fc8e352014-09-16 18:06:47 -07006425 mInitialApplication.onCreate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006426 } catch (Exception e) {
6427 throw new RuntimeException(
6428 "Unable to instantiate Application():" + e.toString(), e);
6429 }
6430 }
Geremy Condrab7faaf42012-09-19 18:07:42 -07006431
6432 // add dropbox logging to libcore
6433 DropBox.setReporter(new DropBoxReporter());
6434
Andrii Kulian44607962017-03-16 11:06:24 -07006435 ViewRootImpl.ConfigChangedCallback configChangedCallback
6436 = (Configuration globalConfig) -> {
6437 synchronized (mResourcesManager) {
6438 // We need to apply this change to the resources immediately, because upon returning
6439 // the view hierarchy will be informed about it.
6440 if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,
6441 null /* compat */)) {
6442 updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
6443 mResourcesManager.getConfiguration().getLocales());
Adam Lesinskib61e4052016-05-19 18:23:05 -07006444
Andrii Kulian44607962017-03-16 11:06:24 -07006445 // This actually changed the resources! Tell everyone about it.
6446 if (mPendingConfiguration == null
6447 || mPendingConfiguration.isOtherSeqNewer(globalConfig)) {
6448 mPendingConfiguration = globalConfig;
6449 sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08006450 }
6451 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08006452 }
Andrii Kulian44607962017-03-16 11:06:24 -07006453 };
6454 ViewRootImpl.addConfigCallback(configChangedCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006455 }
6456
Romain Guy5e9120d2012-01-30 12:17:22 -08006457 public static ActivityThread systemMain() {
Alan Viverette5e1565e2014-07-29 16:14:25 -07006458 // The system process on low-memory devices do not get to use hardware
6459 // accelerated drawing, since this can add too much overhead to the
6460 // process.
6461 if (!ActivityManager.isHighEndGfx()) {
John Reck51aaf902015-12-02 15:08:07 -08006462 ThreadedRenderer.disable(true);
John Reck73840ea2014-09-22 07:39:18 -07006463 } else {
John Reck51aaf902015-12-02 15:08:07 -08006464 ThreadedRenderer.enableForegroundTrimming();
Alan Viverette5e1565e2014-07-29 16:14:25 -07006465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006466 ActivityThread thread = new ActivityThread();
Sudheer Shankaf6690102017-10-16 10:20:32 -07006467 thread.attach(true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006468 return thread;
6469 }
6470
Jeff Brown10e89712011-07-08 18:52:57 -07006471 public final void installSystemProviders(List<ProviderInfo> providers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006472 if (providers != null) {
Jeff Brown10e89712011-07-08 18:52:57 -07006473 installContentProviders(mInitialApplication, providers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006474 }
6475 }
6476
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006477 public int getIntCoreSetting(String key, int defaultValue) {
Craig Mautner88c05892013-06-28 09:47:45 -07006478 synchronized (mResourcesManager) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08006479 if (mCoreSettings != null) {
6480 return mCoreSettings.getInt(key, defaultValue);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006481 }
Craig Mautner88c05892013-06-28 09:47:45 -07006482 return defaultValue;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006483 }
6484 }
6485
Geremy Condra69689a72012-09-11 16:57:17 -07006486 private static class EventLoggingReporter implements EventLogger.Reporter {
6487 @Override
6488 public void report (int code, Object... list) {
6489 EventLog.writeEvent(code, list);
6490 }
6491 }
6492
Geremy Condrab7faaf42012-09-19 18:07:42 -07006493 private class DropBoxReporter implements DropBox.Reporter {
6494
6495 private DropBoxManager dropBox;
6496
Narayan Kamath7f062242015-04-08 13:24:13 +01006497 public DropBoxReporter() {}
Geremy Condrab7faaf42012-09-19 18:07:42 -07006498
6499 @Override
6500 public void addData(String tag, byte[] data, int flags) {
Narayan Kamath7f062242015-04-08 13:24:13 +01006501 ensureInitialized();
Geremy Condrab7faaf42012-09-19 18:07:42 -07006502 dropBox.addData(tag, data, flags);
6503 }
6504
6505 @Override
6506 public void addText(String tag, String data) {
Narayan Kamath7f062242015-04-08 13:24:13 +01006507 ensureInitialized();
Geremy Condrab7faaf42012-09-19 18:07:42 -07006508 dropBox.addText(tag, data);
6509 }
Narayan Kamath7f062242015-04-08 13:24:13 +01006510
6511 private synchronized void ensureInitialized() {
6512 if (dropBox == null) {
6513 dropBox = (DropBoxManager) getSystemContext().getSystemService(Context.DROPBOX_SERVICE);
6514 }
6515 }
Geremy Condrab7faaf42012-09-19 18:07:42 -07006516 }
6517
Romain Guy65b345f2011-07-27 18:51:50 -07006518 public static void main(String[] args) {
Narayan Kamathfbb32f62015-06-12 15:34:35 +01006519 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
Bob Leee5408332009-09-04 18:31:17 -07006520
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08006521 // CloseGuard defaults to true and can be quite spammy. We
6522 // disable it here, but selectively enable it later (via
6523 // StrictMode) on debug builds, but using DropBox, not logs.
6524 CloseGuard.setEnabled(false);
6525
Andreas Gamped281b422016-07-08 03:50:27 +00006526 Environment.initForCurrentUser();
Jeff Sharkeyb049e212012-09-07 23:16:01 -07006527
Geremy Condra69689a72012-09-11 16:57:17 -07006528 // Set the reporter for event logging in libcore
6529 EventLogger.setReporter(new EventLoggingReporter());
6530
Robin Lee3d076af2014-04-25 14:57:49 +01006531 // Make sure TrustedCertificateStore looks in the right place for CA certificates
6532 final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
6533 TrustedCertificateStore.setDefaultUserDirectory(configDir);
6534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006535 Process.setArgV0("<pre-initialized>");
6536
6537 Looper.prepareMainLooper();
6538
Sudheer Shankaf6690102017-10-16 10:20:32 -07006539 // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
6540 // It will be in the format "seq=114"
6541 long startSeq = 0;
6542 if (args != null) {
6543 for (int i = args.length - 1; i >= 0; --i) {
6544 if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
6545 startSeq = Long.parseLong(
6546 args[i].substring(PROC_START_SEQ_IDENT.length()));
6547 }
6548 }
6549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006550 ActivityThread thread = new ActivityThread();
Sudheer Shankaf6690102017-10-16 10:20:32 -07006551 thread.attach(false, startSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006552
Vairavan Srinivasan7335cfd2012-08-18 18:36:03 -07006553 if (sMainThreadHandler == null) {
6554 sMainThreadHandler = thread.getHandler();
6555 }
6556
Dianne Hackborn287952c2010-09-22 22:34:31 -07006557 if (false) {
6558 Looper.myLooper().setMessageLogging(new
6559 LogPrinter(Log.DEBUG, "ActivityThread"));
6560 }
6561
Narayan Kamathfbb32f62015-06-12 15:34:35 +01006562 // End of event ActivityThreadMain.
6563 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006564 Looper.loop();
6565
Jeff Brown10e89712011-07-08 18:52:57 -07006566 throw new RuntimeException("Main thread loop unexpectedly exited");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006567 }
Chris Craikfc294242016-12-13 18:10:46 -08006568
6569 // ------------------ Regular JNI ------------------------
6570
6571 private native void nDumpGraphicsInfo(FileDescriptor fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006572}