blob: 87b334992d2da2fa1bd914c17b72d3d8d9467fee [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 Kulian914aa7d2018-03-19 21:51:53 -070033import android.app.servertransaction.ActivityLifecycleItem;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080034import android.app.servertransaction.ActivityLifecycleItem.LifecycleState;
Andrii Kulian914aa7d2018-03-19 21:51:53 -070035import android.app.servertransaction.ActivityRelaunchItem;
Andrii Kulian446e8242017-10-26 15:17:29 -070036import android.app.servertransaction.ActivityResultItem;
37import android.app.servertransaction.ClientTransaction;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080038import android.app.servertransaction.PendingTransactionActions;
39import android.app.servertransaction.PendingTransactionActions.StopInfo;
40import android.app.servertransaction.TransactionExecutor;
Andrii Kulian914aa7d2018-03-19 21:51:53 -070041import android.app.servertransaction.TransactionExecutorHelper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.BroadcastReceiver;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070043import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.content.ComponentName;
45import android.content.ContentProvider;
46import android.content.Context;
47import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070048import android.content.IIntentReceiver;
Jesse Hall317fa5a2017-05-23 15:46:55 -070049import android.content.Intent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.content.pm.ActivityInfo;
51import android.content.pm.ApplicationInfo;
52import android.content.pm.IPackageManager;
53import android.content.pm.InstrumentationInfo;
Christopher Tate346acb12012-10-15 19:20:25 -070054import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.content.pm.PackageManager;
Sen Hubde75702010-05-28 01:54:03 -070056import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070057import android.content.pm.ParceledListSlice;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.content.pm.ProviderInfo;
59import android.content.pm.ServiceInfo;
60import android.content.res.AssetManager;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -070061import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.content.res.Configuration;
63import android.content.res.Resources;
Alan Viverettee54d2452015-05-06 10:41:43 -070064import android.content.res.Resources.Theme;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.database.sqlite.SQLiteDatabase;
66import android.database.sqlite.SQLiteDebug;
Vasu Noric3849202010-03-09 10:47:25 -080067import android.database.sqlite.SQLiteDebug.DbStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.graphics.Bitmap;
69import android.graphics.Canvas;
Leon Scroggins III8290eab2018-03-19 10:51:44 -040070import android.graphics.ImageDecoder;
Jeff Brownbd6e1502012-08-28 03:27:37 -070071import android.hardware.display.DisplayManagerGlobal;
Paul Jensene0bef712014-12-10 15:12:18 -050072import android.net.ConnectivityManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070073import android.net.IConnectivityManager;
Paul Jensene0bef712014-12-10 15:12:18 -050074import android.net.Network;
Robert Greenwalt434203a2010-10-11 16:00:27 -070075import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040076import android.net.ProxyInfo;
Jason Monk83520b92014-05-09 15:16:06 -040077import android.net.Uri;
Joe Onoratod630f102011-03-17 18:42:26 -070078import android.os.AsyncTask;
Amith Yamasani742a6712011-05-04 14:49:28 -070079import android.os.Binder;
Jeff Sharkey344744b2016-01-28 19:03:30 -070080import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.os.Bundle;
82import android.os.Debug;
Geremy Condrab7faaf42012-09-19 18:07:42 -070083import android.os.DropBoxManager;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070084import android.os.Environment;
Jesse Hallb12249b2016-12-12 12:53:02 -080085import android.os.GraphicsEnvironment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.os.Handler;
Jeff Sharkey8439ac02017-12-12 17:26:23 -070087import android.os.HandlerExecutor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.os.IBinder;
Adam Lesinskib61e4052016-05-19 18:23:05 -070089import android.os.LocaleList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.os.Looper;
91import android.os.Message;
92import android.os.MessageQueue;
Dianne Hackbornfabb70b2014-11-11 12:22:36 -080093import android.os.Parcel;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070094import android.os.ParcelFileDescriptor;
Craig Mautnera0026042014-04-23 11:45:37 -070095import android.os.PersistableBundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import android.os.Process;
97import android.os.RemoteException;
98import android.os.ServiceManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -070099import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import android.os.SystemClock;
Jeff Brownefd43bd2012-09-21 17:02:35 -0700101import android.os.SystemProperties;
Dianne Hackborn1ded0b12012-04-26 14:14:50 -0700102import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700103import android.os.UserHandle;
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600104import android.provider.BlockedNumberContract;
105import android.provider.CalendarContract;
106import android.provider.CallLog;
107import android.provider.ContactsContract;
108import android.provider.Downloads;
Seigo Nonaka54084b62017-04-24 14:46:23 -0700109import android.provider.FontsContract;
Narayan Kamathccb2a0862013-12-19 14:49:36 +0000110import android.provider.Settings;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700111import android.renderscript.RenderScriptCacheDir;
Chad Brubakerc72875b2016-04-27 16:35:11 -0700112import android.security.NetworkSecurityPolicy;
Chad Brubaker78d47122015-11-17 22:26:58 -0800113import android.security.net.config.NetworkSecurityConfigProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.util.AndroidRuntimeException;
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700115import android.util.ArrayMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116import android.util.DisplayMetrics;
117import android.util.EventLog;
118import android.util.Log;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700119import android.util.LogPrinter;
Andrii Kulianb372da62018-01-18 10:46:24 -0800120import android.util.MergedConfiguration;
Craig Mautnereb8abf72014-07-02 15:04:09 -0700121import android.util.Pair;
Jeff Brown6754ba22011-12-14 20:20:01 -0800122import android.util.PrintWriterPrinter;
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800123import android.util.Slog;
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -0700124import android.util.SparseIntArray;
Adam Powell14874662013-07-18 19:42:41 -0700125import android.util.SuperNotCalledException;
Kweku Adams598e9a22017-11-02 17:12:20 -0700126import android.util.proto.ProtoOutputStream;
Jorim Jaggib29e3182018-04-30 18:51:56 +0200127import android.view.Choreographer;
Adam Lesinski3ad1b482016-04-01 16:41:41 -0700128import android.view.ContextThemeWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129import android.view.Display;
John Reck51aaf902015-12-02 15:08:07 -0800130import android.view.ThreadedRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import android.view.View;
132import android.view.ViewDebug;
133import android.view.ViewManager;
Dianne Hackborn6dd005b2011-07-18 13:22:50 -0700134import android.view.ViewRootImpl;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135import android.view.Window;
136import android.view.WindowManager;
Jeff Brown98365d72012-08-19 20:30:52 -0700137import android.view.WindowManagerGlobal;
Richard Uhler2c036192016-09-14 09:48:31 +0100138import android.webkit.WebView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700140import com.android.internal.annotations.GuardedBy;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800141import com.android.internal.annotations.VisibleForTesting;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700142import com.android.internal.app.IVoiceInteractor;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800143import com.android.internal.content.ReferrerIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144import com.android.internal.os.BinderInternal;
145import com.android.internal.os.RuntimeInit;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700146import com.android.internal.os.SomeArgs;
Jeff Sharkey3e195892016-03-05 19:48:59 -0700147import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -0700148import com.android.internal.util.FastPrintWriter;
Jorim Jaggib29e3182018-04-30 18:51:56 +0200149import com.android.internal.util.function.pooled.PooledLambda;
Kenny Root12e75222013-04-23 22:34:24 -0700150import com.android.org.conscrypt.OpenSSLSocketImpl;
Robin Lee3d076af2014-04-25 14:57:49 +0100151import com.android.org.conscrypt.TrustedCertificateStore;
Yi Jin6c6e9ca2018-03-20 16:53:35 -0700152import com.android.server.am.MemInfoDumpProto;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700153
154import dalvik.system.BaseDexClassLoader;
155import dalvik.system.CloseGuard;
156import dalvik.system.VMDebug;
157import dalvik.system.VMRuntime;
158
Jesse Hall317fa5a2017-05-23 15:46:55 -0700159import libcore.io.DropBox;
160import libcore.io.EventLogger;
161import libcore.io.IoUtils;
162import libcore.net.event.NetworkEventDispatcher;
163
164import org.apache.harmony.dalvik.ddmc.DdmVmInternal;
165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166import java.io.File;
167import java.io.FileDescriptor;
168import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700169import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170import java.io.PrintWriter;
171import java.lang.ref.WeakReference;
Svet Ganov37e43272016-09-09 16:01:32 -0700172import java.lang.reflect.Field;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -0400173import java.lang.reflect.Method;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700174import java.net.InetAddress;
Narayan Kamathccb2a0862013-12-19 14:49:36 +0000175import java.text.DateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176import java.util.ArrayList;
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -0600177import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178import java.util.List;
Adam Lesinskib61e4052016-05-19 18:23:05 -0700179import java.util.Locale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180import java.util.Map;
Kenny Roote6585b32013-12-13 12:00:26 -0800181import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182import java.util.TimeZone;
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700183import java.util.concurrent.Executor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700185final class RemoteServiceException extends AndroidRuntimeException {
186 public RemoteServiceException(String msg) {
187 super(msg);
188 }
189}
190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191/**
192 * This manages the execution of the main thread in an
193 * application process, scheduling and executing activities,
194 * broadcasts, and other operations on it as the activity
195 * manager requests.
196 *
197 * {@hide}
198 */
Andrii Kulian446e8242017-10-26 15:17:29 -0700199public final class ActivityThread extends ClientTransactionHandler {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700200 /** @hide */
201 public static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700202 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
Joe Onorato43a17652011-04-06 19:22:23 -0700203 static final boolean localLOGV = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700204 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborne829fef2010-10-26 17:44:01 -0700205 /** @hide */
206 public static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700207 private static final boolean DEBUG_RESULTS = false;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700208 private static final boolean DEBUG_BACKUP = false;
Craig Mautner88c05892013-06-28 09:47:45 -0700209 public static final boolean DEBUG_CONFIGURATION = false;
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800210 private static final boolean DEBUG_SERVICE = false;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800211 public static final boolean DEBUG_MEMORY_TRIM = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700212 private static final boolean DEBUG_PROVIDER = false;
Andrii Kulianb372da62018-01-18 10:46:24 -0800213 public static final boolean DEBUG_ORDER = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216
Dianne Hackborn455625e2015-01-21 09:55:13 -0800217 /** Type for IActivityManager.serviceDoneExecuting: anonymous operation */
218 public static final int SERVICE_DONE_EXECUTING_ANON = 0;
219 /** Type for IActivityManager.serviceDoneExecuting: done with an onStart call */
220 public static final int SERVICE_DONE_EXECUTING_START = 1;
221 /** Type for IActivityManager.serviceDoneExecuting: done stopping (destroying) service */
222 public static final int SERVICE_DONE_EXECUTING_STOP = 2;
223
Filip Gruszczynskica664812015-12-04 12:43:36 -0800224 // Whether to invoke an activity callback after delivering new configuration.
225 private static final boolean REPORT_TO_ACTIVITY = true;
226
Sudheer Shanka84a48952017-03-08 18:19:01 -0800227 /**
228 * Denotes an invalid sequence number corresponding to a process state change.
229 */
230 public static final long INVALID_PROC_STATE_SEQ = -1;
231
Sudheer Shankaf6690102017-10-16 10:20:32 -0700232 /**
233 * Identifier for the sequence no. associated with this process start. It will be provided
234 * as one of the arguments when the process starts.
235 */
236 public static final String PROC_START_SEQ_IDENT = "seq=";
237
Sudheer Shanka84a48952017-03-08 18:19:01 -0800238 private final Object mNetworkPolicyLock = new Object();
239
240 /**
241 * Denotes the sequence number of the process state change for which the main thread needs
242 * to block until the network rules are updated for it.
243 *
244 * Value of {@link #INVALID_PROC_STATE_SEQ} indicates there is no need for blocking.
245 */
246 @GuardedBy("mNetworkPolicyLock")
247 private long mNetworkBlockSeq = INVALID_PROC_STATE_SEQ;
248
Jeff Browndefd4a62014-03-10 21:24:37 -0700249 private ContextImpl mSystemContext;
Adam Lesinskia82b6262017-03-21 16:56:17 -0700250 private ContextImpl mSystemUiContext;
Bob Leee5408332009-09-04 18:31:17 -0700251
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700252 static volatile IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700254 final ApplicationThread mAppThread = new ApplicationThread();
255 final Looper mLooper = Looper.myLooper();
256 final H mH = new H();
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700257 final Executor mExecutor = new HandlerExecutor(mH);
Dianne Hackborn782d4982015-07-08 17:36:37 -0700258 final ArrayMap<IBinder, ActivityClientRecord> mActivities = new ArrayMap<>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700259 // List of new activities (via ActivityRecord.nextIdle) that should
260 // be reported when next we idle.
261 ActivityClientRecord mNewActivities = null;
262 // Number of activities that are currently visible on-screen.
263 int mNumVisibleActivities = 0;
Amith Yamasani4f128e42016-05-10 11:44:12 -0700264 ArrayList<WeakReference<AssistStructure>> mLastAssistStructures = new ArrayList<>();
265 private int mLastSessionId;
Dianne Hackborn782d4982015-07-08 17:36:37 -0700266 final ArrayMap<IBinder, Service> mServices = new ArrayMap<>();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700267 AppBindData mBoundApplication;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700268 Profiler mProfiler;
Dianne Hackborn908aecc2012-07-31 16:37:34 -0700269 int mCurDefaultDisplayDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -0700270 boolean mDensityCompatMode;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700271 Configuration mConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700272 Configuration mCompatConfiguration;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700273 Application mInitialApplication;
274 final ArrayList<Application> mAllApplications
275 = new ArrayList<Application>();
276 // set of instantiated backup agents, keyed by package name
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700277 final ArrayMap<String, BackupAgent> mBackupAgents = new ArrayMap<String, BackupAgent>();
Jeff Sharkey66a017b2013-01-17 18:18:22 -0800278 /** Reference to singleton {@link ActivityThread} */
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700279 private static volatile ActivityThread sCurrentActivityThread;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700280 Instrumentation mInstrumentation;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700281 String mInstrumentationPackageName = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700282 String mInstrumentationAppDir = null;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700283 String[] mInstrumentationSplitAppDirs = null;
284 String mInstrumentationLibDir = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700285 String mInstrumentedAppDir = null;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700286 String[] mInstrumentedSplitAppDirs = null;
287 String mInstrumentedLibDir = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700288 boolean mSystemThread = false;
289 boolean mJitEnabled = false;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700290 boolean mSomeActivitiesChanged = false;
Chong Zhang4951f9d2016-06-23 13:15:08 -0700291 boolean mUpdatingSystemConfig = false;
David Brazdild960cc42018-01-31 07:59:17 +0000292 /* package */ boolean mHiddenApiWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100294 // These can be accessed by multiple threads; mResourcesManager is the lock.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700295 // XXX For now we keep around information about all packages we have
296 // seen, not removing entries from this map.
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800297 // NOTE: The activity and window managers need to call in to
Dianne Hackborn2f0b1752011-05-31 17:59:49 -0700298 // ActivityThread to do things like update resource configurations,
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800299 // which means this lock gets held while the activity and window managers
300 // holds their own lock. Thus you MUST NEVER call back into the activity manager
301 // or window manager or anything that depends on them while holding this lock.
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700302 // These LoadedApk are only valid for the userId that we're running as.
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100303 @GuardedBy("mResourcesManager")
304 final ArrayMap<String, WeakReference<LoadedApk>> mPackages = new ArrayMap<>();
305 @GuardedBy("mResourcesManager")
306 final ArrayMap<String, WeakReference<LoadedApk>> mResourcePackages = new ArrayMap<>();
307 @GuardedBy("mResourcesManager")
308 final ArrayList<ActivityClientRecord> mRelaunchingActivities = new ArrayList<>();
309 @GuardedBy("mResourcesManager")
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700310 Configuration mPendingConfiguration = null;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800311 // An executor that performs multi-step transactions.
312 private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313
Craig Mautner88c05892013-06-28 09:47:45 -0700314 private final ResourcesManager mResourcesManager;
315
Jeff Sharkey6d515712012-09-20 16:06:08 -0700316 private static final class ProviderKey {
317 final String authority;
318 final int userId;
319
320 public ProviderKey(String authority, int userId) {
321 this.authority = authority;
322 this.userId = userId;
323 }
324
325 @Override
326 public boolean equals(Object o) {
327 if (o instanceof ProviderKey) {
328 final ProviderKey other = (ProviderKey) o;
Kenny Roote6585b32013-12-13 12:00:26 -0800329 return Objects.equals(authority, other.authority) && userId == other.userId;
Jeff Sharkey6d515712012-09-20 16:06:08 -0700330 }
331 return false;
332 }
333
334 @Override
335 public int hashCode() {
336 return ((authority != null) ? authority.hashCode() : 0) ^ userId;
337 }
338 }
339
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700340 // The lock of mProviderMap protects the following variables.
Wale Ogunwale1d646122015-04-24 14:45:14 -0700341 final ArrayMap<ProviderKey, ProviderClientRecord> mProviderMap
342 = new ArrayMap<ProviderKey, ProviderClientRecord>();
343 final ArrayMap<IBinder, ProviderRefCount> mProviderRefCountMap
344 = new ArrayMap<IBinder, ProviderRefCount>();
345 final ArrayMap<IBinder, ProviderClientRecord> mLocalProviders
346 = new ArrayMap<IBinder, ProviderClientRecord>();
347 final ArrayMap<ComponentName, ProviderClientRecord> mLocalProvidersByName
348 = new ArrayMap<ComponentName, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349
Makoto Onukib6c79ea2018-05-31 11:03:56 -0700350 // Mitigation for b/74523247: Used to serialize calls to AM.getContentProvider().
351 // Note we never removes items from this map but that's okay because there are only so many
352 // users and so many authorities.
353 // TODO Remove it once we move CPR.wait() from AMS to the client side.
354 @GuardedBy("mGetProviderLocks")
355 final ArrayMap<ProviderKey, Object> mGetProviderLocks = new ArrayMap<>();
356
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700357 final ArrayMap<Activity, ArrayList<OnActivityPausedListener>> mOnPauseListeners
Wale Ogunwale1d646122015-04-24 14:45:14 -0700358 = new ArrayMap<Activity, ArrayList<OnActivityPausedListener>>();
Jeff Hamilton52d32032011-01-08 15:31:26 -0600359
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700360 final GcIdler mGcIdler = new GcIdler();
361 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700363 static volatile Handler sMainThreadHandler; // set once in main()
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700364
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800365 Bundle mCoreSettings = null;
366
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800367 /** Activity client record, used for bookkeeping for the real {@link Activity} instance. */
368 public static final class ActivityClientRecord {
369 public IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700370 int ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371 Intent intent;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800372 String referrer;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700373 IVoiceInteractor voiceInteractor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 Bundle state;
Craig Mautnera0026042014-04-23 11:45:37 -0700375 PersistableBundle persistentState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 Activity activity;
377 Window window;
378 Activity parent;
379 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700380 Activity.NonConfigurationInstances lastNonConfigurationInstances;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800381 // TODO(lifecycler): Use mLifecycleState instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 boolean paused;
383 boolean stopped;
384 boolean hideForNow;
385 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700386 Configuration createdConfig;
Wale Ogunwale60454db2015-01-23 16:05:07 -0800387 Configuration overrideConfig;
Wale Ogunwalec2607b42015-02-07 16:16:59 -0800388 // Used for consolidating configs before sending on to Activity.
389 private Configuration tmpConfig = new Configuration();
Andrii Kulian44607962017-03-16 11:06:24 -0700390 // Callback used for updating activity override config.
391 ViewRootImpl.ActivityConfigCallback configCallback;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700392 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800393
Jeff Hao1b012d32014-08-20 10:35:34 -0700394 ProfilerInfo profilerInfo;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 ActivityInfo activityInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400397 CompatibilityInfo compatInfo;
Todd Kennedy233a0b12018-01-29 20:30:24 +0000398 public LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399
400 List<ResultInfo> pendingResults;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800401 List<ReferrerIntent> pendingIntents;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402
403 boolean startsNotResumed;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800404 public final boolean isForward;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800405 int pendingConfigChanges;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800406
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700407 Window mPendingRemoveWindow;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800408 WindowManager mPendingRemoveWindowManager;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700409 boolean mPreserveWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800411 @LifecycleState
412 private int mLifecycleState = PRE_ON_CREATE;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700413
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800414 @VisibleForTesting
415 public ActivityClientRecord() {
416 this.isForward = false;
417 init();
418 }
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700419
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800420 public ActivityClientRecord(IBinder token, Intent intent, int ident,
421 ActivityInfo info, Configuration overrideConfig, CompatibilityInfo compatInfo,
422 String referrer, IVoiceInteractor voiceInteractor, Bundle state,
423 PersistableBundle persistentState, List<ResultInfo> pendingResults,
424 List<ReferrerIntent> pendingNewIntents, boolean isForward,
425 ProfilerInfo profilerInfo, ClientTransactionHandler client) {
426 this.token = token;
427 this.ident = ident;
428 this.intent = intent;
429 this.referrer = referrer;
430 this.voiceInteractor = voiceInteractor;
431 this.activityInfo = info;
432 this.compatInfo = compatInfo;
433 this.state = state;
434 this.persistentState = persistentState;
435 this.pendingResults = pendingResults;
436 this.pendingIntents = pendingNewIntents;
437 this.isForward = isForward;
438 this.profilerInfo = profilerInfo;
439 this.overrideConfig = overrideConfig;
Todd Kennedy233a0b12018-01-29 20:30:24 +0000440 this.packageInfo = client.getPackageInfoNoCheck(activityInfo.applicationInfo,
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800441 compatInfo);
442 init();
443 }
444
445 /** Common initializer for all constructors. */
446 private void init() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 parent = null;
448 embeddedID = null;
449 paused = false;
450 stopped = false;
451 hideForNow = false;
452 nextIdle = null;
Andrii Kulian44607962017-03-16 11:06:24 -0700453 configCallback = (Configuration overrideConfig, int newDisplayId) -> {
454 if (activity == null) {
455 throw new IllegalStateException(
456 "Received config update for non-existing activity");
457 }
Andrii Kulian446e8242017-10-26 15:17:29 -0700458 activity.mMainThread.handleActivityConfigurationChanged(token, overrideConfig,
459 newDisplayId);
Andrii Kulian44607962017-03-16 11:06:24 -0700460 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 }
462
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800463 /** Get the current lifecycle state. */
464 public int getLifecycleState() {
465 return mLifecycleState;
466 }
467
468 /** Update the current lifecycle state for internal bookkeeping. */
469 public void setState(@LifecycleState int newLifecycleState) {
470 mLifecycleState = newLifecycleState;
471 switch (mLifecycleState) {
472 case ON_CREATE:
473 paused = true;
474 stopped = true;
475 break;
476 case ON_START:
477 paused = true;
478 stopped = false;
479 break;
480 case ON_RESUME:
481 paused = false;
482 stopped = false;
483 break;
484 case ON_PAUSE:
485 paused = true;
486 stopped = false;
487 break;
488 case ON_STOP:
489 paused = true;
490 stopped = true;
491 break;
492 }
493 }
494
Andrii Kulian391161f2018-01-29 10:50:02 -0800495 private boolean isPreHoneycomb() {
496 return activity != null && activity.getApplicationInfo().targetSdkVersion
497 < android.os.Build.VERSION_CODES.HONEYCOMB;
498 }
499
500 private boolean isPreP() {
501 return activity != null && activity.getApplicationInfo().targetSdkVersion
502 < android.os.Build.VERSION_CODES.P;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800503 }
504
Craig Mautnera0026042014-04-23 11:45:37 -0700505 public boolean isPersistable() {
Craig Mautner43e52ed2014-06-16 17:18:52 -0700506 return activityInfo.persistableMode == ActivityInfo.PERSIST_ACROSS_REBOOTS;
Craig Mautnera0026042014-04-23 11:45:37 -0700507 }
508
Andrii Kulian914aa7d2018-03-19 21:51:53 -0700509 public boolean isVisibleFromServer() {
510 return activity != null && activity.mVisibleFromServer;
511 }
512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 public String toString() {
Dianne Hackbornb61a0262012-05-14 17:19:18 -0700514 ComponentName componentName = intent != null ? intent.getComponent() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515 return "ActivityRecord{"
516 + Integer.toHexString(System.identityHashCode(this))
517 + " token=" + token + " " + (componentName == null
518 ? "no component name" : componentName.toShortString())
519 + "}";
520 }
Andrii Kulian58178f22016-03-16 13:44:56 -0700521
522 public String getStateString() {
523 StringBuilder sb = new StringBuilder();
524 sb.append("ActivityClientRecord{");
525 sb.append("paused=").append(paused);
526 sb.append(", stopped=").append(stopped);
527 sb.append(", hideForNow=").append(hideForNow);
528 sb.append(", startsNotResumed=").append(startsNotResumed);
529 sb.append(", isForward=").append(isForward);
530 sb.append(", pendingConfigChanges=").append(pendingConfigChanges);
Andrii Kulian58178f22016-03-16 13:44:56 -0700531 sb.append(", preserveWindow=").append(mPreserveWindow);
532 if (activity != null) {
533 sb.append(", Activity{");
534 sb.append("resumed=").append(activity.mResumed);
535 sb.append(", stopped=").append(activity.mStopped);
536 sb.append(", finished=").append(activity.isFinishing());
537 sb.append(", destroyed=").append(activity.isDestroyed());
538 sb.append(", startedActivity=").append(activity.mStartedActivity);
539 sb.append(", temporaryPause=").append(activity.mTemporaryPause);
540 sb.append(", changingConfigurations=").append(activity.mChangingConfigurations);
Andrii Kulian58178f22016-03-16 13:44:56 -0700541 sb.append("}");
542 }
543 sb.append("}");
544 return sb.toString();
545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 }
547
Wale Ogunwale1d646122015-04-24 14:45:14 -0700548 final class ProviderClientRecord {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700549 final String[] mNames;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 final IContentProvider mProvider;
551 final ContentProvider mLocalProvider;
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700552 final ContentProviderHolder mHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700554 ProviderClientRecord(String[] names, IContentProvider provider,
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700555 ContentProvider localProvider, ContentProviderHolder holder) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700556 mNames = names;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 mProvider = provider;
558 mLocalProvider = localProvider;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700559 mHolder = holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 }
561 }
562
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400563 static final class ReceiverData extends BroadcastReceiver.PendingResult {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700564 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700565 boolean ordered, boolean sticky, IBinder token, int sendingUser) {
566 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky,
riddle_hsu1f5ac4d2015-01-03 15:38:21 +0800567 token, sendingUser, intent.getFlags());
Dianne Hackborne829fef2010-10-26 17:44:01 -0700568 this.intent = intent;
569 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 Intent intent;
572 ActivityInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400573 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 public String toString() {
575 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700576 info.packageName + " resultCode=" + getResultCode()
577 + " resultData=" + getResultData() + " resultExtras="
578 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 }
580 }
581
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400582 static final class CreateBackupAgentData {
Christopher Tate181fafa2009-05-14 11:12:14 -0700583 ApplicationInfo appInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400584 CompatibilityInfo compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700585 int backupMode;
586 public String toString() {
587 return "CreateBackupAgentData{appInfo=" + appInfo
588 + " backupAgent=" + appInfo.backupAgentName
589 + " mode=" + backupMode + "}";
590 }
591 }
Bob Leee5408332009-09-04 18:31:17 -0700592
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400593 static final class CreateServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 IBinder token;
595 ServiceInfo info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400596 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 Intent intent;
598 public String toString() {
599 return "CreateServiceData{token=" + token + " className="
600 + info.name + " packageName=" + info.packageName
601 + " intent=" + intent + "}";
602 }
603 }
604
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400605 static final class BindServiceData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 IBinder token;
607 Intent intent;
608 boolean rebind;
609 public String toString() {
610 return "BindServiceData{token=" + token + " intent=" + intent + "}";
611 }
612 }
613
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400614 static final class ServiceArgsData {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 IBinder token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700616 boolean taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700618 int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 Intent args;
620 public String toString() {
621 return "ServiceArgsData{token=" + token + " startId=" + startId
622 + " args=" + args + "}";
623 }
624 }
625
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400626 static final class AppBindData {
Todd Kennedy233a0b12018-01-29 20:30:24 +0000627 LoadedApk info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 String processName;
629 ApplicationInfo appInfo;
630 List<ProviderInfo> providers;
631 ComponentName instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 Bundle instrumentationArgs;
633 IInstrumentationWatcher instrumentationWatcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800634 IUiAutomationConnection instrumentationUiAutomationConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 int debugMode;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400636 boolean enableBinderTracking;
Man Caocfa78b22015-06-11 20:14:34 -0700637 boolean trackAllocation;
Christopher Tate181fafa2009-05-14 11:12:14 -0700638 boolean restrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700639 boolean persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 Configuration config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400641 CompatibilityInfo compatInfo;
Svet Ganov37e43272016-09-09 16:01:32 -0700642 String buildSerial;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700643
644 /** Initial values for {@link Profiler}. */
Jeff Hao1b012d32014-08-20 10:35:34 -0700645 ProfilerInfo initProfilerInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700646
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800647 boolean autofillCompatibilityEnabled;
648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 public String toString() {
650 return "AppBindData{appInfo=" + appInfo + "}";
651 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700652 }
653
654 static final class Profiler {
655 String profileFile;
656 ParcelFileDescriptor profileFd;
Jeff Hao1b012d32014-08-20 10:35:34 -0700657 int samplingInterval;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700658 boolean autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800659 boolean streamingOutput;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700660 boolean profiling;
661 boolean handlingProfiling;
Jeff Hao1b012d32014-08-20 10:35:34 -0700662 public void setProfiler(ProfilerInfo profilerInfo) {
663 ParcelFileDescriptor fd = profilerInfo.profileFd;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700664 if (profiling) {
665 if (fd != null) {
666 try {
667 fd.close();
668 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700669 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700670 }
671 }
672 return;
673 }
674 if (profileFd != null) {
675 try {
676 profileFd.close();
677 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700678 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700679 }
680 }
Jeff Hao1b012d32014-08-20 10:35:34 -0700681 profileFile = profilerInfo.profileFile;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700682 profileFd = fd;
Jeff Hao1b012d32014-08-20 10:35:34 -0700683 samplingInterval = profilerInfo.samplingInterval;
684 autoStopProfiler = profilerInfo.autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800685 streamingOutput = profilerInfo.streamingOutput;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700686 }
687 public void startProfiling() {
688 if (profileFd == null || profiling) {
689 return;
690 }
691 try {
Andreas Gampeeff06392016-05-10 12:51:45 -0700692 int bufferSize = SystemProperties.getInt("debug.traceview-buffer-size-mb", 8);
Jeff Hao1b012d32014-08-20 10:35:34 -0700693 VMDebug.startMethodTracing(profileFile, profileFd.getFileDescriptor(),
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800694 bufferSize * 1024 * 1024, 0, samplingInterval != 0, samplingInterval,
695 streamingOutput);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700696 profiling = true;
697 } catch (RuntimeException e) {
Andreas Gampe4f689242018-03-14 23:13:28 -0700698 Slog.w(TAG, "Profiling failed on path " + profileFile, e);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700699 try {
700 profileFd.close();
701 profileFd = null;
702 } catch (IOException e2) {
703 Slog.w(TAG, "Failure closing profile fd", e2);
704 }
705 }
706 }
707 public void stopProfiling() {
708 if (profiling) {
709 profiling = false;
710 Debug.stopMethodTracing();
711 if (profileFd != null) {
712 try {
713 profileFd.close();
714 } catch (IOException e) {
715 }
716 }
717 profileFd = null;
718 profileFile = null;
719 }
720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 }
722
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400723 static final class DumpComponentInfo {
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700724 ParcelFileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700725 IBinder token;
Dianne Hackborn30d71892010-12-11 10:37:55 -0800726 String prefix;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 String[] args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 }
729
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400730 static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800731 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 String what;
733 String who;
734 }
735
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400736 static final class DumpHeapData {
Christopher Ferris8d652f82017-04-11 16:29:18 -0700737 public boolean managed;
738 public boolean mallocInfo;
Makoto Onuki4556b7b2017-07-07 14:58:58 -0700739 public boolean runGc;
Andy McFadden824c5102010-07-09 16:26:57 -0700740 String path;
741 ParcelFileDescriptor fd;
742 }
743
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400744 static final class UpdateCompatibilityData {
745 String pkg;
746 CompatibilityInfo info;
747 }
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800748
Adam Skorydfc7fd72013-08-05 19:23:41 -0700749 static final class RequestAssistContextExtras {
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800750 IBinder activityToken;
751 IBinder requestToken;
752 int requestType;
Amith Yamasani4f128e42016-05-10 11:44:12 -0700753 int sessionId;
Svet Ganovfd31f852017-04-26 15:54:27 -0700754 int flags;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800755 }
Anwar Ghuloum3a8ce1b2013-04-26 16:18:28 -0700756
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700757 private class ApplicationThread extends IApplicationThread.Stub {
Vasu Nori3c7131f2010-09-21 14:36:57 -0700758 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700759
Dianne Hackborna413dc02013-07-12 12:02:55 -0700760 private int mLastProcessState = -1;
761
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700762 private void updatePendingConfiguration(Configuration config) {
Craig Mautner88c05892013-06-28 09:47:45 -0700763 synchronized (mResourcesManager) {
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700764 if (mPendingConfiguration == null ||
765 mPendingConfiguration.isOtherSeqNewer(config)) {
766 mPendingConfiguration = config;
767 }
768 }
769 }
770
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800771 public final void scheduleSleeping(IBinder token, boolean sleeping) {
Jeff Brown9ef09972013-10-15 20:49:59 -0700772 sendMessage(H.SLEEPING, token, sleeping ? 1 : 0);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800773 }
774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 public final void scheduleReceiver(Intent intent, ActivityInfo info,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400776 CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700777 boolean sync, int sendingUser, int processState) {
778 updateProcessState(processState, false);
Dianne Hackborne829fef2010-10-26 17:44:01 -0700779 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700780 sync, false, mAppThread.asBinder(), sendingUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 r.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400782 r.compatInfo = compatInfo;
Jeff Brown9ef09972013-10-15 20:49:59 -0700783 sendMessage(H.RECEIVER, r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 }
785
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400786 public final void scheduleCreateBackupAgent(ApplicationInfo app,
787 CompatibilityInfo compatInfo, int backupMode) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700788 CreateBackupAgentData d = new CreateBackupAgentData();
789 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400790 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700791 d.backupMode = backupMode;
792
Jeff Brown9ef09972013-10-15 20:49:59 -0700793 sendMessage(H.CREATE_BACKUP_AGENT, d);
Christopher Tate181fafa2009-05-14 11:12:14 -0700794 }
795
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400796 public final void scheduleDestroyBackupAgent(ApplicationInfo app,
797 CompatibilityInfo compatInfo) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700798 CreateBackupAgentData d = new CreateBackupAgentData();
799 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400800 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700801
Jeff Brown9ef09972013-10-15 20:49:59 -0700802 sendMessage(H.DESTROY_BACKUP_AGENT, d);
Christopher Tate181fafa2009-05-14 11:12:14 -0700803 }
804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 public final void scheduleCreateService(IBinder token,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700806 ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
807 updateProcessState(processState, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 CreateServiceData s = new CreateServiceData();
809 s.token = token;
810 s.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400811 s.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812
Jeff Brown9ef09972013-10-15 20:49:59 -0700813 sendMessage(H.CREATE_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 }
815
816 public final void scheduleBindService(IBinder token, Intent intent,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700817 boolean rebind, int processState) {
818 updateProcessState(processState, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 BindServiceData s = new BindServiceData();
820 s.token = token;
821 s.intent = intent;
822 s.rebind = rebind;
823
Amith Yamasani742a6712011-05-04 14:49:28 -0700824 if (DEBUG_SERVICE)
825 Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
826 + Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
Jeff Brown9ef09972013-10-15 20:49:59 -0700827 sendMessage(H.BIND_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 }
829
830 public final void scheduleUnbindService(IBinder token, Intent intent) {
831 BindServiceData s = new BindServiceData();
832 s.token = token;
833 s.intent = intent;
834
Jeff Brown9ef09972013-10-15 20:49:59 -0700835 sendMessage(H.UNBIND_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 }
837
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -0700838 public final void scheduleServiceArgs(IBinder token, ParceledListSlice args) {
839 List<ServiceStartArgs> list = args.getList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -0700841 for (int i = 0; i < list.size(); i++) {
842 ServiceStartArgs ssa = list.get(i);
843 ServiceArgsData s = new ServiceArgsData();
844 s.token = token;
845 s.taskRemoved = ssa.taskRemoved;
846 s.startId = ssa.startId;
847 s.flags = ssa.flags;
848 s.args = ssa.args;
849
850 sendMessage(H.SERVICE_ARGS, s);
851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 }
853
854 public final void scheduleStopService(IBinder token) {
Jeff Brown9ef09972013-10-15 20:49:59 -0700855 sendMessage(H.STOP_SERVICE, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 }
857
Jeff Hao1b012d32014-08-20 10:35:34 -0700858 public final void bindApplication(String processName, ApplicationInfo appInfo,
859 List<ProviderInfo> providers, ComponentName instrumentationName,
860 ProfilerInfo profilerInfo, Bundle instrumentationArgs,
861 IInstrumentationWatcher instrumentationWatcher,
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800862 IUiAutomationConnection instrumentationUiConnection, int debugMode,
Pablo Ceballosa4d4e822015-10-05 10:27:52 -0700863 boolean enableBinderTracking, boolean trackAllocation,
864 boolean isRestrictedBackupMode, boolean persistent, Configuration config,
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700865 CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800866 String buildSerial, boolean autofillCompatibilityEnabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867
868 if (services != null) {
Makoto Onuki45895652018-05-07 14:43:05 -0700869 if (false) {
870 // Test code to make sure the app could see the passed-in services.
871 for (Object oname : services.keySet()) {
872 if (services.get(oname) == null) {
873 continue; // AM just passed in a null service.
874 }
875 String name = (String) oname;
876
877 // See b/79378449 about the following exemption.
878 switch (name) {
879 case "package":
880 case Context.WINDOW_SERVICE:
881 continue;
882 }
883
884 if (ServiceManager.getService(name) == null) {
885 Log.wtf(TAG, "Service " + name + " should be accessible by this app");
886 }
887 }
888 }
889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 // Setup the service cache in the ServiceManager
891 ServiceManager.initServiceCache(services);
892 }
893
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800894 setCoreSettings(coreSettings);
895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 AppBindData data = new AppBindData();
897 data.processName = processName;
898 data.appInfo = appInfo;
899 data.providers = providers;
900 data.instrumentationName = instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 data.instrumentationArgs = instrumentationArgs;
902 data.instrumentationWatcher = instrumentationWatcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800903 data.instrumentationUiAutomationConnection = instrumentationUiConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 data.debugMode = debugMode;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400905 data.enableBinderTracking = enableBinderTracking;
Man Caocfa78b22015-06-11 20:14:34 -0700906 data.trackAllocation = trackAllocation;
Christopher Tate181fafa2009-05-14 11:12:14 -0700907 data.restrictedBackupMode = isRestrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700908 data.persistent = persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 data.config = config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400910 data.compatInfo = compatInfo;
Jeff Hao1b012d32014-08-20 10:35:34 -0700911 data.initProfilerInfo = profilerInfo;
Svet Ganov37e43272016-09-09 16:01:32 -0700912 data.buildSerial = buildSerial;
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800913 data.autofillCompatibilityEnabled = autofillCompatibilityEnabled;
Jeff Brown9ef09972013-10-15 20:49:59 -0700914 sendMessage(H.BIND_APPLICATION, data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 }
916
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -0400917 public final void runIsolatedEntryPoint(String entryPoint, String[] entryPointArgs) {
918 SomeArgs args = SomeArgs.obtain();
919 args.arg1 = entryPoint;
920 args.arg2 = entryPointArgs;
921 sendMessage(H.RUN_ISOLATED_ENTRY_POINT, args);
922 }
923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 public final void scheduleExit() {
Jeff Brown9ef09972013-10-15 20:49:59 -0700925 sendMessage(H.EXIT_APPLICATION, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 }
927
Christopher Tate5e1ab332009-09-01 20:32:49 -0700928 public final void scheduleSuicide() {
Jeff Brown9ef09972013-10-15 20:49:59 -0700929 sendMessage(H.SUICIDE, null);
Christopher Tate5e1ab332009-09-01 20:32:49 -0700930 }
931
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100932 public void scheduleApplicationInfoChanged(ApplicationInfo ai) {
933 sendMessage(H.APPLICATION_INFO_CHANGED, ai);
934 }
935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 public void updateTimeZone() {
937 TimeZone.setDefault(null);
938 }
939
Robert Greenwalt03595d02010-11-02 14:08:23 -0700940 public void clearDnsCache() {
941 // a non-standard API to get this to libcore
942 InetAddress.clearDnsCache();
Paul Jensene401d172014-09-12 10:47:39 -0400943 // Allow libcore to perform the necessary actions as it sees fit upon a network
944 // configuration change.
945 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Robert Greenwalt03595d02010-11-02 14:08:23 -0700946 }
947
Jason Monk83520b92014-05-09 15:16:06 -0400948 public void setHttpProxy(String host, String port, String exclList, Uri pacFileUrl) {
Chalard Jean100df0a2018-05-15 23:11:45 +0900949 final ConnectivityManager cm = ConnectivityManager.from(
950 getApplication() != null ? getApplication() : getSystemContext());
Paul Jensen72db88e2015-03-10 10:54:12 -0400951 final Network network = cm.getBoundNetworkForProcess();
Paul Jensene0bef712014-12-10 15:12:18 -0500952 if (network != null) {
Paul Jensen72db88e2015-03-10 10:54:12 -0400953 Proxy.setHttpProxySystemProperty(cm.getDefaultProxy());
Paul Jensene0bef712014-12-10 15:12:18 -0500954 } else {
955 Proxy.setHttpProxySystemProperty(host, port, exclList, pacFileUrl);
956 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700957 }
958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 public void processInBackground() {
960 mH.removeMessages(H.GC_WHEN_IDLE);
961 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
962 }
963
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700964 public void dumpService(ParcelFileDescriptor pfd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700965 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700966 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700967 data.fd = pfd.dup();
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700968 data.token = servicetoken;
969 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -0700970 sendMessage(H.DUMP_SERVICE, data, 0, 0, true /*async*/);
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700971 } catch (IOException e) {
972 Slog.w(TAG, "dumpService failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700973 } finally {
974 IoUtils.closeQuietly(pfd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 }
976 }
977
978 // This function exists to make sure all receiver dispatching is
979 // correctly ordered, since these are one-way calls and the binder driver
980 // applies transaction ordering per object for such calls.
981 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -0700982 int resultCode, String dataStr, Bundle extras, boolean ordered,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700983 boolean sticky, int sendingUser, int processState) throws RemoteException {
984 updateProcessState(processState, false);
Dianne Hackborn20e80982012-08-31 19:00:44 -0700985 receiver.performReceive(intent, resultCode, dataStr, extras, ordered,
986 sticky, sendingUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 }
Bob Leee5408332009-09-04 18:31:17 -0700988
Wale Ogunwalec2607b42015-02-07 16:16:59 -0800989 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 public void scheduleLowMemory() {
Jeff Brown9ef09972013-10-15 20:49:59 -0700991 sendMessage(H.LOW_MEMORY, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 }
993
Wale Ogunwale60454db2015-01-23 16:05:07 -0800994 @Override
Jeff Hao1b012d32014-08-20 10:35:34 -0700995 public void profilerControl(boolean start, ProfilerInfo profilerInfo, int profileType) {
996 sendMessage(H.PROFILER_CONTROL, profilerInfo, start ? 1 : 0, profileType);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -0800997 }
998
Makoto Onuki4556b7b2017-07-07 14:58:58 -0700999 @Override
Christopher Ferris8d652f82017-04-11 16:29:18 -07001000 public void dumpHeap(boolean managed, boolean mallocInfo, boolean runGc, String path,
1001 ParcelFileDescriptor fd) {
Andy McFadden824c5102010-07-09 16:26:57 -07001002 DumpHeapData dhd = new DumpHeapData();
Christopher Ferris8d652f82017-04-11 16:29:18 -07001003 dhd.managed = managed;
1004 dhd.mallocInfo = mallocInfo;
Makoto Onuki4556b7b2017-07-07 14:58:58 -07001005 dhd.runGc = runGc;
Andy McFadden824c5102010-07-09 16:26:57 -07001006 dhd.path = path;
1007 dhd.fd = fd;
Christopher Ferris8d652f82017-04-11 16:29:18 -07001008 sendMessage(H.DUMP_HEAP, dhd, 0, 0, true /*async*/);
Andy McFadden824c5102010-07-09 16:26:57 -07001009 }
1010
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001011 public void attachAgent(String agent) {
1012 sendMessage(H.ATTACH_AGENT, agent);
1013 }
1014
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001015 public void setSchedulingGroup(int group) {
1016 // Note: do this immediately, since going into the foreground
1017 // should happen regardless of what pending work we have to do
1018 // and the activity manager will wait for us to report back that
1019 // we are done before sending us to the background.
1020 try {
1021 Process.setProcessGroup(Process.myPid(), group);
1022 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001023 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001024 }
1025 }
Bob Leee5408332009-09-04 18:31:17 -07001026
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001027 public void dispatchPackageBroadcast(int cmd, String[] packages) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001028 sendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001029 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001030
1031 public void scheduleCrash(String msg) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001032 sendMessage(H.SCHEDULE_CRASH, msg);
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001033 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07001034
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001035 public void dumpActivity(ParcelFileDescriptor pfd, IBinder activitytoken,
Dianne Hackborn30d71892010-12-11 10:37:55 -08001036 String prefix, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07001037 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001038 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001039 data.fd = pfd.dup();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001040 data.token = activitytoken;
1041 data.prefix = prefix;
1042 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001043 sendMessage(H.DUMP_ACTIVITY, data, 0, 0, true /*async*/);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001044 } catch (IOException e) {
1045 Slog.w(TAG, "dumpActivity failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001046 } finally {
1047 IoUtils.closeQuietly(pfd);
Dianne Hackborn625ac272010-09-17 18:29:22 -07001048 }
1049 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07001050
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001051 public void dumpProvider(ParcelFileDescriptor pfd, IBinder providertoken,
Marco Nelissen18cb2872011-11-15 11:19:53 -08001052 String[] args) {
1053 DumpComponentInfo data = new DumpComponentInfo();
1054 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001055 data.fd = pfd.dup();
Marco Nelissen18cb2872011-11-15 11:19:53 -08001056 data.token = providertoken;
1057 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001058 sendMessage(H.DUMP_PROVIDER, data, 0, 0, true /*async*/);
Marco Nelissen18cb2872011-11-15 11:19:53 -08001059 } catch (IOException e) {
1060 Slog.w(TAG, "dumpProvider failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001061 } finally {
1062 IoUtils.closeQuietly(pfd);
Marco Nelissen18cb2872011-11-15 11:19:53 -08001063 }
1064 }
1065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001067 public void dumpMemInfo(ParcelFileDescriptor pfd, Debug.MemoryInfo mem, boolean checkin,
Colin Crossc4fb5f92016-02-02 16:51:15 -08001068 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
1069 boolean dumpUnreachable, String[] args) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001070 FileOutputStream fout = new FileOutputStream(pfd.getFileDescriptor());
Dianne Hackborn8c841092013-06-24 13:46:13 -07001071 PrintWriter pw = new FastPrintWriter(fout);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001072 try {
Colin Crossc4fb5f92016-02-02 16:51:15 -08001073 dumpMemInfo(pw, mem, checkin, dumpFullInfo, dumpDalvik, dumpSummaryOnly, dumpUnreachable);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001074 } finally {
Chet Haase9c1e23b2011-03-24 10:51:31 -07001075 pw.flush();
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001076 IoUtils.closeQuietly(pfd);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001077 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001078 }
1079
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001080 private void dumpMemInfo(PrintWriter pw, Debug.MemoryInfo memInfo, boolean checkin,
Colin Crossc4fb5f92016-02-02 16:51:15 -08001081 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly, boolean dumpUnreachable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 long nativeMax = Debug.getNativeHeapSize() / 1024;
1083 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1084 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 Runtime runtime = Runtime.getRuntime();
Mathieu Chartierd288a262015-07-10 13:44:42 -07001087 runtime.gc(); // Do GC since countInstancesOfClass counts unreachable objects.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 long dalvikMax = runtime.totalMemory() / 1024;
1089 long dalvikFree = runtime.freeMemory() / 1024;
1090 long dalvikAllocated = dalvikMax - dalvikFree;
Richard Uhler2c036192016-09-14 09:48:31 +01001091
1092 Class[] classesToCount = new Class[] {
1093 ContextImpl.class,
1094 Activity.class,
1095 WebView.class,
1096 OpenSSLSocketImpl.class
1097 };
1098 long[] instanceCounts = VMDebug.countInstancesOfClasses(classesToCount, true);
1099 long appContextInstanceCount = instanceCounts[0];
1100 long activityInstanceCount = instanceCounts[1];
1101 long webviewInstanceCount = instanceCounts[2];
1102 long openSslSocketCount = instanceCounts[3];
1103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 long viewInstanceCount = ViewDebug.getViewInstanceCount();
Romain Guy65b345f2011-07-27 18:51:50 -07001105 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 int globalAssetCount = AssetManager.getGlobalAssetCount();
1107 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1108 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1109 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1110 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Dianne Hackbornfabb70b2014-11-11 12:22:36 -08001111 long parcelSize = Parcel.getGlobalAllocSize();
1112 long parcelCount = Parcel.getGlobalAllocCount();
Vasu Noric3849202010-03-09 10:47:25 -08001113 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -07001114
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07001115 dumpMemInfoTable(pw, memInfo, checkin, dumpFullInfo, dumpDalvik, dumpSummaryOnly,
1116 Process.myPid(),
Dianne Hackborne77187d2013-10-25 16:32:41 -07001117 (mBoundApplication != null) ? mBoundApplication.processName : "unknown",
1118 nativeMax, nativeAllocated, nativeFree,
1119 dalvikMax, dalvikAllocated, dalvikFree);
1120
Dianne Hackbornb437e092011-08-05 17:50:29 -07001121 if (checkin) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 // NOTE: if you change anything significant below, also consider changing
1123 // ACTIVITY_THREAD_CHECKIN_VERSION.
Anwar Ghuloum3c615062013-05-13 14:18:02 -07001124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 // Object counts
1126 pw.print(viewInstanceCount); pw.print(',');
1127 pw.print(viewRootInstanceCount); pw.print(',');
1128 pw.print(appContextInstanceCount); pw.print(',');
1129 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 pw.print(globalAssetCount); pw.print(',');
1132 pw.print(globalAssetManagerCount); pw.print(',');
1133 pw.print(binderLocalObjectCount); pw.print(',');
1134 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 pw.print(binderDeathObjectCount); pw.print(',');
1137 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 // SQL
Vasu Noric3849202010-03-09 10:47:25 -08001140 pw.print(stats.memoryUsed / 1024); pw.print(',');
Jeff Brown2a293b62012-01-19 14:02:22 -08001141 pw.print(stats.memoryUsed / 1024); pw.print(',');
1142 pw.print(stats.pageCacheOverflow / 1024); pw.print(',');
Dianne Hackbornb437e092011-08-05 17:50:29 -07001143 pw.print(stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001144 for (int i = 0; i < stats.dbStats.size(); i++) {
1145 DbStats dbStats = stats.dbStats.get(i);
Dianne Hackbornb437e092011-08-05 17:50:29 -07001146 pw.print(','); pw.print(dbStats.dbName);
1147 pw.print(','); pw.print(dbStats.pageSize);
1148 pw.print(','); pw.print(dbStats.dbSize);
1149 pw.print(','); pw.print(dbStats.lookaside);
1150 pw.print(','); pw.print(dbStats.cache);
1151 pw.print(','); pw.print(dbStats.cache);
Vasu Noric3849202010-03-09 10:47:25 -08001152 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07001153 pw.println();
Bob Leee5408332009-09-04 18:31:17 -07001154
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001155 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 }
Bob Leee5408332009-09-04 18:31:17 -07001157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 pw.println(" ");
1159 pw.println(" Objects");
Romain Guy65b345f2011-07-27 18:51:50 -07001160 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRootImpl:",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 viewRootInstanceCount);
1162
1163 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
1164 "Activities:", activityInstanceCount);
1165
1166 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
1167 "AssetManagers:", globalAssetManagerCount);
1168
1169 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
1170 "Proxy Binders:", binderProxyObjectCount);
Dianne Hackbornfabb70b2014-11-11 12:22:36 -08001171 printRow(pw, TWO_COUNT_COLUMNS, "Parcel memory:", parcelSize/1024,
1172 "Parcel count:", parcelCount);
1173 printRow(pw, TWO_COUNT_COLUMNS, "Death Recipients:", binderDeathObjectCount,
1174 "OpenSSL Sockets:", openSslSocketCount);
Richard Uhler2c036192016-09-14 09:48:31 +01001175 printRow(pw, ONE_COUNT_COLUMN, "WebViews:", webviewInstanceCount);
Bob Leee5408332009-09-04 18:31:17 -07001176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 // SQLite mem info
1178 pw.println(" ");
1179 pw.println(" SQL");
Jeff Brown2a293b62012-01-19 14:02:22 -08001180 printRow(pw, ONE_COUNT_COLUMN, "MEMORY_USED:", stats.memoryUsed / 1024);
1181 printRow(pw, TWO_COUNT_COLUMNS, "PAGECACHE_OVERFLOW:",
1182 stats.pageCacheOverflow / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001183 pw.println(" ");
1184 int N = stats.dbStats.size();
1185 if (N > 0) {
1186 pw.println(" DATABASES");
Kweku Adams983829f2017-12-06 14:53:50 -08001187 printRow(pw, DB_INFO_FORMAT, "pgsz", "dbsz", "Lookaside(b)", "cache",
Vasu Nori3c7131f2010-09-21 14:36:57 -07001188 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -08001189 for (int i = 0; i < N; i++) {
1190 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -07001191 printRow(pw, DB_INFO_FORMAT,
1192 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
1193 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
1194 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
1195 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -08001196 }
1197 }
Bob Leee5408332009-09-04 18:31:17 -07001198
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001199 // Asset details.
1200 String assetAlloc = AssetManager.getAssetAllocations();
1201 if (assetAlloc != null) {
1202 pw.println(" ");
1203 pw.println(" Asset Allocations");
1204 pw.print(assetAlloc);
1205 }
Colin Crossc4fb5f92016-02-02 16:51:15 -08001206
1207 // Unreachable native memory
1208 if (dumpUnreachable) {
1209 boolean showContents = ((mBoundApplication != null)
1210 && ((mBoundApplication.appInfo.flags&ApplicationInfo.FLAG_DEBUGGABLE) != 0))
1211 || android.os.Build.IS_DEBUGGABLE;
1212 pw.println(" ");
1213 pw.println(" Unreachable memory");
1214 pw.print(Debug.getUnreachableMemory(100, showContents));
1215 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001216 }
1217
1218 @Override
Kweku Adams983829f2017-12-06 14:53:50 -08001219 public void dumpMemInfoProto(ParcelFileDescriptor pfd, Debug.MemoryInfo mem,
1220 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
1221 boolean dumpUnreachable, String[] args) {
1222 ProtoOutputStream proto = new ProtoOutputStream(pfd.getFileDescriptor());
1223 try {
1224 dumpMemInfo(proto, mem, dumpFullInfo, dumpDalvik, dumpSummaryOnly, dumpUnreachable);
1225 } finally {
1226 proto.flush();
1227 IoUtils.closeQuietly(pfd);
1228 }
1229 }
1230
1231 private void dumpMemInfo(ProtoOutputStream proto, Debug.MemoryInfo memInfo,
1232 boolean dumpFullInfo, boolean dumpDalvik,
1233 boolean dumpSummaryOnly, boolean dumpUnreachable) {
1234 long nativeMax = Debug.getNativeHeapSize() / 1024;
1235 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1236 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1237
1238 Runtime runtime = Runtime.getRuntime();
1239 runtime.gc(); // Do GC since countInstancesOfClass counts unreachable objects.
1240 long dalvikMax = runtime.totalMemory() / 1024;
1241 long dalvikFree = runtime.freeMemory() / 1024;
1242 long dalvikAllocated = dalvikMax - dalvikFree;
1243
1244 Class[] classesToCount = new Class[] {
1245 ContextImpl.class,
1246 Activity.class,
1247 WebView.class,
1248 OpenSSLSocketImpl.class
1249 };
1250 long[] instanceCounts = VMDebug.countInstancesOfClasses(classesToCount, true);
1251 long appContextInstanceCount = instanceCounts[0];
1252 long activityInstanceCount = instanceCounts[1];
1253 long webviewInstanceCount = instanceCounts[2];
1254 long openSslSocketCount = instanceCounts[3];
1255
1256 long viewInstanceCount = ViewDebug.getViewInstanceCount();
1257 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
1258 int globalAssetCount = AssetManager.getGlobalAssetCount();
1259 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1260 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1261 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1262 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
1263 long parcelSize = Parcel.getGlobalAllocSize();
1264 long parcelCount = Parcel.getGlobalAllocCount();
1265 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
1266
Yi Jin2b30f322018-02-20 15:41:47 -08001267 final long mToken = proto.start(MemInfoDumpProto.AppData.PROCESS_MEMORY);
1268 proto.write(MemInfoDumpProto.ProcessMemory.PID, Process.myPid());
1269 proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME,
Kweku Adams983829f2017-12-06 14:53:50 -08001270 (mBoundApplication != null) ? mBoundApplication.processName : "unknown");
1271 dumpMemInfoTable(proto, memInfo, dumpDalvik, dumpSummaryOnly,
1272 nativeMax, nativeAllocated, nativeFree,
1273 dalvikMax, dalvikAllocated, dalvikFree);
1274 proto.end(mToken);
1275
Yi Jin2b30f322018-02-20 15:41:47 -08001276 final long oToken = proto.start(MemInfoDumpProto.AppData.OBJECTS);
1277 proto.write(MemInfoDumpProto.AppData.ObjectStats.VIEW_INSTANCE_COUNT,
1278 viewInstanceCount);
1279 proto.write(MemInfoDumpProto.AppData.ObjectStats.VIEW_ROOT_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001280 viewRootInstanceCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001281 proto.write(MemInfoDumpProto.AppData.ObjectStats.APP_CONTEXT_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001282 appContextInstanceCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001283 proto.write(MemInfoDumpProto.AppData.ObjectStats.ACTIVITY_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001284 activityInstanceCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001285 proto.write(MemInfoDumpProto.AppData.ObjectStats.GLOBAL_ASSET_COUNT,
1286 globalAssetCount);
1287 proto.write(MemInfoDumpProto.AppData.ObjectStats.GLOBAL_ASSET_MANAGER_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001288 globalAssetManagerCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001289 proto.write(MemInfoDumpProto.AppData.ObjectStats.LOCAL_BINDER_OBJECT_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001290 binderLocalObjectCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001291 proto.write(MemInfoDumpProto.AppData.ObjectStats.PROXY_BINDER_OBJECT_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001292 binderProxyObjectCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001293 proto.write(MemInfoDumpProto.AppData.ObjectStats.PARCEL_MEMORY_KB,
1294 parcelSize / 1024);
1295 proto.write(MemInfoDumpProto.AppData.ObjectStats.PARCEL_COUNT, parcelCount);
1296 proto.write(MemInfoDumpProto.AppData.ObjectStats.BINDER_OBJECT_DEATH_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001297 binderDeathObjectCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001298 proto.write(MemInfoDumpProto.AppData.ObjectStats.OPEN_SSL_SOCKET_COUNT,
1299 openSslSocketCount);
1300 proto.write(MemInfoDumpProto.AppData.ObjectStats.WEBVIEW_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001301 webviewInstanceCount);
1302 proto.end(oToken);
1303
1304 // SQLite mem info
Yi Jin2b30f322018-02-20 15:41:47 -08001305 final long sToken = proto.start(MemInfoDumpProto.AppData.SQL);
1306 proto.write(MemInfoDumpProto.AppData.SqlStats.MEMORY_USED_KB,
1307 stats.memoryUsed / 1024);
1308 proto.write(MemInfoDumpProto.AppData.SqlStats.PAGECACHE_OVERFLOW_KB,
Kweku Adams983829f2017-12-06 14:53:50 -08001309 stats.pageCacheOverflow / 1024);
Yi Jin2b30f322018-02-20 15:41:47 -08001310 proto.write(MemInfoDumpProto.AppData.SqlStats.MALLOC_SIZE_KB,
1311 stats.largestMemAlloc / 1024);
Kweku Adams983829f2017-12-06 14:53:50 -08001312 int n = stats.dbStats.size();
1313 for (int i = 0; i < n; i++) {
1314 DbStats dbStats = stats.dbStats.get(i);
1315
Yi Jin2b30f322018-02-20 15:41:47 -08001316 final long dToken = proto.start(MemInfoDumpProto.AppData.SqlStats.DATABASES);
1317 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.NAME, dbStats.dbName);
1318 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.PAGE_SIZE, dbStats.pageSize);
1319 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.DB_SIZE, dbStats.dbSize);
1320 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.LOOKASIDE_B,
1321 dbStats.lookaside);
1322 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.CACHE, dbStats.cache);
Kweku Adams983829f2017-12-06 14:53:50 -08001323 proto.end(dToken);
1324 }
1325 proto.end(sToken);
1326
1327 // Asset details.
1328 String assetAlloc = AssetManager.getAssetAllocations();
1329 if (assetAlloc != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08001330 proto.write(MemInfoDumpProto.AppData.ASSET_ALLOCATIONS, assetAlloc);
Kweku Adams983829f2017-12-06 14:53:50 -08001331 }
1332
1333 // Unreachable native memory
1334 if (dumpUnreachable) {
1335 int flags = mBoundApplication == null ? 0 : mBoundApplication.appInfo.flags;
1336 boolean showContents = (flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0
1337 || android.os.Build.IS_DEBUGGABLE;
Yi Jin2b30f322018-02-20 15:41:47 -08001338 proto.write(MemInfoDumpProto.AppData.UNREACHABLE_MEMORY,
Kweku Adams983829f2017-12-06 14:53:50 -08001339 Debug.getUnreachableMemory(100, showContents));
1340 }
1341 }
1342
1343 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001344 public void dumpGfxInfo(ParcelFileDescriptor pfd, String[] args) {
Chris Craikfc294242016-12-13 18:10:46 -08001345 nDumpGraphicsInfo(pfd.getFileDescriptor());
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001346 WindowManagerGlobal.getInstance().dumpGfxInfo(pfd.getFileDescriptor(), args);
1347 IoUtils.closeQuietly(pfd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 }
1349
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001350 private void dumpDatabaseInfo(ParcelFileDescriptor pfd, String[] args) {
1351 PrintWriter pw = new FastPrintWriter(
1352 new FileOutputStream(pfd.getFileDescriptor()));
Jeff Brown6754ba22011-12-14 20:20:01 -08001353 PrintWriterPrinter printer = new PrintWriterPrinter(pw);
1354 SQLiteDebug.dump(printer, args);
1355 pw.flush();
1356 }
1357
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001358 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001359 public void dumpDbInfo(final ParcelFileDescriptor pfd, final String[] args) {
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001360 if (mSystemThread) {
Felipe Leme29de4922016-06-07 16:14:07 -07001361 // Ensure this invocation is asynchronous to prevent writer waiting if buffer cannot
1362 // be consumed. But it must duplicate the file descriptor first, since caller might
1363 // be closing it.
1364 final ParcelFileDescriptor dup;
1365 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001366 dup = pfd.dup();
Felipe Leme29de4922016-06-07 16:14:07 -07001367 } catch (IOException e) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001368 Log.w(TAG, "Could not dup FD " + pfd.getFileDescriptor().getInt$());
Felipe Leme29de4922016-06-07 16:14:07 -07001369 return;
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001370 } finally {
1371 IoUtils.closeQuietly(pfd);
Felipe Leme29de4922016-06-07 16:14:07 -07001372 }
1373
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001374 AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
1375 @Override
1376 public void run() {
Felipe Lemec74972f2016-06-08 09:12:37 -07001377 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001378 dumpDatabaseInfo(dup, args);
Felipe Lemec74972f2016-06-08 09:12:37 -07001379 } finally {
1380 IoUtils.closeQuietly(dup);
1381 }
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001382 }
1383 });
1384 } else {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001385 dumpDatabaseInfo(pfd, args);
1386 IoUtils.closeQuietly(pfd);
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001387 }
1388 }
1389
1390 @Override
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001391 public void unstableProviderDied(IBinder provider) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001392 sendMessage(H.UNSTABLE_PROVIDER_DIED, provider);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001393 }
1394
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001395 @Override
Adam Skorydfc7fd72013-08-05 19:23:41 -07001396 public void requestAssistContextExtras(IBinder activityToken, IBinder requestToken,
Svet Ganovfd31f852017-04-26 15:54:27 -07001397 int requestType, int sessionId, int flags) {
Adam Skorydfc7fd72013-08-05 19:23:41 -07001398 RequestAssistContextExtras cmd = new RequestAssistContextExtras();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001399 cmd.activityToken = activityToken;
1400 cmd.requestToken = requestToken;
1401 cmd.requestType = requestType;
Amith Yamasani4f128e42016-05-10 11:44:12 -07001402 cmd.sessionId = sessionId;
Svet Ganovfd31f852017-04-26 15:54:27 -07001403 cmd.flags = flags;
Jeff Brown9ef09972013-10-15 20:49:59 -07001404 sendMessage(H.REQUEST_ASSIST_CONTEXT_EXTRAS, cmd);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001405 }
1406
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08001407 public void setCoreSettings(Bundle coreSettings) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001408 sendMessage(H.SET_CORE_SETTINGS, coreSettings);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001409 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001410
1411 public void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) {
1412 UpdateCompatibilityData ucd = new UpdateCompatibilityData();
1413 ucd.pkg = pkg;
1414 ucd.info = info;
Jeff Brown9ef09972013-10-15 20:49:59 -07001415 sendMessage(H.UPDATE_PACKAGE_COMPATIBILITY_INFO, ucd);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001416 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001417
1418 public void scheduleTrimMemory(int level) {
Jorim Jaggib29e3182018-04-30 18:51:56 +02001419 final Runnable r = PooledLambda.obtainRunnable(ActivityThread::handleTrimMemory,
1420 ActivityThread.this, level);
1421 // Schedule trimming memory after drawing the frame to minimize jank-risk.
1422 Choreographer choreographer = Choreographer.getMainThreadInstance();
1423 if (choreographer != null) {
1424 choreographer.postCallback(Choreographer.CALLBACK_COMMIT, r, null);
1425 } else {
1426 mH.post(r);
1427 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001428 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001429
Craig Mautner5eda9b32013-07-02 11:58:16 -07001430 public void scheduleTranslucentConversionComplete(IBinder token, boolean drawComplete) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001431 sendMessage(H.TRANSLUCENT_CONVERSION_COMPLETE, token, drawComplete ? 1 : 0);
Craig Mautner5eda9b32013-07-02 11:58:16 -07001432 }
Dianne Hackborna413dc02013-07-12 12:02:55 -07001433
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001434 public void scheduleOnNewActivityOptions(IBinder token, Bundle options) {
Craig Mautnereb8abf72014-07-02 15:04:09 -07001435 sendMessage(H.ON_NEW_ACTIVITY_OPTIONS,
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001436 new Pair<IBinder, ActivityOptions>(token, ActivityOptions.fromBundle(options)));
Craig Mautnereb8abf72014-07-02 15:04:09 -07001437 }
1438
Dianne Hackborna413dc02013-07-12 12:02:55 -07001439 public void setProcessState(int state) {
1440 updateProcessState(state, true);
1441 }
1442
1443 public void updateProcessState(int processState, boolean fromIpc) {
1444 synchronized (this) {
1445 if (mLastProcessState != processState) {
1446 mLastProcessState = processState;
Mathieu Chartier1e370902013-07-18 10:58:01 -07001447 // Update Dalvik state based on ActivityManager.PROCESS_STATE_* constants.
1448 final int DALVIK_PROCESS_STATE_JANK_PERCEPTIBLE = 0;
1449 final int DALVIK_PROCESS_STATE_JANK_IMPERCEPTIBLE = 1;
1450 int dalvikProcessState = DALVIK_PROCESS_STATE_JANK_IMPERCEPTIBLE;
1451 // TODO: Tune this since things like gmail sync are important background but not jank perceptible.
1452 if (processState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
1453 dalvikProcessState = DALVIK_PROCESS_STATE_JANK_PERCEPTIBLE;
1454 }
1455 VMRuntime.getRuntime().updateProcessState(dalvikProcessState);
Dianne Hackborna413dc02013-07-12 12:02:55 -07001456 if (false) {
1457 Slog.i(TAG, "******************* PROCESS STATE CHANGED TO: " + processState
1458 + (fromIpc ? " (from ipc": ""));
1459 }
1460 }
1461 }
1462 }
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001463
Sudheer Shanka84a48952017-03-08 18:19:01 -08001464 /**
1465 * Updates {@link #mNetworkBlockSeq}. This is used by ActivityManagerService to inform
1466 * the main thread that it needs to wait for the network rules to get updated before
1467 * launching an activity.
1468 */
1469 @Override
1470 public void setNetworkBlockSeq(long procStateSeq) {
1471 synchronized (mNetworkPolicyLock) {
1472 mNetworkBlockSeq = procStateSeq;
1473 }
1474 }
1475
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001476 @Override
1477 public void scheduleInstallProvider(ProviderInfo provider) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001478 sendMessage(H.INSTALL_PROVIDER, provider);
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001479 }
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001480
1481 @Override
Neil Fullerb7146fe2016-11-15 16:52:15 +00001482 public final void updateTimePrefs(int timeFormatPreference) {
1483 final Boolean timeFormatPreferenceBool;
1484 // For convenience we are using the Intent extra values.
1485 if (timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_12_HOUR) {
1486 timeFormatPreferenceBool = Boolean.FALSE;
1487 } else if (timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_24_HOUR) {
1488 timeFormatPreferenceBool = Boolean.TRUE;
1489 } else {
1490 // timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_LOCALE_DEFAULT
1491 // (or unknown).
1492 timeFormatPreferenceBool = null;
1493 }
1494 DateFormat.set24HourTimePref(timeFormatPreferenceBool);
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001495 }
Craig Mautneree2e45a2014-06-27 12:10:03 -07001496
1497 @Override
Craig Mautner8746a472014-07-24 15:12:54 -07001498 public void scheduleEnterAnimationComplete(IBinder token) {
1499 sendMessage(H.ENTER_ANIMATION_COMPLETE, token);
1500 }
Jeff Sharkey605eb792014-11-04 13:34:06 -08001501
1502 @Override
1503 public void notifyCleartextNetwork(byte[] firstPacket) {
1504 if (StrictMode.vmCleartextNetworkEnabled()) {
1505 StrictMode.onCleartextNetworkDetected(firstPacket);
1506 }
1507 }
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001508
1509 @Override
1510 public void startBinderTracking() {
1511 sendMessage(H.START_BINDER_TRACKING, null);
1512 }
1513
1514 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001515 public void stopBinderTrackingAndDump(ParcelFileDescriptor pfd) {
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001516 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001517 sendMessage(H.STOP_BINDER_TRACKING_AND_DUMP, pfd.dup());
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001518 } catch (IOException e) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001519 } finally {
1520 IoUtils.closeQuietly(pfd);
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001521 }
1522 }
Wale Ogunwale5f986092015-12-04 15:35:38 -08001523
1524 @Override
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001525 public void scheduleLocalVoiceInteractionStarted(IBinder token,
1526 IVoiceInteractor voiceInteractor) throws RemoteException {
1527 SomeArgs args = SomeArgs.obtain();
1528 args.arg1 = token;
1529 args.arg2 = voiceInteractor;
1530 sendMessage(H.LOCAL_VOICE_INTERACTION_STARTED, args);
1531 }
Chad Brubakerc72875b2016-04-27 16:35:11 -07001532
1533 @Override
1534 public void handleTrustStorageUpdate() {
1535 NetworkSecurityPolicy.getInstance().handleTrustStorageUpdate();
1536 }
Andrii Kulian446e8242017-10-26 15:17:29 -07001537
1538 @Override
1539 public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
1540 ActivityThread.this.scheduleTransaction(transaction);
1541 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 }
1543
Andrii Kulian446e8242017-10-26 15:17:29 -07001544 @Override
1545 public void updatePendingConfiguration(Configuration config) {
1546 mAppThread.updatePendingConfiguration(config);
1547 }
1548
1549 @Override
1550 public void updateProcessState(int processState, boolean fromIpc) {
1551 mAppThread.updateProcessState(processState, fromIpc);
1552 }
1553
Andrii Kulian446e8242017-10-26 15:17:29 -07001554 class H extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 public static final int BIND_APPLICATION = 110;
1556 public static final int EXIT_APPLICATION = 111;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 public static final int RECEIVER = 113;
1558 public static final int CREATE_SERVICE = 114;
1559 public static final int SERVICE_ARGS = 115;
1560 public static final int STOP_SERVICE = 116;
Dianne Hackborn09233282014-04-30 11:33:59 -07001561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 public static final int CONFIGURATION_CHANGED = 118;
1563 public static final int CLEAN_UP_CONTEXT = 119;
1564 public static final int GC_WHEN_IDLE = 120;
1565 public static final int BIND_SERVICE = 121;
1566 public static final int UNBIND_SERVICE = 122;
1567 public static final int DUMP_SERVICE = 123;
1568 public static final int LOW_MEMORY = 124;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001569 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001570 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001571 public static final int DESTROY_BACKUP_AGENT = 129;
1572 public static final int SUICIDE = 130;
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001573 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001574 public static final int ENABLE_JIT = 132;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001575 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001576 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -07001577 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001578 public static final int DUMP_ACTIVITY = 136;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001579 public static final int SLEEPING = 137;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001580 public static final int SET_CORE_SETTINGS = 138;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001581 public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001582 public static final int DUMP_PROVIDER = 141;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001583 public static final int UNSTABLE_PROVIDER_DIED = 142;
Adam Skorydfc7fd72013-08-05 19:23:41 -07001584 public static final int REQUEST_ASSIST_CONTEXT_EXTRAS = 143;
Craig Mautner5eda9b32013-07-02 11:58:16 -07001585 public static final int TRANSLUCENT_CONVERSION_COMPLETE = 144;
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001586 public static final int INSTALL_PROVIDER = 145;
Craig Mautnereb8abf72014-07-02 15:04:09 -07001587 public static final int ON_NEW_ACTIVITY_OPTIONS = 146;
Craig Mautner8746a472014-07-24 15:12:54 -07001588 public static final int ENTER_ANIMATION_COMPLETE = 149;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001589 public static final int START_BINDER_TRACKING = 150;
1590 public static final int STOP_BINDER_TRACKING_AND_DUMP = 151;
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001591 public static final int LOCAL_VOICE_INTERACTION_STARTED = 154;
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001592 public static final int ATTACH_AGENT = 155;
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001593 public static final int APPLICATION_INFO_CHANGED = 156;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001594 public static final int RUN_ISOLATED_ENTRY_POINT = 158;
Andrii Kulian446e8242017-10-26 15:17:29 -07001595 public static final int EXECUTE_TRANSACTION = 159;
Andrii Kulian320e3b52018-05-03 16:26:25 -07001596 public static final int RELAUNCH_ACTIVITY = 160;
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001599 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 switch (code) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 case BIND_APPLICATION: return "BIND_APPLICATION";
1602 case EXIT_APPLICATION: return "EXIT_APPLICATION";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 case RECEIVER: return "RECEIVER";
1604 case CREATE_SERVICE: return "CREATE_SERVICE";
1605 case SERVICE_ARGS: return "SERVICE_ARGS";
1606 case STOP_SERVICE: return "STOP_SERVICE";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1608 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1609 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1610 case BIND_SERVICE: return "BIND_SERVICE";
1611 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1612 case DUMP_SERVICE: return "DUMP_SERVICE";
1613 case LOW_MEMORY: return "LOW_MEMORY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001614 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001615 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1616 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001617 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001618 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001619 case ENABLE_JIT: return "ENABLE_JIT";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001620 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001621 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -07001622 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -07001623 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001624 case SLEEPING: return "SLEEPING";
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001625 case SET_CORE_SETTINGS: return "SET_CORE_SETTINGS";
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001626 case UPDATE_PACKAGE_COMPATIBILITY_INFO: return "UPDATE_PACKAGE_COMPATIBILITY_INFO";
Marco Nelissen18cb2872011-11-15 11:19:53 -08001627 case DUMP_PROVIDER: return "DUMP_PROVIDER";
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001628 case UNSTABLE_PROVIDER_DIED: return "UNSTABLE_PROVIDER_DIED";
Adam Skorydfc7fd72013-08-05 19:23:41 -07001629 case REQUEST_ASSIST_CONTEXT_EXTRAS: return "REQUEST_ASSIST_CONTEXT_EXTRAS";
Craig Mautner5eda9b32013-07-02 11:58:16 -07001630 case TRANSLUCENT_CONVERSION_COMPLETE: return "TRANSLUCENT_CONVERSION_COMPLETE";
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001631 case INSTALL_PROVIDER: return "INSTALL_PROVIDER";
Craig Mautnereb8abf72014-07-02 15:04:09 -07001632 case ON_NEW_ACTIVITY_OPTIONS: return "ON_NEW_ACTIVITY_OPTIONS";
Craig Mautner8746a472014-07-24 15:12:54 -07001633 case ENTER_ANIMATION_COMPLETE: return "ENTER_ANIMATION_COMPLETE";
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001634 case LOCAL_VOICE_INTERACTION_STARTED: return "LOCAL_VOICE_INTERACTION_STARTED";
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001635 case ATTACH_AGENT: return "ATTACH_AGENT";
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001636 case APPLICATION_INFO_CHANGED: return "APPLICATION_INFO_CHANGED";
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001637 case RUN_ISOLATED_ENTRY_POINT: return "RUN_ISOLATED_ENTRY_POINT";
Andrii Kulian446e8242017-10-26 15:17:29 -07001638 case EXECUTE_TRANSACTION: return "EXECUTE_TRANSACTION";
Andrii Kulian320e3b52018-05-03 16:26:25 -07001639 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 }
1641 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001642 return Integer.toString(code);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 }
1644 public void handleMessage(Message msg) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001645 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 switch (msg.what) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 case BIND_APPLICATION:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001648 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 AppBindData data = (AppBindData)msg.obj;
1650 handleBindApplication(data);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001651 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 break;
1653 case EXIT_APPLICATION:
1654 if (mInitialApplication != null) {
1655 mInitialApplication.onTerminate();
1656 }
1657 Looper.myLooper().quit();
1658 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 case RECEIVER:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001660 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveComp");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 handleReceiver((ReceiverData)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;
1664 case CREATE_SERVICE:
Tim Murrayb6f5a422016-04-07 15:25:22 -07001665 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceCreate: " + String.valueOf(msg.obj)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 handleCreateService((CreateServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001667 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 break;
1669 case BIND_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001670 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 handleBindService((BindServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001672 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 break;
1674 case UNBIND_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001675 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceUnbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 handleUnbindService((BindServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001677 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 break;
1679 case SERVICE_ARGS:
Tim Murrayb6f5a422016-04-07 15:25:22 -07001680 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceStart: " + String.valueOf(msg.obj)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 handleServiceArgs((ServiceArgsData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001682 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 break;
1684 case STOP_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001685 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 handleStopService((IBinder)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001687 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 case CONFIGURATION_CHANGED:
Andrii Kulian446e8242017-10-26 15:17:29 -07001690 handleConfigurationChanged((Configuration) msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 break;
1692 case CLEAN_UP_CONTEXT:
1693 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1694 cci.context.performFinalCleanup(cci.who, cci.what);
1695 break;
1696 case GC_WHEN_IDLE:
1697 scheduleGcIdler();
1698 break;
1699 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001700 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 break;
1702 case LOW_MEMORY:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001703 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "lowMemory");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 handleLowMemory();
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001705 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001707 case PROFILER_CONTROL:
Jeff Hao1b012d32014-08-20 10:35:34 -07001708 handleProfilerControl(msg.arg1 != 0, (ProfilerInfo)msg.obj, msg.arg2);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001709 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001710 case CREATE_BACKUP_AGENT:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001711 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupCreateAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001712 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001713 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate181fafa2009-05-14 11:12:14 -07001714 break;
1715 case DESTROY_BACKUP_AGENT:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001716 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupDestroyAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001717 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001718 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate181fafa2009-05-14 11:12:14 -07001719 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001720 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001721 Process.killProcess(Process.myPid());
1722 break;
1723 case REMOVE_PROVIDER:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001724 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "providerRemove");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001725 completeRemoveProvider((ProviderRefCount)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001726 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001727 break;
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001728 case ENABLE_JIT:
1729 ensureJitEnabled();
1730 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001731 case DISPATCH_PACKAGE_BROADCAST:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001732 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastPackage");
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001733 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001734 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001735 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001736 case SCHEDULE_CRASH:
1737 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001738 case DUMP_HEAP:
Christopher Ferris8d652f82017-04-11 16:29:18 -07001739 handleDumpHeap((DumpHeapData) msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001740 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001741 case DUMP_ACTIVITY:
1742 handleDumpActivity((DumpComponentInfo)msg.obj);
1743 break;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001744 case DUMP_PROVIDER:
1745 handleDumpProvider((DumpComponentInfo)msg.obj);
1746 break;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001747 case SLEEPING:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001748 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "sleeping");
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001749 handleSleeping((IBinder)msg.obj, msg.arg1 != 0);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001750 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001751 break;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001752 case SET_CORE_SETTINGS:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001753 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setCoreSettings");
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001754 handleSetCoreSettings((Bundle) msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001755 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001756 break;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001757 case UPDATE_PACKAGE_COMPATIBILITY_INFO:
1758 handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001759 break;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001760 case UNSTABLE_PROVIDER_DIED:
1761 handleUnstableProviderDied((IBinder)msg.obj, false);
1762 break;
Adam Skorydfc7fd72013-08-05 19:23:41 -07001763 case REQUEST_ASSIST_CONTEXT_EXTRAS:
1764 handleRequestAssistContextExtras((RequestAssistContextExtras)msg.obj);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001765 break;
Craig Mautner5eda9b32013-07-02 11:58:16 -07001766 case TRANSLUCENT_CONVERSION_COMPLETE:
1767 handleTranslucentConversionComplete((IBinder)msg.obj, msg.arg1 == 1);
1768 break;
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001769 case INSTALL_PROVIDER:
1770 handleInstallProvider((ProviderInfo) msg.obj);
1771 break;
Craig Mautnereb8abf72014-07-02 15:04:09 -07001772 case ON_NEW_ACTIVITY_OPTIONS:
1773 Pair<IBinder, ActivityOptions> pair = (Pair<IBinder, ActivityOptions>) msg.obj;
1774 onNewActivityOptions(pair.first, pair.second);
Dake Gu7ef70b02014-07-08 18:37:12 -07001775 break;
Craig Mautner8746a472014-07-24 15:12:54 -07001776 case ENTER_ANIMATION_COMPLETE:
1777 handleEnterAnimationComplete((IBinder) msg.obj);
1778 break;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001779 case START_BINDER_TRACKING:
1780 handleStartBinderTracking();
1781 break;
1782 case STOP_BINDER_TRACKING_AND_DUMP:
1783 handleStopBinderTrackingAndDump((ParcelFileDescriptor) msg.obj);
1784 break;
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001785 case LOCAL_VOICE_INTERACTION_STARTED:
1786 handleLocalVoiceInteractionStarted((IBinder) ((SomeArgs) msg.obj).arg1,
1787 (IVoiceInteractor) ((SomeArgs) msg.obj).arg2);
Amith Yamasani61019112017-01-10 15:05:00 -08001788 break;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08001789 case ATTACH_AGENT: {
1790 Application app = getApplication();
1791 handleAttachAgent((String) msg.obj, app != null ? app.mLoadedApk : null);
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001792 break;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08001793 }
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001794 case APPLICATION_INFO_CHANGED:
1795 mUpdatingSystemConfig = true;
1796 try {
1797 handleApplicationInfoChanged((ApplicationInfo) msg.obj);
1798 } finally {
1799 mUpdatingSystemConfig = false;
1800 }
1801 break;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001802 case RUN_ISOLATED_ENTRY_POINT:
1803 handleRunIsolatedEntryPoint((String) ((SomeArgs) msg.obj).arg1,
1804 (String[]) ((SomeArgs) msg.obj).arg2);
1805 break;
Andrii Kulian446e8242017-10-26 15:17:29 -07001806 case EXECUTE_TRANSACTION:
Andrii Kulian04470682018-01-10 15:32:31 -08001807 final ClientTransaction transaction = (ClientTransaction) msg.obj;
1808 mTransactionExecutor.execute(transaction);
1809 if (isSystem()) {
1810 // Client transactions inside system process are recycled on the client side
1811 // instead of ClientLifecycleManager to avoid being cleared before this
1812 // message is handled.
1813 transaction.recycle();
1814 }
Andrii Kulian914aa7d2018-03-19 21:51:53 -07001815 // TODO(lifecycler): Recycle locally scheduled transactions.
Andrii Kulian446e8242017-10-26 15:17:29 -07001816 break;
Andrii Kulian320e3b52018-05-03 16:26:25 -07001817 case RELAUNCH_ACTIVITY:
1818 handleRelaunchActivityLocally((IBinder) msg.obj);
1819 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 }
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07001821 Object obj = msg.obj;
1822 if (obj instanceof SomeArgs) {
1823 ((SomeArgs) obj).recycle();
1824 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001825 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 }
1827 }
1828
Romain Guy65b345f2011-07-27 18:51:50 -07001829 private class Idler implements MessageQueue.IdleHandler {
Craig Mautner48d0d182013-06-11 07:53:06 -07001830 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001832 ActivityClientRecord a = mNewActivities;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001833 boolean stopProfiling = false;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001834 if (mBoundApplication != null && mProfiler.profileFd != null
1835 && mProfiler.autoStopProfiler) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001836 stopProfiling = true;
1837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 if (a != null) {
1839 mNewActivities = null;
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001840 IActivityManager am = ActivityManager.getService();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001841 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001843 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 TAG, "Reporting idle of " + a +
1845 " finished=" +
Romain Guy65b345f2011-07-27 18:51:50 -07001846 (a.activity != null && a.activity.mFinished));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847 if (a.activity != null && !a.activity.mFinished) {
1848 try {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001849 am.activityIdle(a.token, a.createdConfig, stopProfiling);
Dianne Hackborne88846e2009-09-30 21:34:25 -07001850 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001852 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 }
1854 }
1855 prev = a;
1856 a = a.nextIdle;
1857 prev.nextIdle = null;
1858 } while (a != null);
1859 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001860 if (stopProfiling) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001861 mProfiler.stopProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001862 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08001863 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 return false;
1865 }
1866 }
1867
1868 final class GcIdler implements MessageQueue.IdleHandler {
Craig Mautner48d0d182013-06-11 07:53:06 -07001869 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 public final boolean queueIdle() {
1871 doGcIfNeeded();
1872 return false;
1873 }
1874 }
1875
Romain Guy65b345f2011-07-27 18:51:50 -07001876 public static ActivityThread currentActivityThread() {
Jeff Sharkey66a017b2013-01-17 18:18:22 -08001877 return sCurrentActivityThread;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879
Wale Ogunwale9a6ef1e2015-06-02 13:41:00 -07001880 public static boolean isSystem() {
1881 return (sCurrentActivityThread != null) ? sCurrentActivityThread.mSystemThread : false;
1882 }
1883
Svetoslavfbf0eca2015-05-01 16:52:41 -07001884 public static String currentOpPackageName() {
1885 ActivityThread am = currentActivityThread();
1886 return (am != null && am.getApplication() != null)
1887 ? am.getApplication().getOpPackageName() : null;
1888 }
1889
Romain Guy65b345f2011-07-27 18:51:50 -07001890 public static String currentPackageName() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001891 ActivityThread am = currentActivityThread();
1892 return (am != null && am.mBoundApplication != null)
Dianne Hackbornb57a50b2013-04-11 17:29:32 -07001893 ? am.mBoundApplication.appInfo.packageName : null;
1894 }
1895
1896 public static String currentProcessName() {
1897 ActivityThread am = currentActivityThread();
1898 return (am != null && am.mBoundApplication != null)
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001899 ? am.mBoundApplication.processName : null;
1900 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901
Romain Guy65b345f2011-07-27 18:51:50 -07001902 public static Application currentApplication() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001903 ActivityThread am = currentActivityThread();
1904 return am != null ? am.mInitialApplication : null;
1905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001907 public static IPackageManager getPackageManager() {
1908 if (sPackageManager != null) {
1909 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
1910 return sPackageManager;
1911 }
1912 IBinder b = ServiceManager.getService("package");
1913 //Slog.v("PackageManager", "default service binder = " + b);
1914 sPackageManager = IPackageManager.Stub.asInterface(b);
1915 //Slog.v("PackageManager", "default service = " + sPackageManager);
1916 return sPackageManager;
1917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001918
Romain Guy65b345f2011-07-27 18:51:50 -07001919 private Configuration mMainThreadConfig = new Configuration();
Amith Yamasani4f128e42016-05-10 11:44:12 -07001920
Dianne Hackborn908aecc2012-07-31 16:37:34 -07001921 Configuration applyConfigCompatMainThread(int displayDensity, Configuration config,
1922 CompatibilityInfo compat) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001923 if (config == null) {
1924 return null;
1925 }
Craig Mautner48d0d182013-06-11 07:53:06 -07001926 if (!compat.supportsScreen()) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001927 mMainThreadConfig.setTo(config);
1928 config = mMainThreadConfig;
Dianne Hackborn908aecc2012-07-31 16:37:34 -07001929 compat.applyToConfiguration(displayDensity, config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001930 }
1931 return config;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001934 /**
Todd Kennedy39bfee52016-02-24 10:28:21 -08001935 * Creates the top level resources for the given package. Will return an existing
1936 * Resources if one has already been created.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001937 */
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07001938 Resources getTopLevelResources(String resDir, String[] splitResDirs, String[] overlayDirs,
Adam Lesinski082614c2016-03-04 14:33:47 -08001939 String[] libDirs, int displayId, LoadedApk pkgInfo) {
1940 return mResourcesManager.getResources(null, resDir, splitResDirs, overlayDirs, libDirs,
1941 displayId, null, pkgInfo.getCompatibilityInfo(), pkgInfo.getClassLoader());
Todd Kennedy39bfee52016-02-24 10:28:21 -08001942 }
1943
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001944 final Handler getHandler() {
1945 return mH;
1946 }
1947
Todd Kennedy233a0b12018-01-29 20:30:24 +00001948 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
1949 int flags) {
1950 return getPackageInfo(packageName, compatInfo, flags, UserHandle.myUserId());
Amith Yamasani98edc952012-09-25 14:09:27 -07001951 }
1952
Todd Kennedy233a0b12018-01-29 20:30:24 +00001953 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
1954 int flags, int userId) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07001955 final boolean differentUser = (UserHandle.myUserId() != userId);
Craig Mautner88c05892013-06-28 09:47:45 -07001956 synchronized (mResourcesManager) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001957 WeakReference<LoadedApk> ref;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07001958 if (differentUser) {
1959 // Caching not supported across users
1960 ref = null;
1961 } else if ((flags & Context.CONTEXT_INCLUDE_CODE) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 ref = mPackages.get(packageName);
1963 } else {
1964 ref = mResourcePackages.get(packageName);
1965 }
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07001966
Todd Kennedy233a0b12018-01-29 20:30:24 +00001967 LoadedApk packageInfo = ref != null ? ref.get() : null;
1968 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
1969 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
1970 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
1971 if (packageInfo != null && (packageInfo.mResources == null
1972 || packageInfo.mResources.getAssets().isUpToDate())) {
1973 if (packageInfo.isSecurityViolation()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
1975 throw new SecurityException(
1976 "Requesting code from " + packageName
1977 + " to be run in process "
1978 + mBoundApplication.processName
1979 + "/" + mBoundApplication.appInfo.uid);
1980 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00001981 return packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 }
1983 }
1984
1985 ApplicationInfo ai = null;
1986 try {
1987 ai = getPackageManager().getApplicationInfo(packageName,
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001988 PackageManager.GET_SHARED_LIBRARY_FILES
1989 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1990 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001992 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 }
1994
1995 if (ai != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00001996 return getPackageInfo(ai, compatInfo, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 }
1998
1999 return null;
2000 }
2001
Todd Kennedy233a0b12018-01-29 20:30:24 +00002002 public final LoadedApk getPackageInfo(ApplicationInfo ai, CompatibilityInfo compatInfo,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002003 int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
2005 boolean securityViolation = includeCode && ai.uid != 0
2006 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002007 ? !UserHandle.isSameApp(ai.uid, mBoundApplication.appInfo.uid)
Amith Yamasani742a6712011-05-04 14:49:28 -07002008 : true);
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002009 boolean registerPackage = includeCode && (flags&Context.CONTEXT_REGISTER_PACKAGE) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 if ((flags&(Context.CONTEXT_INCLUDE_CODE
2011 |Context.CONTEXT_IGNORE_SECURITY))
2012 == Context.CONTEXT_INCLUDE_CODE) {
2013 if (securityViolation) {
2014 String msg = "Requesting code from " + ai.packageName
2015 + " (with uid " + ai.uid + ")";
2016 if (mBoundApplication != null) {
2017 msg = msg + " to be run in process "
2018 + mBoundApplication.processName + " (with uid "
2019 + mBoundApplication.appInfo.uid + ")";
2020 }
2021 throw new SecurityException(msg);
2022 }
2023 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00002024 return getPackageInfo(ai, compatInfo, null, securityViolation, includeCode,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002025 registerPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 }
2027
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002028 @Override
Todd Kennedy233a0b12018-01-29 20:30:24 +00002029 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002030 CompatibilityInfo compatInfo) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002031 return getPackageInfo(ai, compatInfo, null, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 }
2033
Todd Kennedy233a0b12018-01-29 20:30:24 +00002034 public final LoadedApk peekPackageInfo(String packageName, boolean includeCode) {
Craig Mautner88c05892013-06-28 09:47:45 -07002035 synchronized (mResourcesManager) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002036 WeakReference<LoadedApk> ref;
2037 if (includeCode) {
2038 ref = mPackages.get(packageName);
2039 } else {
2040 ref = mResourcePackages.get(packageName);
2041 }
2042 return ref != null ? ref.get() : null;
2043 }
2044 }
2045
Todd Kennedy233a0b12018-01-29 20:30:24 +00002046 private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002047 ClassLoader baseLoader, boolean securityViolation, boolean includeCode,
2048 boolean registerPackage) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002049 final boolean differentUser = (UserHandle.myUserId() != UserHandle.getUserId(aInfo.uid));
Craig Mautner88c05892013-06-28 09:47:45 -07002050 synchronized (mResourcesManager) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002051 WeakReference<LoadedApk> ref;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002052 if (differentUser) {
2053 // Caching not supported across users
2054 ref = null;
2055 } else if (includeCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 ref = mPackages.get(aInfo.packageName);
2057 } else {
2058 ref = mResourcePackages.get(aInfo.packageName);
2059 }
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002060
Todd Kennedy233a0b12018-01-29 20:30:24 +00002061 LoadedApk packageInfo = ref != null ? ref.get() : null;
2062 if (packageInfo == null || (packageInfo.mResources != null
2063 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002064 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 : "Loading resource-only package ") + aInfo.packageName
2066 + " (in " + (mBoundApplication != null
2067 ? mBoundApplication.processName : null)
2068 + ")");
Todd Kennedy233a0b12018-01-29 20:30:24 +00002069 packageInfo =
Jeff Browndefd4a62014-03-10 21:24:37 -07002070 new LoadedApk(this, aInfo, compatInfo, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 securityViolation, includeCode &&
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002072 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0, registerPackage);
Narayan Kamathcb383182014-10-29 17:56:42 +00002073
2074 if (mSystemThread && "android".equals(aInfo.packageName)) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002075 packageInfo.installSystemApplicationInfo(aInfo,
2076 getSystemContext().mPackageInfo.getClassLoader());
Narayan Kamathcb383182014-10-29 17:56:42 +00002077 }
2078
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002079 if (differentUser) {
2080 // Caching not supported across users
2081 } else if (includeCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082 mPackages.put(aInfo.packageName,
Todd Kennedy233a0b12018-01-29 20:30:24 +00002083 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 } else {
2085 mResourcePackages.put(aInfo.packageName,
Todd Kennedy233a0b12018-01-29 20:30:24 +00002086 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 }
2088 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00002089 return packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 }
2091 }
2092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 ActivityThread() {
Craig Mautner88c05892013-06-28 09:47:45 -07002094 mResourcesManager = ResourcesManager.getInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 }
2096
2097 public ApplicationThread getApplicationThread()
2098 {
2099 return mAppThread;
2100 }
2101
2102 public Instrumentation getInstrumentation()
2103 {
2104 return mInstrumentation;
2105 }
2106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 public boolean isProfiling() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002108 return mProfiler != null && mProfiler.profileFile != null
2109 && mProfiler.profileFd == null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 }
2111
2112 public String getProfileFilePath() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002113 return mProfiler.profileFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 }
2115
2116 public Looper getLooper() {
2117 return mLooper;
2118 }
2119
Jeff Sharkey8439ac02017-12-12 17:26:23 -07002120 public Executor getExecutor() {
2121 return mExecutor;
2122 }
2123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 public Application getApplication() {
2125 return mInitialApplication;
2126 }
Bob Leee5408332009-09-04 18:31:17 -07002127
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07002128 public String getProcessName() {
2129 return mBoundApplication.processName;
2130 }
Bob Leee5408332009-09-04 18:31:17 -07002131
Dianne Hackborn21556372010-02-04 16:34:40 -08002132 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133 synchronized (this) {
2134 if (mSystemContext == null) {
Jeff Browndefd4a62014-03-10 21:24:37 -07002135 mSystemContext = ContextImpl.createSystemContext(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002136 }
Jeff Browndefd4a62014-03-10 21:24:37 -07002137 return mSystemContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 }
2140
Adam Lesinskia82b6262017-03-21 16:56:17 -07002141 public ContextImpl getSystemUiContext() {
2142 synchronized (this) {
2143 if (mSystemUiContext == null) {
Adam Lesinski6f1a9172017-04-10 16:35:19 -07002144 mSystemUiContext = ContextImpl.createSystemUiContext(getSystemContext());
Adam Lesinskia82b6262017-03-21 16:56:17 -07002145 }
2146 return mSystemUiContext;
2147 }
2148 }
2149
Narayan Kamath29564cd2014-08-07 10:57:40 +01002150 public void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
Mike Cleron432b7132009-09-24 15:28:29 -07002151 synchronized (this) {
Narayan Kamath29564cd2014-08-07 10:57:40 +01002152 getSystemContext().installSystemApplicationInfo(info, classLoader);
Adam Lesinskia82b6262017-03-21 16:56:17 -07002153 getSystemUiContext().installSystemApplicationInfo(info, classLoader);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002154
2155 // give ourselves a default profiler
2156 mProfiler = new Profiler();
Mike Cleron432b7132009-09-24 15:28:29 -07002157 }
2158 }
2159
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002160 void ensureJitEnabled() {
2161 if (!mJitEnabled) {
2162 mJitEnabled = true;
2163 dalvik.system.VMRuntime.getRuntime().startJitCompilation();
2164 }
2165 }
Craig Mautner48d0d182013-06-11 07:53:06 -07002166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002167 void scheduleGcIdler() {
2168 if (!mGcIdlerScheduled) {
2169 mGcIdlerScheduled = true;
2170 Looper.myQueue().addIdleHandler(mGcIdler);
2171 }
2172 mH.removeMessages(H.GC_WHEN_IDLE);
2173 }
2174
2175 void unscheduleGcIdler() {
2176 if (mGcIdlerScheduled) {
2177 mGcIdlerScheduled = false;
2178 Looper.myQueue().removeIdleHandler(mGcIdler);
2179 }
2180 mH.removeMessages(H.GC_WHEN_IDLE);
2181 }
2182
2183 void doGcIfNeeded() {
2184 mGcIdlerScheduled = false;
2185 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002186 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 // + "m now=" + now);
2188 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002189 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002190 BinderInternal.forceGc("bg");
2191 }
2192 }
2193
Dianne Hackborne77187d2013-10-25 16:32:41 -07002194 private static final String HEAP_FULL_COLUMN
2195 = "%13s %8s %8s %8s %8s %8s %8s %8s %8s %8s %8s";
2196 private static final String HEAP_COLUMN
2197 = "%13s %8s %8s %8s %8s %8s %8s %8s";
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002198 private static final String ONE_COUNT_COLUMN = "%21s %8d";
2199 private static final String TWO_COUNT_COLUMNS = "%21s %8d %21s %8d";
2200 private static final String ONE_COUNT_COLUMN_HEADER = "%21s %8s";
Dianne Hackborne77187d2013-10-25 16:32:41 -07002201
2202 // Formatting for checkin service - update version if row format changes
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002203 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 4;
Dianne Hackborne77187d2013-10-25 16:32:41 -07002204
2205 static void printRow(PrintWriter pw, String format, Object...objs) {
2206 pw.println(String.format(format, objs));
2207 }
2208
2209 public static void dumpMemInfoTable(PrintWriter pw, Debug.MemoryInfo memInfo, boolean checkin,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002210 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
2211 int pid, String processName,
Dianne Hackborne77187d2013-10-25 16:32:41 -07002212 long nativeMax, long nativeAllocated, long nativeFree,
2213 long dalvikMax, long dalvikAllocated, long dalvikFree) {
2214
2215 // For checkin, we print one long comma-separated list of values
2216 if (checkin) {
2217 // NOTE: if you change anything significant below, also consider changing
2218 // ACTIVITY_THREAD_CHECKIN_VERSION.
2219
2220 // Header
2221 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
2222 pw.print(pid); pw.print(',');
2223 pw.print(processName); pw.print(',');
2224
2225 // Heap info - max
2226 pw.print(nativeMax); pw.print(',');
2227 pw.print(dalvikMax); pw.print(',');
2228 pw.print("N/A,");
2229 pw.print(nativeMax + dalvikMax); pw.print(',');
2230
2231 // Heap info - allocated
2232 pw.print(nativeAllocated); pw.print(',');
2233 pw.print(dalvikAllocated); pw.print(',');
2234 pw.print("N/A,");
2235 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
2236
2237 // Heap info - free
2238 pw.print(nativeFree); pw.print(',');
2239 pw.print(dalvikFree); pw.print(',');
2240 pw.print("N/A,");
2241 pw.print(nativeFree + dalvikFree); pw.print(',');
2242
2243 // Heap info - proportional set size
2244 pw.print(memInfo.nativePss); pw.print(',');
2245 pw.print(memInfo.dalvikPss); pw.print(',');
2246 pw.print(memInfo.otherPss); pw.print(',');
2247 pw.print(memInfo.getTotalPss()); pw.print(',');
2248
2249 // Heap info - swappable set size
2250 pw.print(memInfo.nativeSwappablePss); pw.print(',');
2251 pw.print(memInfo.dalvikSwappablePss); pw.print(',');
2252 pw.print(memInfo.otherSwappablePss); pw.print(',');
2253 pw.print(memInfo.getTotalSwappablePss()); pw.print(',');
2254
2255 // Heap info - shared dirty
2256 pw.print(memInfo.nativeSharedDirty); pw.print(',');
2257 pw.print(memInfo.dalvikSharedDirty); pw.print(',');
2258 pw.print(memInfo.otherSharedDirty); pw.print(',');
2259 pw.print(memInfo.getTotalSharedDirty()); pw.print(',');
2260
2261 // Heap info - shared clean
2262 pw.print(memInfo.nativeSharedClean); pw.print(',');
2263 pw.print(memInfo.dalvikSharedClean); pw.print(',');
2264 pw.print(memInfo.otherSharedClean); pw.print(',');
2265 pw.print(memInfo.getTotalSharedClean()); pw.print(',');
2266
2267 // Heap info - private Dirty
2268 pw.print(memInfo.nativePrivateDirty); pw.print(',');
2269 pw.print(memInfo.dalvikPrivateDirty); pw.print(',');
2270 pw.print(memInfo.otherPrivateDirty); pw.print(',');
2271 pw.print(memInfo.getTotalPrivateDirty()); pw.print(',');
2272
2273 // Heap info - private Clean
2274 pw.print(memInfo.nativePrivateClean); pw.print(',');
2275 pw.print(memInfo.dalvikPrivateClean); pw.print(',');
2276 pw.print(memInfo.otherPrivateClean); pw.print(',');
2277 pw.print(memInfo.getTotalPrivateClean()); pw.print(',');
2278
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002279 // Heap info - swapped out
2280 pw.print(memInfo.nativeSwappedOut); pw.print(',');
2281 pw.print(memInfo.dalvikSwappedOut); pw.print(',');
2282 pw.print(memInfo.otherSwappedOut); pw.print(',');
2283 pw.print(memInfo.getTotalSwappedOut()); pw.print(',');
2284
2285 // Heap info - swapped out pss
2286 if (memInfo.hasSwappedOutPss) {
2287 pw.print(memInfo.nativeSwappedOutPss); pw.print(',');
2288 pw.print(memInfo.dalvikSwappedOutPss); pw.print(',');
2289 pw.print(memInfo.otherSwappedOutPss); pw.print(',');
2290 pw.print(memInfo.getTotalSwappedOutPss()); pw.print(',');
2291 } else {
2292 pw.print("N/A,");
2293 pw.print("N/A,");
2294 pw.print("N/A,");
2295 pw.print("N/A,");
2296 }
2297
Dianne Hackborne77187d2013-10-25 16:32:41 -07002298 // Heap info - other areas
2299 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
2300 pw.print(Debug.MemoryInfo.getOtherLabel(i)); pw.print(',');
2301 pw.print(memInfo.getOtherPss(i)); pw.print(',');
2302 pw.print(memInfo.getOtherSwappablePss(i)); pw.print(',');
2303 pw.print(memInfo.getOtherSharedDirty(i)); pw.print(',');
2304 pw.print(memInfo.getOtherSharedClean(i)); pw.print(',');
2305 pw.print(memInfo.getOtherPrivateDirty(i)); pw.print(',');
2306 pw.print(memInfo.getOtherPrivateClean(i)); pw.print(',');
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002307 pw.print(memInfo.getOtherSwappedOut(i)); pw.print(',');
2308 if (memInfo.hasSwappedOutPss) {
2309 pw.print(memInfo.getOtherSwappedOutPss(i)); pw.print(',');
2310 } else {
2311 pw.print("N/A,");
2312 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002313 }
2314 return;
2315 }
2316
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002317 if (!dumpSummaryOnly) {
2318 if (dumpFullInfo) {
2319 printRow(pw, HEAP_FULL_COLUMN, "", "Pss", "Pss", "Shared", "Private",
Martijn Coenene0764852016-01-07 17:04:22 -08002320 "Shared", "Private", memInfo.hasSwappedOutPss ? "SwapPss" : "Swap",
2321 "Heap", "Heap", "Heap");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002322 printRow(pw, HEAP_FULL_COLUMN, "", "Total", "Clean", "Dirty", "Dirty",
Martijn Coenene0764852016-01-07 17:04:22 -08002323 "Clean", "Clean", "Dirty",
2324 "Size", "Alloc", "Free");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002325 printRow(pw, HEAP_FULL_COLUMN, "", "------", "------", "------", "------",
2326 "------", "------", "------", "------", "------", "------");
2327 printRow(pw, HEAP_FULL_COLUMN, "Native Heap", memInfo.nativePss,
2328 memInfo.nativeSwappablePss, memInfo.nativeSharedDirty,
2329 memInfo.nativePrivateDirty, memInfo.nativeSharedClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002330 memInfo.nativePrivateClean, memInfo.hasSwappedOutPss ?
Richard Uhler91702eb32017-06-23 16:54:25 +01002331 memInfo.nativeSwappedOutPss : memInfo.nativeSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002332 nativeMax, nativeAllocated, nativeFree);
2333 printRow(pw, HEAP_FULL_COLUMN, "Dalvik Heap", memInfo.dalvikPss,
2334 memInfo.dalvikSwappablePss, memInfo.dalvikSharedDirty,
2335 memInfo.dalvikPrivateDirty, memInfo.dalvikSharedClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002336 memInfo.dalvikPrivateClean, memInfo.hasSwappedOutPss ?
Richard Uhler91702eb32017-06-23 16:54:25 +01002337 memInfo.dalvikSwappedOutPss : memInfo.dalvikSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002338 dalvikMax, dalvikAllocated, dalvikFree);
2339 } else {
2340 printRow(pw, HEAP_COLUMN, "", "Pss", "Private",
Martijn Coenene0764852016-01-07 17:04:22 -08002341 "Private", memInfo.hasSwappedOutPss ? "SwapPss" : "Swap",
2342 "Heap", "Heap", "Heap");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002343 printRow(pw, HEAP_COLUMN, "", "Total", "Dirty",
2344 "Clean", "Dirty", "Size", "Alloc", "Free");
2345 printRow(pw, HEAP_COLUMN, "", "------", "------", "------",
2346 "------", "------", "------", "------", "------");
2347 printRow(pw, HEAP_COLUMN, "Native Heap", memInfo.nativePss,
2348 memInfo.nativePrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002349 memInfo.nativePrivateClean,
2350 memInfo.hasSwappedOutPss ? memInfo.nativeSwappedOutPss :
2351 memInfo.nativeSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002352 nativeMax, nativeAllocated, nativeFree);
2353 printRow(pw, HEAP_COLUMN, "Dalvik Heap", memInfo.dalvikPss,
2354 memInfo.dalvikPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002355 memInfo.dalvikPrivateClean,
2356 memInfo.hasSwappedOutPss ? memInfo.dalvikSwappedOutPss :
2357 memInfo.dalvikSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002358 dalvikMax, dalvikAllocated, dalvikFree);
Dianne Hackborne77187d2013-10-25 16:32:41 -07002359 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002360
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002361 int otherPss = memInfo.otherPss;
2362 int otherSwappablePss = memInfo.otherSwappablePss;
2363 int otherSharedDirty = memInfo.otherSharedDirty;
2364 int otherPrivateDirty = memInfo.otherPrivateDirty;
2365 int otherSharedClean = memInfo.otherSharedClean;
2366 int otherPrivateClean = memInfo.otherPrivateClean;
2367 int otherSwappedOut = memInfo.otherSwappedOut;
Martijn Coenene0764852016-01-07 17:04:22 -08002368 int otherSwappedOutPss = memInfo.otherSwappedOutPss;
Dianne Hackborne77187d2013-10-25 16:32:41 -07002369
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002370 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
Dianne Hackborne77187d2013-10-25 16:32:41 -07002371 final int myPss = memInfo.getOtherPss(i);
2372 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2373 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2374 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2375 final int mySharedClean = memInfo.getOtherSharedClean(i);
2376 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2377 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
Martijn Coenene0764852016-01-07 17:04:22 -08002378 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Dianne Hackborne77187d2013-10-25 16:32:41 -07002379 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
Martijn Coenene0764852016-01-07 17:04:22 -08002380 || mySharedClean != 0 || myPrivateClean != 0
2381 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Dianne Hackborne77187d2013-10-25 16:32:41 -07002382 if (dumpFullInfo) {
2383 printRow(pw, HEAP_FULL_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2384 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002385 mySharedClean, myPrivateClean,
2386 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2387 "", "", "");
Dianne Hackborne77187d2013-10-25 16:32:41 -07002388 } else {
2389 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2390 myPss, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002391 myPrivateClean,
2392 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2393 "", "", "");
Dianne Hackborne77187d2013-10-25 16:32:41 -07002394 }
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002395 otherPss -= myPss;
2396 otherSwappablePss -= mySwappablePss;
2397 otherSharedDirty -= mySharedDirty;
2398 otherPrivateDirty -= myPrivateDirty;
2399 otherSharedClean -= mySharedClean;
2400 otherPrivateClean -= myPrivateClean;
2401 otherSwappedOut -= mySwappedOut;
Martijn Coenene0764852016-01-07 17:04:22 -08002402 otherSwappedOutPss -= mySwappedOutPss;
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002403 }
2404 }
2405
2406 if (dumpFullInfo) {
2407 printRow(pw, HEAP_FULL_COLUMN, "Unknown", otherPss, otherSwappablePss,
2408 otherSharedDirty, otherPrivateDirty, otherSharedClean, otherPrivateClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002409 memInfo.hasSwappedOutPss ? otherSwappedOutPss : otherSwappedOut,
2410 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002411 printRow(pw, HEAP_FULL_COLUMN, "TOTAL", memInfo.getTotalPss(),
2412 memInfo.getTotalSwappablePss(),
2413 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
2414 memInfo.getTotalSharedClean(), memInfo.getTotalPrivateClean(),
Thierry Strudel9b511602016-02-25 17:46:38 -08002415 memInfo.hasSwappedOutPss ? memInfo.getTotalSwappedOutPss() :
2416 memInfo.getTotalSwappedOut(),
Martijn Coenene0764852016-01-07 17:04:22 -08002417 nativeMax+dalvikMax, nativeAllocated+dalvikAllocated,
2418 nativeFree+dalvikFree);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002419 } else {
2420 printRow(pw, HEAP_COLUMN, "Unknown", otherPss,
Martijn Coenene0764852016-01-07 17:04:22 -08002421 otherPrivateDirty, otherPrivateClean,
2422 memInfo.hasSwappedOutPss ? otherSwappedOutPss : otherSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002423 "", "", "");
2424 printRow(pw, HEAP_COLUMN, "TOTAL", memInfo.getTotalPss(),
2425 memInfo.getTotalPrivateDirty(),
2426 memInfo.getTotalPrivateClean(),
Martijn Coenene0764852016-01-07 17:04:22 -08002427 memInfo.hasSwappedOutPss ? memInfo.getTotalSwappedOutPss() :
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002428 memInfo.getTotalSwappedOut(),
2429 nativeMax+dalvikMax,
2430 nativeAllocated+dalvikAllocated, nativeFree+dalvikFree);
2431 }
2432
2433 if (dumpDalvik) {
2434 pw.println(" ");
2435 pw.println(" Dalvik Details");
2436
2437 for (int i=Debug.MemoryInfo.NUM_OTHER_STATS;
2438 i<Debug.MemoryInfo.NUM_OTHER_STATS + Debug.MemoryInfo.NUM_DVK_STATS; i++) {
2439 final int myPss = memInfo.getOtherPss(i);
2440 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2441 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2442 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2443 final int mySharedClean = memInfo.getOtherSharedClean(i);
2444 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2445 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
Martijn Coenene0764852016-01-07 17:04:22 -08002446 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002447 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
Martijn Coenene0764852016-01-07 17:04:22 -08002448 || mySharedClean != 0 || myPrivateClean != 0
2449 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002450 if (dumpFullInfo) {
2451 printRow(pw, HEAP_FULL_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2452 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002453 mySharedClean, myPrivateClean,
2454 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2455 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002456 } else {
2457 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2458 myPss, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002459 myPrivateClean,
2460 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2461 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002462 }
2463 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002464 }
2465 }
2466 }
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002467
2468 pw.println(" ");
2469 pw.println(" App Summary");
2470 printRow(pw, ONE_COUNT_COLUMN_HEADER, "", "Pss(KB)");
2471 printRow(pw, ONE_COUNT_COLUMN_HEADER, "", "------");
2472 printRow(pw, ONE_COUNT_COLUMN,
2473 "Java Heap:", memInfo.getSummaryJavaHeap());
2474 printRow(pw, ONE_COUNT_COLUMN,
2475 "Native Heap:", memInfo.getSummaryNativeHeap());
2476 printRow(pw, ONE_COUNT_COLUMN,
2477 "Code:", memInfo.getSummaryCode());
2478 printRow(pw, ONE_COUNT_COLUMN,
2479 "Stack:", memInfo.getSummaryStack());
2480 printRow(pw, ONE_COUNT_COLUMN,
2481 "Graphics:", memInfo.getSummaryGraphics());
2482 printRow(pw, ONE_COUNT_COLUMN,
2483 "Private Other:", memInfo.getSummaryPrivateOther());
2484 printRow(pw, ONE_COUNT_COLUMN,
2485 "System:", memInfo.getSummarySystem());
2486 pw.println(" ");
Martijn Coenene0764852016-01-07 17:04:22 -08002487 if (memInfo.hasSwappedOutPss) {
2488 printRow(pw, TWO_COUNT_COLUMNS,
2489 "TOTAL:", memInfo.getSummaryTotalPss(),
2490 "TOTAL SWAP PSS:", memInfo.getSummaryTotalSwapPss());
2491 } else {
2492 printRow(pw, TWO_COUNT_COLUMNS,
2493 "TOTAL:", memInfo.getSummaryTotalPss(),
2494 "TOTAL SWAP (KB):", memInfo.getSummaryTotalSwap());
2495 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002496 }
2497
Kweku Adams598e9a22017-11-02 17:12:20 -07002498 /**
2499 * Dump heap info to proto.
2500 *
2501 * @param hasSwappedOutPss determines whether to use dirtySwap or dirtySwapPss
2502 */
Kweku Adams983829f2017-12-06 14:53:50 -08002503 private static void dumpMemoryInfo(ProtoOutputStream proto, long fieldId, String name,
Kweku Adams598e9a22017-11-02 17:12:20 -07002504 int pss, int cleanPss, int sharedDirty, int privateDirty,
2505 int sharedClean, int privateClean,
2506 boolean hasSwappedOutPss, int dirtySwap, int dirtySwapPss) {
2507 final long token = proto.start(fieldId);
2508
Yi Jin2b30f322018-02-20 15:41:47 -08002509 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.NAME, name);
2510 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.TOTAL_PSS_KB, pss);
2511 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.CLEAN_PSS_KB, cleanPss);
2512 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.SHARED_DIRTY_KB, sharedDirty);
2513 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.PRIVATE_DIRTY_KB, privateDirty);
2514 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.SHARED_CLEAN_KB, sharedClean);
2515 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.PRIVATE_CLEAN_KB, privateClean);
Kweku Adams598e9a22017-11-02 17:12:20 -07002516 if (hasSwappedOutPss) {
Yi Jin2b30f322018-02-20 15:41:47 -08002517 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.DIRTY_SWAP_PSS_KB, dirtySwapPss);
Kweku Adams598e9a22017-11-02 17:12:20 -07002518 } else {
Yi Jin2b30f322018-02-20 15:41:47 -08002519 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.DIRTY_SWAP_KB, dirtySwap);
Kweku Adams598e9a22017-11-02 17:12:20 -07002520 }
2521
2522 proto.end(token);
2523 }
2524
2525 /**
2526 * Dump mem info data to proto.
2527 */
2528 public static void dumpMemInfoTable(ProtoOutputStream proto, Debug.MemoryInfo memInfo,
2529 boolean dumpDalvik, boolean dumpSummaryOnly,
2530 long nativeMax, long nativeAllocated, long nativeFree,
2531 long dalvikMax, long dalvikAllocated, long dalvikFree) {
2532
2533 if (!dumpSummaryOnly) {
Yi Jin2b30f322018-02-20 15:41:47 -08002534 final long nhToken = proto.start(MemInfoDumpProto.ProcessMemory.NATIVE_HEAP);
2535 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "Native Heap",
Kweku Adams598e9a22017-11-02 17:12:20 -07002536 memInfo.nativePss, memInfo.nativeSwappablePss, memInfo.nativeSharedDirty,
2537 memInfo.nativePrivateDirty, memInfo.nativeSharedClean,
2538 memInfo.nativePrivateClean, memInfo.hasSwappedOutPss,
2539 memInfo.nativeSwappedOut, memInfo.nativeSwappedOutPss);
Yi Jin2b30f322018-02-20 15:41:47 -08002540 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB, nativeMax);
2541 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB, nativeAllocated);
2542 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB, nativeFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002543 proto.end(nhToken);
2544
Yi Jin2b30f322018-02-20 15:41:47 -08002545 final long dvToken = proto.start(MemInfoDumpProto.ProcessMemory.DALVIK_HEAP);
2546 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "Dalvik Heap",
Kweku Adams598e9a22017-11-02 17:12:20 -07002547 memInfo.dalvikPss, memInfo.dalvikSwappablePss, memInfo.dalvikSharedDirty,
2548 memInfo.dalvikPrivateDirty, memInfo.dalvikSharedClean,
2549 memInfo.dalvikPrivateClean, memInfo.hasSwappedOutPss,
2550 memInfo.dalvikSwappedOut, memInfo.dalvikSwappedOutPss);
Yi Jin2b30f322018-02-20 15:41:47 -08002551 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB, dalvikMax);
2552 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB, dalvikAllocated);
2553 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB, dalvikFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002554 proto.end(dvToken);
2555
2556 int otherPss = memInfo.otherPss;
2557 int otherSwappablePss = memInfo.otherSwappablePss;
2558 int otherSharedDirty = memInfo.otherSharedDirty;
2559 int otherPrivateDirty = memInfo.otherPrivateDirty;
2560 int otherSharedClean = memInfo.otherSharedClean;
2561 int otherPrivateClean = memInfo.otherPrivateClean;
2562 int otherSwappedOut = memInfo.otherSwappedOut;
2563 int otherSwappedOutPss = memInfo.otherSwappedOutPss;
2564
2565 for (int i = 0; i < Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
2566 final int myPss = memInfo.getOtherPss(i);
2567 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2568 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2569 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2570 final int mySharedClean = memInfo.getOtherSharedClean(i);
2571 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2572 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
2573 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
2574 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
2575 || mySharedClean != 0 || myPrivateClean != 0
2576 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Yi Jin2b30f322018-02-20 15:41:47 -08002577 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.OTHER_HEAPS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002578 Debug.MemoryInfo.getOtherLabel(i),
2579 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
2580 mySharedClean, myPrivateClean,
2581 memInfo.hasSwappedOutPss, mySwappedOut, mySwappedOutPss);
2582
2583 otherPss -= myPss;
2584 otherSwappablePss -= mySwappablePss;
2585 otherSharedDirty -= mySharedDirty;
2586 otherPrivateDirty -= myPrivateDirty;
2587 otherSharedClean -= mySharedClean;
2588 otherPrivateClean -= myPrivateClean;
2589 otherSwappedOut -= mySwappedOut;
2590 otherSwappedOutPss -= mySwappedOutPss;
2591 }
2592 }
2593
Yi Jin2b30f322018-02-20 15:41:47 -08002594 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.UNKNOWN_HEAP, "Unknown",
Kweku Adams598e9a22017-11-02 17:12:20 -07002595 otherPss, otherSwappablePss,
2596 otherSharedDirty, otherPrivateDirty, otherSharedClean, otherPrivateClean,
2597 memInfo.hasSwappedOutPss, otherSwappedOut, otherSwappedOutPss);
Yi Jin2b30f322018-02-20 15:41:47 -08002598 final long tToken = proto.start(MemInfoDumpProto.ProcessMemory.TOTAL_HEAP);
2599 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "TOTAL",
Kweku Adams598e9a22017-11-02 17:12:20 -07002600 memInfo.getTotalPss(), memInfo.getTotalSwappablePss(),
2601 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
2602 memInfo.getTotalSharedClean(), memInfo.getTotalPrivateClean(),
2603 memInfo.hasSwappedOutPss, memInfo.getTotalSwappedOut(),
2604 memInfo.getTotalSwappedOutPss());
Yi Jin2b30f322018-02-20 15:41:47 -08002605 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB,
2606 nativeMax + dalvikMax);
2607 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002608 nativeAllocated + dalvikAllocated);
Yi Jin2b30f322018-02-20 15:41:47 -08002609 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB,
2610 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) {
Yi Jin2b30f322018-02-20 15:41:47 -08002628 dumpMemoryInfo(proto, MemInfoDumpProto.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
Yi Jin2b30f322018-02-20 15:41:47 -08002638 final long asToken = proto.start(MemInfoDumpProto.ProcessMemory.APP_SUMMARY);
2639 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.JAVA_HEAP_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002640 memInfo.getSummaryJavaHeap());
Yi Jin2b30f322018-02-20 15:41:47 -08002641 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.NATIVE_HEAP_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002642 memInfo.getSummaryNativeHeap());
Yi Jin2b30f322018-02-20 15:41:47 -08002643 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.CODE_PSS_KB,
2644 memInfo.getSummaryCode());
2645 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.STACK_PSS_KB,
2646 memInfo.getSummaryStack());
2647 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.GRAPHICS_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002648 memInfo.getSummaryGraphics());
Yi Jin2b30f322018-02-20 15:41:47 -08002649 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.PRIVATE_OTHER_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002650 memInfo.getSummaryPrivateOther());
Yi Jin2b30f322018-02-20 15:41:47 -08002651 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.SYSTEM_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002652 memInfo.getSummarySystem());
2653 if (memInfo.hasSwappedOutPss) {
Yi Jin2b30f322018-02-20 15:41:47 -08002654 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.TOTAL_SWAP_PSS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002655 memInfo.getSummaryTotalSwapPss());
2656 } else {
Yi Jin2b30f322018-02-20 15:41:47 -08002657 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.TOTAL_SWAP_PSS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002658 memInfo.getSummaryTotalSwap());
2659 }
2660 proto.end(asToken);
2661 }
2662
Jeff Hamilton52d32032011-01-08 15:31:26 -06002663 public void registerOnActivityPausedListener(Activity activity,
2664 OnActivityPausedListener listener) {
2665 synchronized (mOnPauseListeners) {
2666 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
2667 if (list == null) {
2668 list = new ArrayList<OnActivityPausedListener>();
2669 mOnPauseListeners.put(activity, list);
2670 }
2671 list.add(listener);
2672 }
2673 }
2674
Jeff Hamiltonce3224c2011-01-17 11:05:03 -08002675 public void unregisterOnActivityPausedListener(Activity activity,
2676 OnActivityPausedListener listener) {
2677 synchronized (mOnPauseListeners) {
2678 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
2679 if (list != null) {
2680 list.remove(listener);
2681 }
2682 }
2683 }
2684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 public final ActivityInfo resolveActivityInfo(Intent intent) {
2686 ActivityInfo aInfo = intent.resolveActivityInfo(
2687 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
2688 if (aInfo == null) {
2689 // Throw an exception.
2690 Instrumentation.checkStartActivityResult(
Dianne Hackborna4972e92012-03-14 10:38:05 -07002691 ActivityManager.START_CLASS_NOT_FOUND, intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 }
2693 return aInfo;
2694 }
Bob Leee5408332009-09-04 18:31:17 -07002695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002698 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002699 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002701 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 r.intent = intent;
2703 r.state = state;
2704 r.parent = parent;
2705 r.embeddedID = id;
2706 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002707 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002708 if (localLOGV) {
2709 ComponentName compname = intent.getComponent();
2710 String name;
2711 if (compname != null) {
2712 name = compname.toShortString();
2713 } else {
2714 name = "(Intent " + intent + ").getComponent() returned null";
2715 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002716 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 + ", comp=" + name
2718 + ", token=" + token);
2719 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002720 // TODO(lifecycler): Can't switch to use #handleLaunchActivity() because it will try to
2721 // call #reportSizeConfigurations(), but the server might not know anything about the
2722 // activity if it was launched from LocalAcvitivyManager.
Andrii Kulian770c4032018-05-02 18:40:59 -07002723 return performLaunchActivity(r, null /* customIntent */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 }
2725
2726 public final Activity getActivity(IBinder token) {
2727 return mActivities.get(token).activity;
2728 }
2729
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002730 @Override
2731 public ActivityClientRecord getActivityClient(IBinder token) {
2732 return mActivities.get(token);
2733 }
2734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 public final void sendActivityResult(
2736 IBinder token, String id, int requestCode,
2737 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002738 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07002739 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2741 list.add(new ResultInfo(id, requestCode, resultCode, data));
Andrii Kulian9c5ea9c2017-12-07 09:31:01 -08002742 final ClientTransaction clientTransaction = ClientTransaction.obtain(mAppThread, token);
2743 clientTransaction.addCallback(ActivityResultItem.obtain(list));
Andrii Kulian446e8242017-10-26 15:17:29 -07002744 try {
2745 mAppThread.scheduleTransaction(clientTransaction);
2746 } catch (RemoteException e) {
2747 // Local scheduling
2748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 }
2750
Andrii Kulian914aa7d2018-03-19 21:51:53 -07002751 @Override
2752 TransactionExecutor getTransactionExecutor() {
2753 return mTransactionExecutor;
2754 }
2755
Andrii Kulian446e8242017-10-26 15:17:29 -07002756 void sendMessage(int what, Object obj) {
Jeff Brown9ef09972013-10-15 20:49:59 -07002757 sendMessage(what, obj, 0, 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 }
2759
Jeff Brown9ef09972013-10-15 20:49:59 -07002760 private void sendMessage(int what, Object obj, int arg1) {
2761 sendMessage(what, obj, arg1, 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002762 }
2763
Jeff Brown9ef09972013-10-15 20:49:59 -07002764 private void sendMessage(int what, Object obj, int arg1, int arg2) {
2765 sendMessage(what, obj, arg1, arg2, false);
2766 }
2767
2768 private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
2769 if (DEBUG_MESSAGES) Slog.v(
2770 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
2771 + ": " + arg1 + " / " + obj);
2772 Message msg = Message.obtain();
2773 msg.what = what;
2774 msg.obj = obj;
2775 msg.arg1 = arg1;
2776 msg.arg2 = arg2;
2777 if (async) {
2778 msg.setAsynchronous(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 }
Jeff Brown9ef09972013-10-15 20:49:59 -07002780 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 }
2782
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07002783 private void sendMessage(int what, Object obj, int arg1, int arg2, int seq) {
2784 if (DEBUG_MESSAGES) Slog.v(
2785 TAG, "SCHEDULE " + mH.codeToString(what) + " arg1=" + arg1 + " arg2=" + arg2 +
2786 "seq= " + seq);
2787 Message msg = Message.obtain();
2788 msg.what = what;
2789 SomeArgs args = SomeArgs.obtain();
2790 args.arg1 = obj;
2791 args.argi1 = arg1;
2792 args.argi2 = arg2;
2793 args.argi3 = seq;
2794 msg.obj = args;
2795 mH.sendMessage(msg);
2796 }
2797
Dianne Hackborn21556372010-02-04 16:34:40 -08002798 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799 String what) {
2800 ContextCleanupInfo cci = new ContextCleanupInfo();
2801 cci.context = context;
2802 cci.who = who;
2803 cci.what = what;
Jeff Brown9ef09972013-10-15 20:49:59 -07002804 sendMessage(H.CLEAN_UP_CONTEXT, cci);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002805 }
2806
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002807 /** Core implementation of activity launch. */
Andrii Kulian770c4032018-05-02 18:40:59 -07002808 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002809 ActivityInfo aInfo = r.activityInfo;
Todd Kennedy233a0b12018-01-29 20:30:24 +00002810 if (r.packageInfo == null) {
2811 r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 Context.CONTEXT_INCLUDE_CODE);
2813 }
Bob Leee5408332009-09-04 18:31:17 -07002814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 ComponentName component = r.intent.getComponent();
2816 if (component == null) {
2817 component = r.intent.resolveActivity(
2818 mInitialApplication.getPackageManager());
2819 r.intent.setComponent(component);
2820 }
2821
2822 if (r.activityInfo.targetActivity != null) {
2823 component = new ComponentName(r.activityInfo.packageName,
2824 r.activityInfo.targetActivity);
2825 }
2826
Adam Lesinski4e862812016-11-21 16:02:24 -08002827 ContextImpl appContext = createBaseContextForActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 Activity activity = null;
2829 try {
Adam Lesinski4e862812016-11-21 16:02:24 -08002830 java.lang.ClassLoader cl = appContext.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04002831 activity = mInstrumentation.newActivity(
2832 cl, component.getClassName(), r.intent);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08002833 StrictMode.incrementExpectedActivityCount(activity.getClass());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 r.intent.setExtrasClassLoader(cl);
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01002835 r.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 if (r.state != null) {
2837 r.state.setClassLoader(cl);
2838 }
2839 } catch (Exception e) {
2840 if (!mInstrumentation.onException(activity, e)) {
2841 throw new RuntimeException(
2842 "Unable to instantiate activity " + component
2843 + ": " + e.toString(), e);
2844 }
2845 }
2846
2847 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002848 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07002849
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002850 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
2851 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 TAG, r + ": app=" + app
2853 + ", appName=" + app.getPackageName()
Todd Kennedy233a0b12018-01-29 20:30:24 +00002854 + ", pkg=" + r.packageInfo.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 + ", comp=" + r.intent.getComponent().toShortString()
Todd Kennedy233a0b12018-01-29 20:30:24 +00002856 + ", dir=" + r.packageInfo.getAppDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857
2858 if (activity != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002860 Configuration config = new Configuration(mCompatConfiguration);
Andrii Kuliand0ad9382016-04-18 20:54:20 -07002861 if (r.overrideConfig != null) {
2862 config.updateFrom(r.overrideConfig);
2863 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002864 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07002865 + r.activityInfo.name + " with config " + config);
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07002866 Window window = null;
2867 if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
2868 window = r.mPendingRemoveWindow;
2869 r.mPendingRemoveWindow = null;
2870 r.mPendingRemoveWindowManager = null;
2871 }
Adam Lesinski4e862812016-11-21 16:02:24 -08002872 appContext.setOuterContext(activity);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002873 activity.attach(appContext, this, getInstrumentation(), r.token,
2874 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Craig Mautner233ceee2014-05-09 17:05:11 -07002875 r.embeddedID, r.lastNonConfigurationInstances, config,
Andrii Kulian51c1b672017-04-07 18:39:32 -07002876 r.referrer, r.voiceInteractor, window, r.configCallback);
Bob Leee5408332009-09-04 18:31:17 -07002877
Andrii Kulian770c4032018-05-02 18:40:59 -07002878 if (customIntent != null) {
2879 activity.mIntent = customIntent;
2880 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002881 r.lastNonConfigurationInstances = null;
Sudheer Shanka84a48952017-03-08 18:19:01 -08002882 checkAndBlockForNetworkAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 activity.mStartedActivity = false;
2884 int theme = r.activityInfo.getThemeResource();
2885 if (theme != 0) {
2886 activity.setTheme(theme);
2887 }
2888
2889 activity.mCalled = false;
Craig Mautnera0026042014-04-23 11:45:37 -07002890 if (r.isPersistable()) {
2891 mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
2892 } else {
2893 mInstrumentation.callActivityOnCreate(activity, r.state);
2894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 if (!activity.mCalled) {
2896 throw new SuperNotCalledException(
2897 "Activity " + r.intent.getComponent().toShortString() +
2898 " did not call through to super.onCreate()");
2899 }
2900 r.activity = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002902 r.setState(ON_CREATE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903
2904 mActivities.put(r.token, r);
2905
2906 } catch (SuperNotCalledException e) {
2907 throw e;
2908
2909 } catch (Exception e) {
2910 if (!mInstrumentation.onException(activity, e)) {
2911 throw new RuntimeException(
2912 "Unable to start activity " + component
2913 + ": " + e.toString(), e);
2914 }
2915 }
2916
2917 return activity;
2918 }
2919
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002920 @Override
2921 public void handleStartActivity(ActivityClientRecord r,
2922 PendingTransactionActions pendingActions) {
2923 final Activity activity = r.activity;
2924 if (r.activity == null) {
2925 // TODO(lifecycler): What do we do in this case?
2926 return;
2927 }
2928 if (!r.stopped) {
2929 throw new IllegalStateException("Can't start activity that is not stopped.");
2930 }
2931 if (r.activity.mFinished) {
2932 // TODO(lifecycler): How can this happen?
2933 return;
2934 }
2935
2936 // Start
Andrii Kuliand25680c2018-02-21 15:16:58 -08002937 activity.performStart("handleStartActivity");
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002938 r.setState(ON_START);
2939
2940 if (pendingActions == null) {
2941 // No more work to do.
2942 return;
2943 }
2944
2945 // Restore instance state
2946 if (pendingActions.shouldRestoreInstanceState()) {
2947 if (r.isPersistable()) {
2948 if (r.state != null || r.persistentState != null) {
2949 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
2950 r.persistentState);
2951 }
2952 } else if (r.state != null) {
2953 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
2954 }
2955 }
2956
2957 // Call postOnCreate()
2958 if (pendingActions.shouldCallOnPostCreate()) {
2959 activity.mCalled = false;
2960 if (r.isPersistable()) {
2961 mInstrumentation.callActivityOnPostCreate(activity, r.state,
2962 r.persistentState);
2963 } else {
2964 mInstrumentation.callActivityOnPostCreate(activity, r.state);
2965 }
2966 if (!activity.mCalled) {
2967 throw new SuperNotCalledException(
2968 "Activity " + r.intent.getComponent().toShortString()
2969 + " did not call through to super.onPostCreate()");
2970 }
2971 }
2972 }
2973
Sudheer Shanka84a48952017-03-08 18:19:01 -08002974 /**
2975 * Checks if {@link #mNetworkBlockSeq} is {@link #INVALID_PROC_STATE_SEQ} and if so, returns
2976 * immediately. Otherwise, makes a blocking call to ActivityManagerService to wait for the
2977 * network rules to get updated.
2978 */
2979 private void checkAndBlockForNetworkAccess() {
2980 synchronized (mNetworkPolicyLock) {
2981 if (mNetworkBlockSeq != INVALID_PROC_STATE_SEQ) {
2982 try {
2983 ActivityManager.getService().waitForNetworkStateUpdate(mNetworkBlockSeq);
2984 mNetworkBlockSeq = INVALID_PROC_STATE_SEQ;
2985 } catch (RemoteException ignored) {}
2986 }
2987 }
2988 }
2989
Adam Lesinski4e862812016-11-21 16:02:24 -08002990 private ContextImpl createBaseContextForActivity(ActivityClientRecord r) {
2991 final int displayId;
Craig Mautnere0a38842013-12-16 16:14:02 -08002992 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002993 displayId = ActivityManager.getService().getActivityDisplayId(r.token);
Craig Mautnere0a38842013-12-16 16:14:02 -08002994 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002995 throw e.rethrowFromSystemServer();
Craig Mautnere0a38842013-12-16 16:14:02 -08002996 }
Jeff Brownefd43bd2012-09-21 17:02:35 -07002997
Wale Ogunwale7c726682015-02-06 17:34:28 -08002998 ContextImpl appContext = ContextImpl.createActivityContext(
Todd Kennedy233a0b12018-01-29 20:30:24 +00002999 this, r.packageInfo, r.activityInfo, r.token, displayId, r.overrideConfig);
Wale Ogunwale7c726682015-02-06 17:34:28 -08003000
3001 final DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance();
Jeff Brownefd43bd2012-09-21 17:02:35 -07003002 // For debugging purposes, if the activity's package name contains the value of
3003 // the "debug.use-second-display" system property as a substring, then show
3004 // its content on a secondary display if there is one.
Jeff Brownefd43bd2012-09-21 17:02:35 -07003005 String pkgName = SystemProperties.get("debug.second-display.pkg");
3006 if (pkgName != null && !pkgName.isEmpty()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003007 && r.packageInfo.mPackageName.contains(pkgName)) {
Wale Ogunwale7c726682015-02-06 17:34:28 -08003008 for (int id : dm.getDisplayIds()) {
3009 if (id != Display.DEFAULT_DISPLAY) {
Wale Ogunwale26698512015-06-05 16:55:33 -07003010 Display display =
Bryce Lee609bf652017-02-09 16:50:13 -08003011 dm.getCompatibleDisplay(id, appContext.getResources());
Adam Lesinski4e862812016-11-21 16:02:24 -08003012 appContext = (ContextImpl) appContext.createDisplayContext(display);
Jeff Brownefd43bd2012-09-21 17:02:35 -07003013 break;
3014 }
3015 }
3016 }
Adam Lesinski4e862812016-11-21 16:02:24 -08003017 return appContext;
Jeff Brownefd43bd2012-09-21 17:02:35 -07003018 }
3019
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003020 /**
3021 * Extended implementation of activity launch. Used when server requests a launch or relaunch.
3022 */
Andrii Kulian446e8242017-10-26 15:17:29 -07003023 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003024 public Activity handleLaunchActivity(ActivityClientRecord r,
Andrii Kulian770c4032018-05-02 18:40:59 -07003025 PendingTransactionActions pendingActions, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026 // If we are getting ready to gc after going to the background, well
3027 // we are back active so skip it.
3028 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003029 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003030
Jeff Hao1b012d32014-08-20 10:35:34 -07003031 if (r.profilerInfo != null) {
3032 mProfiler.setProfiler(r.profilerInfo);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003033 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003034 }
3035
Dianne Hackborn58f42a52011-10-10 13:46:34 -07003036 // Make sure we are running with the most recent config.
3037 handleConfigurationChanged(null, null);
3038
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003039 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 TAG, "Handling launch of " + r);
Adam Powellcfbe9be2013-11-06 14:58:58 -08003041
Chet Haase0d1c27a2014-11-03 18:35:16 +00003042 // Initialize before creating the activity
Jesse Hallc37984f2017-05-23 16:55:08 -07003043 if (!ThreadedRenderer.sRendererDisabled) {
3044 GraphicsEnvironment.earlyInitEGL();
3045 }
Chet Haase0d1c27a2014-11-03 18:35:16 +00003046 WindowManagerGlobal.initialize();
3047
Andrii Kulian770c4032018-05-02 18:40:59 -07003048 final Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049
3050 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003051 r.createdConfig = new Configuration(mConfiguration);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003052 reportSizeConfigurations(r);
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003053 if (!r.activity.mFinished && pendingActions != null) {
3054 pendingActions.setOldState(r.state);
3055 pendingActions.setRestoreInstanceState(true);
3056 pendingActions.setCallOnPostCreate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 }
3058 } else {
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07003059 // 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 -08003060 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003061 ActivityManager.getService()
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003062 .finishActivity(r.token, Activity.RESULT_CANCELED, null,
3063 Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003065 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003066 }
3067 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003068
3069 return a;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 }
3071
Filip Gruszczynski23493322015-07-29 17:02:59 -07003072 private void reportSizeConfigurations(ActivityClientRecord r) {
3073 Configuration[] configurations = r.activity.getResources().getSizeConfigurations();
3074 if (configurations == null) {
3075 return;
3076 }
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003077 SparseIntArray horizontal = new SparseIntArray();
3078 SparseIntArray vertical = new SparseIntArray();
3079 SparseIntArray smallest = new SparseIntArray();
Filip Gruszczynski23493322015-07-29 17:02:59 -07003080 for (int i = configurations.length - 1; i >= 0; i--) {
3081 Configuration config = configurations[i];
3082 if (config.screenHeightDp != Configuration.SCREEN_HEIGHT_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003083 vertical.put(config.screenHeightDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003084 }
3085 if (config.screenWidthDp != Configuration.SCREEN_WIDTH_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003086 horizontal.put(config.screenWidthDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003087 }
3088 if (config.smallestScreenWidthDp != Configuration.SMALLEST_SCREEN_WIDTH_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003089 smallest.put(config.smallestScreenWidthDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003090 }
3091 }
Filip Gruszczynski23493322015-07-29 17:02:59 -07003092 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003093 ActivityManager.getService().reportSizeConfigurations(r.token,
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003094 horizontal.copyKeys(), vertical.copyKeys(), smallest.copyKeys());
Filip Gruszczynski23493322015-07-29 17:02:59 -07003095 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003096 throw ex.rethrowFromSystemServer();
Filip Gruszczynski23493322015-07-29 17:02:59 -07003097 }
3098
3099 }
3100
Dianne Hackborn85d558c2014-11-04 10:31:54 -08003101 private void deliverNewIntents(ActivityClientRecord r, List<ReferrerIntent> intents) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 final int N = intents.size();
3103 for (int i=0; i<N; i++) {
Dianne Hackborna01a0fa2014-12-02 10:33:14 -08003104 ReferrerIntent intent = intents.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 intent.setExtrasClassLoader(r.activity.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003106 intent.prepareToEnterProcess();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003107 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003108 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
3109 }
3110 }
3111
Wale Ogunwale826c7062016-09-13 08:25:54 -07003112 void performNewIntents(IBinder token, List<ReferrerIntent> intents, boolean andPause) {
3113 final ActivityClientRecord r = mActivities.get(token);
3114 if (r == null) {
3115 return;
3116 }
3117
3118 final boolean resumed = !r.paused;
3119 if (resumed) {
3120 r.activity.mTemporaryPause = true;
3121 mInstrumentation.callActivityOnPause(r.activity);
3122 }
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07003123 checkAndBlockForNetworkAccess();
Wale Ogunwale826c7062016-09-13 08:25:54 -07003124 deliverNewIntents(r, intents);
3125 if (resumed) {
Andrii Kuliand25680c2018-02-21 15:16:58 -08003126 r.activity.performResume(false, "performNewIntents");
Wale Ogunwale826c7062016-09-13 08:25:54 -07003127 r.activity.mTemporaryPause = false;
3128 }
3129
3130 if (r.paused && andPause) {
3131 // In this case the activity was in the paused state when we delivered the intent,
3132 // to guarantee onResume gets called after onNewIntent we temporarily resume the
3133 // activity and pause again as the caller wanted.
3134 performResumeActivity(token, false, "performNewIntents");
3135 performPauseActivityIfNeeded(r, "performNewIntents");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 }
3137 }
Bob Leee5408332009-09-04 18:31:17 -07003138
Andrii Kulian446e8242017-10-26 15:17:29 -07003139 @Override
3140 public void handleNewIntent(IBinder token, List<ReferrerIntent> intents, boolean andPause) {
3141 performNewIntents(token, intents, andPause);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 }
3143
Adam Skorydfc7fd72013-08-05 19:23:41 -07003144 public void handleRequestAssistContextExtras(RequestAssistContextExtras cmd) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003145 // Filling for autofill has a few differences:
Felipe Leme1ca634a2016-11-28 17:21:21 -08003146 // - it does not need an AssistContent
3147 // - it does not call onProvideAssistData()
3148 // - it needs an IAutoFillCallback
Felipe Leme640f30a2017-03-06 15:44:06 -08003149 boolean forAutofill = cmd.requestType == ActivityManager.ASSIST_CONTEXT_AUTOFILL;
Felipe Leme1ca634a2016-11-28 17:21:21 -08003150
Felipe Leme85d1c2d2017-04-21 08:56:04 -07003151 // TODO: decide if lastSessionId logic applies to autofill sessions
Amith Yamasani4f128e42016-05-10 11:44:12 -07003152 if (mLastSessionId != cmd.sessionId) {
3153 // Clear the existing structures
3154 mLastSessionId = cmd.sessionId;
3155 for (int i = mLastAssistStructures.size() - 1; i >= 0; i--) {
3156 AssistStructure structure = mLastAssistStructures.get(i).get();
3157 if (structure != null) {
3158 structure.clearSendChannel();
3159 }
3160 mLastAssistStructures.remove(i);
Dianne Hackborn782d4982015-07-08 17:36:37 -07003161 }
3162 }
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003163
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003164 Bundle data = new Bundle();
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003165 AssistStructure structure = null;
Felipe Leme640f30a2017-03-06 15:44:06 -08003166 AssistContent content = forAutofill ? null : new AssistContent();
Amith Yamasani858f98d2017-02-22 12:59:53 -08003167 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003168 ActivityClientRecord r = mActivities.get(cmd.activityToken);
Dianne Hackborna3acdb32015-06-08 17:07:40 -07003169 Uri referrer = null;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003170 if (r != null) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003171 if (!forAutofill) {
Felipe Leme1ca634a2016-11-28 17:21:21 -08003172 r.activity.getApplication().dispatchOnProvideAssistData(r.activity, data);
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003173 r.activity.onProvideAssistData(data);
Felipe Leme6d553872016-12-08 17:13:25 -08003174 referrer = r.activity.onProvideReferrer();
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003175 }
Felipe Leme640f30a2017-03-06 15:44:06 -08003176 if (cmd.requestType == ActivityManager.ASSIST_CONTEXT_FULL || forAutofill) {
Svet Ganovfd31f852017-04-26 15:54:27 -07003177 structure = new AssistStructure(r.activity, forAutofill, cmd.flags);
Adam Skory4aaed142015-04-22 11:29:31 -06003178 Intent activityIntent = r.activity.getIntent();
Felipe Leme6d553872016-12-08 17:13:25 -08003179 boolean notSecure = r.window == null ||
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003180 (r.window.getAttributes().flags
Felipe Leme6d553872016-12-08 17:13:25 -08003181 & WindowManager.LayoutParams.FLAG_SECURE) == 0;
3182 if (activityIntent != null && notSecure) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003183 if (!forAutofill) {
Felipe Leme1ca634a2016-11-28 17:21:21 -08003184 Intent intent = new Intent(activityIntent);
3185 intent.setFlags(intent.getFlags() & ~(Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3186 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION));
3187 intent.removeUnsafeExtras();
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003188 content.setDefaultIntent(intent);
3189 }
Adam Skory4aaed142015-04-22 11:29:31 -06003190 } else {
Felipe Leme640f30a2017-03-06 15:44:06 -08003191 if (!forAutofill) {
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003192 content.setDefaultIntent(new Intent());
3193 }
Adam Skory4aaed142015-04-22 11:29:31 -06003194 }
Felipe Leme640f30a2017-03-06 15:44:06 -08003195 if (!forAutofill) {
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003196 r.activity.onProvideAssistContent(content);
3197 }
Dianne Hackborna83ce1d2015-03-11 15:16:13 -07003198 }
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003199 }
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003200 if (structure == null) {
3201 structure = new AssistStructure();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003202 }
Felipe Leme0200d9e2017-01-24 15:10:26 -08003203
Felipe Leme85d1c2d2017-04-21 08:56:04 -07003204 // TODO: decide if lastSessionId logic applies to autofill sessions
Amith Yamasani858f98d2017-02-22 12:59:53 -08003205
3206 structure.setAcquisitionStartTime(startTime);
3207 structure.setAcquisitionEndTime(SystemClock.uptimeMillis());
3208
Amith Yamasani4f128e42016-05-10 11:44:12 -07003209 mLastAssistStructures.add(new WeakReference<>(structure));
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003210 IActivityManager mgr = ActivityManager.getService();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003211 try {
Dianne Hackborna3acdb32015-06-08 17:07:40 -07003212 mgr.reportAssistContextExtras(cmd.requestToken, data, structure, content, referrer);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003213 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003214 throw e.rethrowFromSystemServer();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003215 }
3216 }
Craig Mautner5eda9b32013-07-02 11:58:16 -07003217
3218 public void handleTranslucentConversionComplete(IBinder token, boolean drawComplete) {
3219 ActivityClientRecord r = mActivities.get(token);
3220 if (r != null) {
3221 r.activity.onTranslucentConversionComplete(drawComplete);
3222 }
3223 }
3224
Craig Mautnereb8abf72014-07-02 15:04:09 -07003225 public void onNewActivityOptions(IBinder token, ActivityOptions options) {
3226 ActivityClientRecord r = mActivities.get(token);
3227 if (r != null) {
3228 r.activity.onNewActivityOptions(options);
3229 }
3230 }
3231
Jeff Sharkeydd97f422013-10-08 17:01:30 -07003232 public void handleInstallProvider(ProviderInfo info) {
Jeff Sharkeybb2e2ca2014-10-23 11:42:31 -07003233 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3234 try {
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -06003235 installContentProviders(mInitialApplication, Arrays.asList(info));
Jeff Sharkeybb2e2ca2014-10-23 11:42:31 -07003236 } finally {
3237 StrictMode.setThreadPolicy(oldPolicy);
3238 }
Jeff Sharkeydd97f422013-10-08 17:01:30 -07003239 }
3240
Craig Mautner8746a472014-07-24 15:12:54 -07003241 private void handleEnterAnimationComplete(IBinder token) {
3242 ActivityClientRecord r = mActivities.get(token);
3243 if (r != null) {
Filip Gruszczynski6eafa902014-11-14 14:24:37 -08003244 r.activity.dispatchEnterAnimationComplete();
Craig Mautner8746a472014-07-24 15:12:54 -07003245 }
3246 }
3247
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04003248 private void handleStartBinderTracking() {
3249 Binder.enableTracing();
3250 }
3251
3252 private void handleStopBinderTrackingAndDump(ParcelFileDescriptor fd) {
3253 try {
3254 Binder.disableTracing();
3255 Binder.getTransactionTracker().writeTracesToFile(fd);
3256 } finally {
3257 IoUtils.closeQuietly(fd);
3258 Binder.getTransactionTracker().clearTraces();
3259 }
3260 }
3261
Andrii Kulian446e8242017-10-26 15:17:29 -07003262 @Override
3263 public void handleMultiWindowModeChanged(IBinder token, boolean isInMultiWindowMode,
Winson Chung5af42fc2017-03-24 17:11:33 -07003264 Configuration overrideConfig) {
Wale Ogunwale5f986092015-12-04 15:35:38 -08003265 final ActivityClientRecord r = mActivities.get(token);
3266 if (r != null) {
Winson Chung5af42fc2017-03-24 17:11:33 -07003267 final Configuration newConfig = new Configuration(mConfiguration);
3268 if (overrideConfig != null) {
3269 newConfig.updateFrom(overrideConfig);
3270 }
3271 r.activity.dispatchMultiWindowModeChanged(isInMultiWindowMode, newConfig);
Wale Ogunwale5f986092015-12-04 15:35:38 -08003272 }
3273 }
3274
Andrii Kulian446e8242017-10-26 15:17:29 -07003275 @Override
3276 public void handlePictureInPictureModeChanged(IBinder token, boolean isInPipMode,
Winson Chung5af42fc2017-03-24 17:11:33 -07003277 Configuration overrideConfig) {
Wale Ogunwale5f986092015-12-04 15:35:38 -08003278 final ActivityClientRecord r = mActivities.get(token);
3279 if (r != null) {
Winson Chung5af42fc2017-03-24 17:11:33 -07003280 final Configuration newConfig = new Configuration(mConfiguration);
3281 if (overrideConfig != null) {
3282 newConfig.updateFrom(overrideConfig);
3283 }
3284 r.activity.dispatchPictureInPictureModeChanged(isInPipMode, newConfig);
Wale Ogunwale5f986092015-12-04 15:35:38 -08003285 }
3286 }
3287
Amith Yamasani0af6fa72016-01-17 15:36:19 -08003288 private void handleLocalVoiceInteractionStarted(IBinder token, IVoiceInteractor interactor) {
3289 final ActivityClientRecord r = mActivities.get(token);
3290 if (r != null) {
3291 r.voiceInteractor = interactor;
3292 r.activity.setVoiceInteractor(interactor);
3293 if (interactor == null) {
3294 r.activity.onLocalVoiceInteractionStopped();
3295 } else {
3296 r.activity.onLocalVoiceInteractionStarted();
3297 }
3298 }
3299 }
3300
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003301 private static boolean attemptAttachAgent(String agent, ClassLoader classLoader) {
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003302 try {
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003303 VMDebug.attachAgent(agent, classLoader);
3304 return true;
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003305 } catch (IOException e) {
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003306 Slog.e(TAG, "Attaching agent with " + classLoader + " failed: " + agent);
3307 return false;
3308 }
3309 }
3310
3311 static void handleAttachAgent(String agent, LoadedApk loadedApk) {
3312 ClassLoader classLoader = loadedApk != null ? loadedApk.getClassLoader() : null;
3313 if (attemptAttachAgent(agent, classLoader)) {
3314 return;
3315 }
3316 if (classLoader != null) {
3317 attemptAttachAgent(agent, null);
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003318 }
3319 }
3320
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003321 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
3322
3323 /**
3324 * Return the Intent that's currently being handled by a
3325 * BroadcastReceiver on this thread, or null if none.
3326 * @hide
3327 */
3328 public static Intent getIntentBeingBroadcast() {
3329 return sCurrentBroadcastIntent.get();
3330 }
3331
Romain Guy65b345f2011-07-27 18:51:50 -07003332 private void handleReceiver(ReceiverData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 // If we are getting ready to gc after going to the background, well
3334 // we are back active so skip it.
3335 unscheduleGcIdler();
3336
3337 String component = data.intent.getComponent().getClassName();
3338
Todd Kennedy233a0b12018-01-29 20:30:24 +00003339 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003340 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003342 IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343
Adam Lesinski4e862812016-11-21 16:02:24 -08003344 Application app;
Romain Guy65b345f2011-07-27 18:51:50 -07003345 BroadcastReceiver receiver;
Adam Lesinski4e862812016-11-21 16:02:24 -08003346 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003347 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00003348 app = packageInfo.makeApplication(false, mInstrumentation);
Adam Lesinski4e862812016-11-21 16:02:24 -08003349 context = (ContextImpl) app.getBaseContext();
3350 if (data.info.splitName != null) {
3351 context = (ContextImpl) context.createContextForSplit(data.info.splitName);
3352 }
3353 java.lang.ClassLoader cl = context.getClassLoader();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003354 data.intent.setExtrasClassLoader(cl);
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003355 data.intent.prepareToEnterProcess();
Dianne Hackborne829fef2010-10-26 17:44:01 -07003356 data.setExtrasClassLoader(cl);
Todd Kennedy233a0b12018-01-29 20:30:24 +00003357 receiver = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05003358 .instantiateReceiver(cl, data.info.name, data.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07003360 if (DEBUG_BROADCAST) Slog.i(TAG,
3361 "Finishing failed broadcast to " + data.intent.getComponent());
3362 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 throw new RuntimeException(
3364 "Unable to instantiate receiver " + component
3365 + ": " + e.toString(), e);
3366 }
3367
3368 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003369 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 TAG, "Performing receive of " + data.intent
3371 + ": app=" + app
3372 + ", appName=" + app.getPackageName()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003373 + ", pkg=" + packageInfo.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 + ", comp=" + data.intent.getComponent().toShortString()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003375 + ", dir=" + packageInfo.getAppDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003376
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003377 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07003378 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003379 receiver.onReceive(context.getReceiverRestrictedContext(),
3380 data.intent);
3381 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07003382 if (DEBUG_BROADCAST) Slog.i(TAG,
3383 "Finishing failed broadcast to " + data.intent.getComponent());
3384 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 if (!mInstrumentation.onException(receiver, e)) {
3386 throw new RuntimeException(
3387 "Unable to start receiver " + component
3388 + ": " + e.toString(), e);
3389 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003390 } finally {
3391 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003392 }
3393
Dianne Hackborne829fef2010-10-26 17:44:01 -07003394 if (receiver.getPendingResult() != null) {
3395 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003396 }
3397 }
3398
Christopher Tate181fafa2009-05-14 11:12:14 -07003399 // Instantiate a BackupAgent and tell it that it's alive
Romain Guy65b345f2011-07-27 18:51:50 -07003400 private void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003401 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07003402
Christopher Tate346acb12012-10-15 19:20:25 -07003403 // Sanity check the requested target package's uid against ours
3404 try {
3405 PackageInfo requestedPackage = getPackageManager().getPackageInfo(
3406 data.appInfo.packageName, 0, UserHandle.myUserId());
3407 if (requestedPackage.applicationInfo.uid != Process.myUid()) {
3408 Slog.w(TAG, "Asked to instantiate non-matching package "
3409 + data.appInfo.packageName);
3410 return;
3411 }
3412 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003413 throw e.rethrowFromSystemServer();
Christopher Tate346acb12012-10-15 19:20:25 -07003414 }
3415
Christopher Tate181fafa2009-05-14 11:12:14 -07003416 // no longer idle; we have backup work to do
3417 unscheduleGcIdler();
3418
3419 // instantiate the BackupAgent class named in the manifest
Todd Kennedy233a0b12018-01-29 20:30:24 +00003420 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
3421 String packageName = packageInfo.mPackageName;
Christopher Tate346acb12012-10-15 19:20:25 -07003422 if (packageName == null) {
3423 Slog.d(TAG, "Asked to create backup agent for nonexistent package");
3424 return;
3425 }
3426
Christopher Tate181fafa2009-05-14 11:12:14 -07003427 String classname = data.appInfo.backupAgentName;
Christopher Tate79ec80d2011-06-24 14:58:49 -07003428 // full backup operation but no app-supplied agent? use the default implementation
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003429 if (classname == null && (data.backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL
3430 || data.backupMode == ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL)) {
Christopher Tate4a627c72011-04-01 14:43:32 -07003431 classname = "android.app.backup.FullBackupAgent";
Christopher Tate181fafa2009-05-14 11:12:14 -07003432 }
Christopher Tate4a627c72011-04-01 14:43:32 -07003433
Christopher Tate181fafa2009-05-14 11:12:14 -07003434 try {
Christopher Tated1475e02009-07-09 15:36:17 -07003435 IBinder binder = null;
Christopher Tate2e40d112014-07-15 12:37:38 -07003436 BackupAgent agent = mBackupAgents.get(packageName);
3437 if (agent != null) {
3438 // reusing the existing instance
3439 if (DEBUG_BACKUP) {
3440 Slog.v(TAG, "Reusing existing agent instance");
Christopher Tated1475e02009-07-09 15:36:17 -07003441 }
Christopher Tate2e40d112014-07-15 12:37:38 -07003442 binder = agent.onBind();
3443 } else {
3444 try {
3445 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing agent class " + classname);
3446
Todd Kennedy233a0b12018-01-29 20:30:24 +00003447 java.lang.ClassLoader cl = packageInfo.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04003448 agent = (BackupAgent) cl.loadClass(classname).newInstance();
Christopher Tate2e40d112014-07-15 12:37:38 -07003449
3450 // set up the agent's context
Todd Kennedy233a0b12018-01-29 20:30:24 +00003451 ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
Christopher Tate2e40d112014-07-15 12:37:38 -07003452 context.setOuterContext(agent);
3453 agent.attach(context);
3454
3455 agent.onCreate();
3456 binder = agent.onBind();
3457 mBackupAgents.put(packageName, agent);
3458 } catch (Exception e) {
3459 // If this is during restore, fail silently; otherwise go
3460 // ahead and let the user see the crash.
3461 Slog.e(TAG, "Agent threw during creation: " + e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003462 if (data.backupMode != ApplicationThreadConstants.BACKUP_MODE_RESTORE
3463 && data.backupMode !=
3464 ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL) {
Christopher Tate2e40d112014-07-15 12:37:38 -07003465 throw e;
3466 }
3467 // falling through with 'binder' still null
3468 }
Christopher Tated1475e02009-07-09 15:36:17 -07003469 }
Christopher Tate181fafa2009-05-14 11:12:14 -07003470
3471 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07003472 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003473 ActivityManager.getService().backupAgentCreated(packageName, binder);
Christopher Tate181fafa2009-05-14 11:12:14 -07003474 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003475 throw e.rethrowFromSystemServer();
Christopher Tate181fafa2009-05-14 11:12:14 -07003476 }
Christopher Tate181fafa2009-05-14 11:12:14 -07003477 } catch (Exception e) {
3478 throw new RuntimeException("Unable to create BackupAgent "
Christopher Tate4a627c72011-04-01 14:43:32 -07003479 + classname + ": " + e.toString(), e);
Christopher Tate181fafa2009-05-14 11:12:14 -07003480 }
3481 }
3482
3483 // Tear down a BackupAgent
Romain Guy65b345f2011-07-27 18:51:50 -07003484 private void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003485 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07003486
Todd Kennedy233a0b12018-01-29 20:30:24 +00003487 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
3488 String packageName = packageInfo.mPackageName;
Christopher Tate181fafa2009-05-14 11:12:14 -07003489 BackupAgent agent = mBackupAgents.get(packageName);
3490 if (agent != null) {
3491 try {
3492 agent.onDestroy();
3493 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003494 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07003495 e.printStackTrace();
3496 }
3497 mBackupAgents.remove(packageName);
3498 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003499 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07003500 }
3501 }
3502
Romain Guy65b345f2011-07-27 18:51:50 -07003503 private void handleCreateService(CreateServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003504 // If we are getting ready to gc after going to the background, well
3505 // we are back active so skip it.
3506 unscheduleGcIdler();
3507
Todd Kennedy233a0b12018-01-29 20:30:24 +00003508 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003509 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003510 Service service = null;
3511 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00003512 java.lang.ClassLoader cl = packageInfo.getClassLoader();
3513 service = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05003514 .instantiateService(cl, data.info.name, data.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003515 } catch (Exception e) {
3516 if (!mInstrumentation.onException(service, e)) {
3517 throw new RuntimeException(
3518 "Unable to instantiate service " + data.info.name
3519 + ": " + e.toString(), e);
3520 }
3521 }
3522
3523 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003524 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003525
Todd Kennedy233a0b12018-01-29 20:30:24 +00003526 ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
Jeff Browndefd4a62014-03-10 21:24:37 -07003527 context.setOuterContext(service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528
Todd Kennedy233a0b12018-01-29 20:30:24 +00003529 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530 service.attach(context, this, data.info.name, data.token, app,
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003531 ActivityManager.getService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532 service.onCreate();
3533 mServices.put(data.token, service);
3534 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003535 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003536 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003537 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003538 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 }
3540 } catch (Exception e) {
3541 if (!mInstrumentation.onException(service, e)) {
3542 throw new RuntimeException(
3543 "Unable to create service " + data.info.name
3544 + ": " + e.toString(), e);
3545 }
3546 }
3547 }
3548
Romain Guy65b345f2011-07-27 18:51:50 -07003549 private void handleBindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003550 Service s = mServices.get(data.token);
Amith Yamasani742a6712011-05-04 14:49:28 -07003551 if (DEBUG_SERVICE)
3552 Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003553 if (s != null) {
3554 try {
3555 data.intent.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003556 data.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003557 try {
3558 if (!data.rebind) {
3559 IBinder binder = s.onBind(data.intent);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003560 ActivityManager.getService().publishService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003561 data.token, data.intent, binder);
3562 } else {
3563 s.onRebind(data.intent);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003564 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003565 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003567 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003569 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003570 }
3571 } catch (Exception e) {
3572 if (!mInstrumentation.onException(s, e)) {
3573 throw new RuntimeException(
3574 "Unable to bind to service " + s
3575 + " with " + data.intent + ": " + e.toString(), e);
3576 }
3577 }
3578 }
3579 }
3580
Romain Guy65b345f2011-07-27 18:51:50 -07003581 private void handleUnbindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003582 Service s = mServices.get(data.token);
3583 if (s != null) {
3584 try {
3585 data.intent.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003586 data.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003587 boolean doRebind = s.onUnbind(data.intent);
3588 try {
3589 if (doRebind) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003590 ActivityManager.getService().unbindFinished(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003591 data.token, data.intent, doRebind);
3592 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003593 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003594 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003595 }
3596 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003597 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003598 }
3599 } catch (Exception e) {
3600 if (!mInstrumentation.onException(s, e)) {
3601 throw new RuntimeException(
3602 "Unable to unbind to service " + s
3603 + " with " + data.intent + ": " + e.toString(), e);
3604 }
3605 }
3606 }
3607 }
3608
Dianne Hackborn625ac272010-09-17 18:29:22 -07003609 private void handleDumpService(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08003610 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3611 try {
3612 Service s = mServices.get(info.token);
3613 if (s != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07003614 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
3615 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08003616 s.dump(info.fd.getFileDescriptor(), pw, info.args);
3617 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003618 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08003619 } finally {
3620 IoUtils.closeQuietly(info.fd);
3621 StrictMode.setThreadPolicy(oldPolicy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003622 }
3623 }
3624
Dianne Hackborn625ac272010-09-17 18:29:22 -07003625 private void handleDumpActivity(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08003626 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3627 try {
3628 ActivityClientRecord r = mActivities.get(info.token);
3629 if (r != null && r.activity != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07003630 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
3631 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08003632 r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
3633 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07003634 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08003635 } finally {
3636 IoUtils.closeQuietly(info.fd);
3637 StrictMode.setThreadPolicy(oldPolicy);
Dianne Hackborn625ac272010-09-17 18:29:22 -07003638 }
3639 }
3640
Marco Nelissen18cb2872011-11-15 11:19:53 -08003641 private void handleDumpProvider(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08003642 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3643 try {
3644 ProviderClientRecord r = mLocalProviders.get(info.token);
3645 if (r != null && r.mLocalProvider != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07003646 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
3647 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08003648 r.mLocalProvider.dump(info.fd.getFileDescriptor(), pw, info.args);
3649 pw.flush();
Marco Nelissen18cb2872011-11-15 11:19:53 -08003650 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08003651 } finally {
3652 IoUtils.closeQuietly(info.fd);
3653 StrictMode.setThreadPolicy(oldPolicy);
Marco Nelissen18cb2872011-11-15 11:19:53 -08003654 }
3655 }
3656
Romain Guy65b345f2011-07-27 18:51:50 -07003657 private void handleServiceArgs(ServiceArgsData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 Service s = mServices.get(data.token);
3659 if (s != null) {
3660 try {
3661 if (data.args != null) {
3662 data.args.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003663 data.args.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003664 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003665 int res;
3666 if (!data.taskRemoved) {
3667 res = s.onStartCommand(data.args, data.flags, data.startId);
3668 } else {
3669 s.onTaskRemoved(data.args);
3670 res = Service.START_TASK_REMOVED_COMPLETE;
3671 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003672
3673 QueuedWork.waitToFinish();
3674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003675 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003676 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003677 data.token, SERVICE_DONE_EXECUTING_START, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003678 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003679 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003680 }
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08003681 ensureJitEnabled();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003682 } catch (Exception e) {
3683 if (!mInstrumentation.onException(s, e)) {
3684 throw new RuntimeException(
3685 "Unable to start service " + s
3686 + " with " + data.args + ": " + e.toString(), e);
3687 }
3688 }
3689 }
3690 }
3691
Romain Guy65b345f2011-07-27 18:51:50 -07003692 private void handleStopService(IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003693 Service s = mServices.remove(token);
3694 if (s != null) {
3695 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003696 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003697 s.onDestroy();
Amith Yamasani75928252017-05-22 15:10:47 -07003698 s.detachAndCleanUp();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08003700 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003701 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08003702 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003703 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003704
3705 QueuedWork.waitToFinish();
3706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003707 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003708 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003709 token, SERVICE_DONE_EXECUTING_STOP, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003711 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003712 }
3713 } catch (Exception e) {
3714 if (!mInstrumentation.onException(s, e)) {
3715 throw new RuntimeException(
3716 "Unable to stop service " + s
3717 + ": " + e.toString(), e);
3718 }
Craig Mautner66c4a822015-01-16 12:48:16 -08003719 Slog.i(TAG, "handleStopService: exception for " + token, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720 }
Craig Mautner9776ad42015-01-15 14:38:39 -08003721 } else {
3722 Slog.i(TAG, "handleStopService: token=" + token + " not found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003724 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003725 }
3726
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003727 /**
3728 * Resume the activity.
3729 * @param token Target activity token.
3730 * @param finalStateRequest Flag indicating if this is part of final state resolution for a
3731 * transaction.
3732 * @param reason Reason for performing the action.
3733 *
3734 * @return The {@link ActivityClientRecord} that was resumed, {@code null} otherwise.
3735 */
3736 @VisibleForTesting
3737 public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
Andrii Kuliandfbf9712018-03-08 15:42:24 -08003738 String reason) {
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003739 final ActivityClientRecord r = mActivities.get(token);
3740 if (localLOGV) {
3741 Slog.v(TAG, "Performing resume of " + r + " finished=" + r.activity.mFinished);
3742 }
3743 if (r == null || r.activity.mFinished) {
3744 return null;
3745 }
3746 if (r.getLifecycleState() == ON_RESUME) {
3747 if (!finalStateRequest) {
3748 final RuntimeException e = new IllegalStateException(
3749 "Trying to resume activity which is already resumed");
3750 Slog.e(TAG, e.getMessage(), e);
3751 Slog.e(TAG, r.getStateString());
3752 // TODO(lifecycler): A double resume request is possible when an activity
3753 // receives two consequent transactions with relaunch requests and "resumed"
3754 // final state requests and the second relaunch is omitted. We still try to
3755 // handle two resume requests for the final state. For cases other than this
3756 // one, we don't expect it to happen.
Andrii Kulian9956d892018-02-14 13:48:56 -08003757 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003758 return null;
3759 }
3760 if (finalStateRequest) {
3761 r.hideForNow = false;
3762 r.activity.mStartedActivity = false;
3763 }
3764 try {
3765 r.activity.onStateNotSaved();
3766 r.activity.mFragments.noteStateNotSaved();
3767 checkAndBlockForNetworkAccess();
3768 if (r.pendingIntents != null) {
3769 deliverNewIntents(r, r.pendingIntents);
3770 r.pendingIntents = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003771 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003772 if (r.pendingResults != null) {
Andrii Kuliane55b0092018-04-19 15:29:22 -07003773 deliverResults(r, r.pendingResults, reason);
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003774 r.pendingResults = null;
3775 }
3776 r.activity.performResume(r.startsNotResumed, reason);
Bob Leee5408332009-09-04 18:31:17 -07003777
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003778 r.state = null;
3779 r.persistentState = null;
3780 r.setState(ON_RESUME);
3781 } catch (Exception e) {
3782 if (!mInstrumentation.onException(r.activity, e)) {
3783 throw new RuntimeException("Unable to resume activity "
3784 + r.intent.getComponent().toShortString() + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003785 }
3786 }
3787 return r;
3788 }
3789
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003790 static final void cleanUpPendingRemoveWindows(ActivityClientRecord r, boolean force) {
3791 if (r.mPreserveWindow && !force) {
3792 return;
3793 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003794 if (r.mPendingRemoveWindow != null) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003795 r.mPendingRemoveWindowManager.removeViewImmediate(
3796 r.mPendingRemoveWindow.getDecorView());
3797 IBinder wtoken = r.mPendingRemoveWindow.getDecorView().getWindowToken();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003798 if (wtoken != null) {
Jeff Brown98365d72012-08-19 20:30:52 -07003799 WindowManagerGlobal.getInstance().closeAll(wtoken,
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003800 r.activity.getClass().getName(), "Activity");
3801 }
3802 }
3803 r.mPendingRemoveWindow = null;
3804 r.mPendingRemoveWindowManager = null;
3805 }
3806
Andrii Kulian446e8242017-10-26 15:17:29 -07003807 @Override
Andrii Kuliandfbf9712018-03-08 15:42:24 -08003808 public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003809 String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810 // If we are getting ready to gc after going to the background, well
3811 // we are back active so skip it.
3812 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003813 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003814
Adam Powellcfbe9be2013-11-06 14:58:58 -08003815 // TODO Push resumeArgs into the activity for consideration
Andrii Kuliandfbf9712018-03-08 15:42:24 -08003816 final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003817 if (r == null) {
3818 // We didn't actually resume the activity, so skipping any follow-up actions.
3819 return;
3820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003821
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003822 final Activity a = r.activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003824 if (localLOGV) {
3825 Slog.v(TAG, "Resume " + r + " started activity: " + a.mStartedActivity
3826 + ", hideForNow: " + r.hideForNow + ", finished: " + a.mFinished);
3827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003828
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003829 final int forwardBit = isForward
3830 ? WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07003831
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003832 // If the window hasn't yet been added to the window manager,
3833 // and this guy didn't finish itself or start another activity,
3834 // then go ahead and add the window.
3835 boolean willBeVisible = !a.mStartedActivity;
3836 if (!willBeVisible) {
3837 try {
3838 willBeVisible = ActivityManager.getService().willActivityBeVisible(
3839 a.getActivityToken());
3840 } catch (RemoteException e) {
3841 throw e.rethrowFromSystemServer();
3842 }
3843 }
3844 if (r.window == null && !a.mFinished && willBeVisible) {
3845 r.window = r.activity.getWindow();
3846 View decor = r.window.getDecorView();
3847 decor.setVisibility(View.INVISIBLE);
3848 ViewManager wm = a.getWindowManager();
3849 WindowManager.LayoutParams l = r.window.getAttributes();
3850 a.mDecor = decor;
3851 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
3852 l.softInputMode |= forwardBit;
3853 if (r.mPreserveWindow) {
3854 a.mWindowAdded = true;
3855 r.mPreserveWindow = false;
3856 // Normally the ViewRoot sets up callbacks with the Activity
3857 // in addView->ViewRootImpl#setView. If we are instead reusing
3858 // the decor view we have to notify the view root that the
3859 // callbacks may have changed.
3860 ViewRootImpl impl = decor.getViewRootImpl();
3861 if (impl != null) {
3862 impl.notifyChildRebuilt();
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003863 }
3864 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003865 if (a.mVisibleFromClient) {
3866 if (!a.mWindowAdded) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003867 a.mWindowAdded = true;
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003868 wm.addView(decor, l);
3869 } else {
3870 // The activity will get a callback for this {@link LayoutParams} change
3871 // earlier. However, at that time the decor will not be set (this is set
3872 // in this method), so no action will be taken. This call ensures the
3873 // callback occurs with the decor set.
3874 a.onWindowAttributesChanged(l);
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003875 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877
3878 // If the window has already been added, but during resume
3879 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08003880 // window visible.
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003881 } else if (!willBeVisible) {
3882 if (localLOGV) Slog.v(TAG, "Launch " + r + " mStartedActivity set");
3883 r.hideForNow = true;
3884 }
3885
3886 // Get rid of anything left hanging around.
3887 cleanUpPendingRemoveWindows(r, false /* force */);
3888
3889 // The window is now visible if it has been added, we are not
3890 // simply finishing, and we are not starting another activity.
3891 if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) {
3892 if (r.newConfig != null) {
3893 performConfigurationChangedForActivity(r, r.newConfig);
3894 if (DEBUG_CONFIGURATION) {
3895 Slog.v(TAG, "Resuming activity " + r.activityInfo.name + " with newConfig "
3896 + r.activity.mCurrentConfig);
3897 }
3898 r.newConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003900 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward=" + isForward);
3901 WindowManager.LayoutParams l = r.window.getAttributes();
3902 if ((l.softInputMode
3903 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
3904 != forwardBit) {
3905 l.softInputMode = (l.softInputMode
3906 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
3907 | forwardBit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 if (r.activity.mVisibleFromClient) {
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003909 ViewManager wm = a.getWindowManager();
3910 View decor = r.window.getDecorView();
3911 wm.updateViewLayout(decor, l);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 }
3913 }
3914
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003915 r.activity.mVisibleFromServer = true;
3916 mNumVisibleActivities++;
3917 if (r.activity.mVisibleFromClient) {
3918 r.activity.makeVisible();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919 }
3920 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003921
3922 r.nextIdle = mNewActivities;
3923 mNewActivities = r;
3924 if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);
3925 Looper.myQueue().addIdleHandler(new Idler());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003926 }
3927
Andrii Kulian446e8242017-10-26 15:17:29 -07003928 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003929 public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
Andrii Kuliana6176e32018-02-27 11:51:18 -08003930 int configChanges, PendingTransactionActions pendingActions, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003931 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003932 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 if (userLeaving) {
3934 performUserLeavingActivity(r);
3935 }
Bob Leee5408332009-09-04 18:31:17 -07003936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 r.activity.mConfigChangeFlags |= configChanges;
Andrii Kuliand25680c2018-02-21 15:16:58 -08003938 performPauseActivity(r, finished, reason, pendingActions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003939
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07003940 // Make sure any pending writes are now committed.
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08003941 if (r.isPreHoneycomb()) {
3942 QueuedWork.waitToFinish();
3943 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003944 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 }
3946 }
3947
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003948 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 mInstrumentation.callActivityOnUserLeaving(r.activity);
3950 }
3951
Andrii Kulian8ae79572018-01-26 15:36:06 -08003952 final Bundle performPauseActivity(IBinder token, boolean finished, String reason,
3953 PendingTransactionActions pendingActions) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003954 ActivityClientRecord r = mActivities.get(token);
Andrii Kulian8ae79572018-01-26 15:36:06 -08003955 return r != null ? performPauseActivity(r, finished, reason, pendingActions) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003956 }
3957
Andrii Kulian8ae79572018-01-26 15:36:06 -08003958 /**
3959 * Pause the activity.
3960 * @return Saved instance state for pre-Honeycomb apps if it was saved, {@code null} otherwise.
3961 */
3962 private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
3963 PendingTransactionActions pendingActions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964 if (r.paused) {
3965 if (r.activity.mFinished) {
3966 // If we are finishing, we won't call onResume() in certain cases.
3967 // So here we likewise don't want to call onPause() if the activity
3968 // isn't resumed.
3969 return null;
3970 }
3971 RuntimeException e = new RuntimeException(
3972 "Performing pause of activity that is not resumed: "
3973 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003974 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003976 if (finished) {
3977 r.activity.mFinished = true;
3978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003979
Andrii Kulian8ae79572018-01-26 15:36:06 -08003980 // Pre-Honeycomb apps always save their state before pausing
3981 final boolean shouldSaveState = !r.activity.mFinished && r.isPreHoneycomb();
3982 if (shouldSaveState) {
3983 callActivityOnSaveInstanceState(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984 }
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07003985
3986 performPauseActivityIfNeeded(r, reason);
Jeff Hamilton52d32032011-01-08 15:31:26 -06003987
3988 // Notify any outstanding on paused listeners
3989 ArrayList<OnActivityPausedListener> listeners;
3990 synchronized (mOnPauseListeners) {
3991 listeners = mOnPauseListeners.remove(r.activity);
3992 }
3993 int size = (listeners != null ? listeners.size() : 0);
3994 for (int i = 0; i < size; i++) {
3995 listeners.get(i).onPaused(r.activity);
3996 }
3997
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003998 final Bundle oldState = pendingActions != null ? pendingActions.getOldState() : null;
3999 if (oldState != null) {
4000 // We need to keep around the original state, in case we need to be created again.
4001 // But we only do this for pre-Honeycomb apps, which always save their state when
4002 // pausing, so we can not have them save their state when restarting from a paused
4003 // state. For HC and later, we want to (and can) let the state be saved as the
4004 // normal part of stopping the activity.
4005 if (r.isPreHoneycomb()) {
4006 r.state = oldState;
4007 }
4008 }
4009
Andrii Kulian8ae79572018-01-26 15:36:06 -08004010 return shouldSaveState ? r.state : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 }
4012
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004013 private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
4014 if (r.paused) {
4015 // You are already paused silly...
4016 return;
4017 }
4018
4019 try {
4020 r.activity.mCalled = false;
4021 mInstrumentation.callActivityOnPause(r.activity);
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004022 if (!r.activity.mCalled) {
4023 throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
4024 + " did not call through to super.onPause()");
4025 }
4026 } catch (SuperNotCalledException e) {
4027 throw e;
4028 } catch (Exception e) {
4029 if (!mInstrumentation.onException(r.activity, e)) {
4030 throw new RuntimeException("Unable to pause activity "
4031 + safeToComponentShortString(r.intent) + ": " + e.toString(), e);
4032 }
4033 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004034 r.setState(ON_PAUSE);
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004035 }
4036
Andrii Kulian829829c2018-03-19 18:19:05 -07004037 /** Called from {@link LocalActivityManager}. */
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08004038 final void performStopActivity(IBinder token, boolean saveState, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004039 ActivityClientRecord r = mActivities.get(token);
Andrii Kulian829829c2018-03-19 18:19:05 -07004040 performStopActivityInner(r, null /* stopInfo */, false /* keepShown */, saveState,
4041 false /* finalStateRequest */, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004042 }
4043
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004044 private static final class ProviderRefCount {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07004045 public final ContentProviderHolder holder;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004046 public final ProviderClientRecord client;
4047 public int stableCount;
4048 public int unstableCount;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004049
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004050 // When this is set, the stable and unstable ref counts are 0 and
4051 // we have a pending operation scheduled to remove the ref count
4052 // from the activity manager. On the activity manager we are still
4053 // holding an unstable ref, though it is not reflected in the counts
4054 // here.
4055 public boolean removePending;
4056
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07004057 ProviderRefCount(ContentProviderHolder inHolder,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004058 ProviderClientRecord inClient, int sCount, int uCount) {
4059 holder = inHolder;
4060 client = inClient;
4061 stableCount = sCount;
4062 unstableCount = uCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 }
4064 }
4065
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004066 /**
4067 * Core implementation of stopping an activity. Note this is a little
4068 * tricky because the server's meaning of stop is slightly different
4069 * than our client -- for the server, stop means to save state and give
4070 * it the result when it is done, but the window may still be visible.
4071 * For the client, we want to call onStop()/onStart() to indicate when
Wale Ogunwaleb5066fe2016-09-21 07:33:43 -07004072 * the activity's UI visibility changes.
Andrii Kulian829829c2018-03-19 18:19:05 -07004073 * @param r Target activity client record.
4074 * @param info Action that will report activity stop to server.
4075 * @param keepShown Flag indicating whether the activity is still shown.
4076 * @param saveState Flag indicating whether the activity state should be saved.
4077 * @param finalStateRequest Flag indicating if this call is handling final lifecycle state
4078 * request for a transaction.
4079 * @param reason Reason for performing this operation.
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004080 */
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004081 private void performStopActivityInner(ActivityClientRecord r, StopInfo info, boolean keepShown,
Andrii Kulian829829c2018-03-19 18:19:05 -07004082 boolean saveState, boolean finalStateRequest, String reason) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004083 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 if (r != null) {
4085 if (!keepShown && r.stopped) {
4086 if (r.activity.mFinished) {
4087 // If we are finishing, we won't call onResume() in certain
4088 // cases. So here we likewise don't want to call onStop()
4089 // if the activity isn't resumed.
4090 return;
4091 }
Andrii Kulian829829c2018-03-19 18:19:05 -07004092 if (!finalStateRequest) {
4093 final RuntimeException e = new RuntimeException(
4094 "Performing stop of activity that is already stopped: "
4095 + r.intent.getComponent().toShortString());
4096 Slog.e(TAG, e.getMessage(), e);
4097 Slog.e(TAG, r.getStateString());
4098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004099 }
4100
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004101 // One must first be paused before stopped...
4102 performPauseActivityIfNeeded(r, reason);
4103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004104 if (info != null) {
4105 try {
4106 // First create a thumbnail for the activity...
Dianne Hackborn0500b3c2011-11-01 15:28:43 -07004107 // For now, don't create the thumbnail here; we are
4108 // doing that by doing a screen snapshot.
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004109 info.setDescription(r.activity.onCreateDescription());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004110 } catch (Exception e) {
4111 if (!mInstrumentation.onException(r.activity, e)) {
4112 throw new RuntimeException(
4113 "Unable to save state of activity "
4114 + r.intent.getComponent().toShortString()
4115 + ": " + e.toString(), e);
4116 }
4117 }
4118 }
4119
4120 if (!keepShown) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004121 callActivityOnStop(r, saveState, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004123 }
4124 }
4125
Andrii Kulian8ae79572018-01-26 15:36:06 -08004126 /**
4127 * Calls {@link Activity#onStop()} and {@link Activity#onSaveInstanceState(Bundle)}, and updates
4128 * the client record's state.
4129 * All calls to stop an activity must be done through this method to make sure that
4130 * {@link Activity#onSaveInstanceState(Bundle)} is also executed in the same call.
4131 */
4132 private void callActivityOnStop(ActivityClientRecord r, boolean saveState, String reason) {
Andrii Kulian391161f2018-01-29 10:50:02 -08004133 // Before P onSaveInstanceState was called before onStop, starting with P it's
4134 // called after. Before Honeycomb state was always saved before onPause.
Andrii Kulian8ae79572018-01-26 15:36:06 -08004135 final boolean shouldSaveState = saveState && !r.activity.mFinished && r.state == null
4136 && !r.isPreHoneycomb();
Andrii Kulian391161f2018-01-29 10:50:02 -08004137 final boolean isPreP = r.isPreP();
4138 if (shouldSaveState && isPreP) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004139 callActivityOnSaveInstanceState(r);
4140 }
4141
4142 try {
Andrii Kuliand25680c2018-02-21 15:16:58 -08004143 r.activity.performStop(false /*preserveWindow*/, reason);
Andrii Kulian8ae79572018-01-26 15:36:06 -08004144 } catch (SuperNotCalledException e) {
4145 throw e;
4146 } catch (Exception e) {
4147 if (!mInstrumentation.onException(r.activity, e)) {
4148 throw new RuntimeException(
4149 "Unable to stop activity "
4150 + r.intent.getComponent().toShortString()
4151 + ": " + e.toString(), e);
4152 }
4153 }
4154 r.setState(ON_STOP);
Andrii Kulian391161f2018-01-29 10:50:02 -08004155
4156 if (shouldSaveState && !isPreP) {
4157 callActivityOnSaveInstanceState(r);
4158 }
Andrii Kulian8ae79572018-01-26 15:36:06 -08004159 }
4160
Romain Guy65b345f2011-07-27 18:51:50 -07004161 private void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004162 View v = r.activity.mDecor;
4163 if (v != null) {
4164 if (show) {
4165 if (!r.activity.mVisibleFromServer) {
4166 r.activity.mVisibleFromServer = true;
4167 mNumVisibleActivities++;
4168 if (r.activity.mVisibleFromClient) {
4169 r.activity.makeVisible();
4170 }
4171 }
4172 if (r.newConfig != null) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004173 performConfigurationChangedForActivity(r, r.newConfig);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004174 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Adam Lesinski082614c2016-03-04 14:33:47 -08004175 + r.activityInfo.name + " with new config "
4176 + r.activity.mCurrentConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004177 r.newConfig = null;
4178 }
4179 } else {
4180 if (r.activity.mVisibleFromServer) {
4181 r.activity.mVisibleFromServer = false;
4182 mNumVisibleActivities--;
4183 v.setVisibility(View.INVISIBLE);
4184 }
4185 }
4186 }
4187 }
4188
Andrii Kulian446e8242017-10-26 15:17:29 -07004189 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004190 public void handleStopActivity(IBinder token, boolean show, int configChanges,
Andrii Kulian829829c2018-03-19 18:19:05 -07004191 PendingTransactionActions pendingActions, boolean finalStateRequest, String reason) {
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004192 final ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004193 r.activity.mConfigChangeFlags |= configChanges;
4194
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004195 final StopInfo stopInfo = new StopInfo();
Andrii Kulian829829c2018-03-19 18:19:05 -07004196 performStopActivityInner(r, stopInfo, show, true /* saveState */, finalStateRequest,
4197 reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004198
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004199 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004200 TAG, "Finishing stop of " + r + ": show=" + show
4201 + " win=" + r.window);
4202
4203 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07004204
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004205 // Make sure any pending writes are now committed.
4206 if (!r.isPreHoneycomb()) {
4207 QueuedWork.waitToFinish();
4208 }
4209
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004210 stopInfo.setActivity(r);
4211 stopInfo.setState(r.state);
4212 stopInfo.setPersistentState(r.persistentState);
4213 pendingActions.setStopInfo(stopInfo);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004214 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004215 }
4216
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004217 /**
4218 * Schedule the call to tell the activity manager we have stopped. We don't do this
4219 * immediately, because we want to have a chance for any other pending work (in particular
4220 * memory trim requests) to complete before you tell the activity manager to proceed and allow
4221 * us to go fully into the background.
4222 */
4223 @Override
4224 public void reportStop(PendingTransactionActions pendingActions) {
4225 mH.post(pendingActions.getStopInfo());
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07004226 }
4227
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004228 @Override
4229 public void performRestartActivity(IBinder token, boolean start) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004230 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004231 if (r.stopped) {
Andrii Kuliand25680c2018-02-21 15:16:58 -08004232 r.activity.performRestart(start, "performRestartActivity");
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004233 if (start) {
4234 r.setState(ON_START);
4235 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004236 }
4237 }
4238
Andrii Kulian446e8242017-10-26 15:17:29 -07004239 @Override
4240 public void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004241 ActivityClientRecord r = mActivities.get(token);
Tim Murraye1e6c662015-04-07 13:24:14 -07004242
Dianne Hackbornbfddc0f2010-12-14 11:28:01 -08004243 if (r == null) {
4244 Log.w(TAG, "handleWindowVisibility: no activity for token " + token);
4245 return;
4246 }
Tim Murraye1e6c662015-04-07 13:24:14 -07004247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 if (!show && !r.stopped) {
Andrii Kulian829829c2018-03-19 18:19:05 -07004249 performStopActivityInner(r, null /* stopInfo */, show, false /* saveState */,
4250 false /* finalStateRequest */, "handleWindowVisibility");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004251 } else if (show && r.stopped) {
4252 // If we are getting ready to gc after going to the background, well
4253 // we are back active so skip it.
4254 unscheduleGcIdler();
4255
Andrii Kuliand25680c2018-02-21 15:16:58 -08004256 r.activity.performRestart(true /* start */, "handleWindowVisibility");
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004257 r.setState(ON_START);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 }
4259 if (r.activity.mDecor != null) {
Joe Onorato43a17652011-04-06 19:22:23 -07004260 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 TAG, "Handle window " + r + " visibility: " + show);
4262 updateVisibility(r, show);
4263 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004264 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004265 }
4266
Wale Ogunwaleb5066fe2016-09-21 07:33:43 -07004267 // TODO: This method should be changed to use {@link #performStopActivityInner} to perform to
4268 // stop operation on the activity to reduce code duplication and the chance of fixing a bug in
4269 // one place and missing the other.
Romain Guy65b345f2011-07-27 18:51:50 -07004270 private void handleSleeping(IBinder token, boolean sleeping) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004271 ActivityClientRecord r = mActivities.get(token);
4272
4273 if (r == null) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08004274 Log.w(TAG, "handleSleeping: no activity for token " + token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004275 return;
4276 }
4277
4278 if (sleeping) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08004279 if (!r.stopped && !r.isPreHoneycomb()) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004280 callActivityOnStop(r, true /* saveState */, "sleeping");
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004281 }
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004282
4283 // Make sure any pending writes are now committed.
4284 if (!r.isPreHoneycomb()) {
4285 QueuedWork.waitToFinish();
4286 }
4287
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004288 // Tell activity manager we slept.
4289 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004290 ActivityManager.getService().activitySlept(r.token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004291 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004292 throw ex.rethrowFromSystemServer();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004293 }
4294 } else {
4295 if (r.stopped && r.activity.mVisibleFromServer) {
Andrii Kuliand25680c2018-02-21 15:16:58 -08004296 r.activity.performRestart(true /* start */, "handleSleeping");
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004297 r.setState(ON_START);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004298 }
4299 }
4300 }
4301
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004302 private void handleSetCoreSettings(Bundle coreSettings) {
Craig Mautner88c05892013-06-28 09:47:45 -07004303 synchronized (mResourcesManager) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08004304 mCoreSettings = coreSettings;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004305 }
Jon Miranda836c0a82014-08-11 12:32:26 -07004306 onCoreSettingsChange();
4307 }
4308
4309 private void onCoreSettingsChange() {
4310 boolean debugViewAttributes =
4311 mCoreSettings.getInt(Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0;
4312 if (debugViewAttributes != View.mDebugViewAttributes) {
4313 View.mDebugViewAttributes = debugViewAttributes;
4314
4315 // request all activities to relaunch for the changes to take place
Wale Ogunwale5527a502018-02-20 18:18:21 -08004316 relaunchAllActivities();
Fyodor Kupolovcb93d6f2017-05-04 17:27:16 -07004317 }
4318 }
4319
Wale Ogunwale5527a502018-02-20 18:18:21 -08004320 private void relaunchAllActivities() {
Fyodor Kupolovcb93d6f2017-05-04 17:27:16 -07004321 for (Map.Entry<IBinder, ActivityClientRecord> entry : mActivities.entrySet()) {
4322 final Activity activity = entry.getValue().activity;
4323 if (!activity.mFinished) {
Andrii Kulian320e3b52018-05-03 16:26:25 -07004324 scheduleRelaunchActivity(entry.getKey());
Jon Miranda836c0a82014-08-11 12:32:26 -07004325 }
4326 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004327 }
4328
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004329 private void handleUpdatePackageCompatibilityInfo(UpdateCompatibilityData data) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00004330 LoadedApk apk = peekPackageInfo(data.pkg, false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004331 if (apk != null) {
Craig Mautner48d0d182013-06-11 07:53:06 -07004332 apk.setCompatibilityInfo(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004333 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00004334 apk = peekPackageInfo(data.pkg, true);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004335 if (apk != null) {
Craig Mautner48d0d182013-06-11 07:53:06 -07004336 apk.setCompatibilityInfo(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004337 }
4338 handleConfigurationChanged(mConfiguration, data.info);
Jeff Brown98365d72012-08-19 20:30:52 -07004339 WindowManagerGlobal.getInstance().reportNewConfiguration(mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004340 }
4341
Andrii Kuliane55b0092018-04-19 15:29:22 -07004342 private void deliverResults(ActivityClientRecord r, List<ResultInfo> results, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004343 final int N = results.size();
4344 for (int i=0; i<N; i++) {
4345 ResultInfo ri = results.get(i);
4346 try {
4347 if (ri.mData != null) {
4348 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01004349 ri.mData.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004350 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004351 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07004352 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004353 r.activity.dispatchActivityResult(ri.mResultWho,
Andrii Kuliane55b0092018-04-19 15:29:22 -07004354 ri.mRequestCode, ri.mResultCode, ri.mData, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004355 } catch (Exception e) {
4356 if (!mInstrumentation.onException(r.activity, e)) {
4357 throw new RuntimeException(
4358 "Failure delivering result " + ri + " to activity "
4359 + r.intent.getComponent().toShortString()
4360 + ": " + e.toString(), e);
4361 }
4362 }
4363 }
4364 }
4365
Andrii Kulian446e8242017-10-26 15:17:29 -07004366 @Override
Andrii Kuliane55b0092018-04-19 15:29:22 -07004367 public void handleSendResult(IBinder token, List<ResultInfo> results, String reason) {
Andrii Kulian446e8242017-10-26 15:17:29 -07004368 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004369 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004370 if (r != null) {
4371 final boolean resumed = !r.paused;
4372 if (!r.activity.mFinished && r.activity.mDecor != null
4373 && r.hideForNow && resumed) {
4374 // We had hidden the activity because it started another
4375 // one... we have gotten a result back and we are not
4376 // paused, so make sure our window is visible.
4377 updateVisibility(r, true);
4378 }
4379 if (resumed) {
4380 try {
4381 // Now we are idle.
4382 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004383 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004384 mInstrumentation.callActivityOnPause(r.activity);
4385 if (!r.activity.mCalled) {
4386 throw new SuperNotCalledException(
4387 "Activity " + r.intent.getComponent().toShortString()
4388 + " did not call through to super.onPause()");
4389 }
4390 } catch (SuperNotCalledException e) {
4391 throw e;
4392 } catch (Exception e) {
4393 if (!mInstrumentation.onException(r.activity, e)) {
4394 throw new RuntimeException(
4395 "Unable to pause activity "
4396 + r.intent.getComponent().toShortString()
4397 + ": " + e.toString(), e);
4398 }
4399 }
4400 }
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07004401 checkAndBlockForNetworkAccess();
Andrii Kuliane55b0092018-04-19 15:29:22 -07004402 deliverResults(r, results, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004403 if (resumed) {
Andrii Kuliane55b0092018-04-19 15:29:22 -07004404 r.activity.performResume(false, reason);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004405 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004406 }
4407 }
4408 }
4409
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004410 /** Core implementation of activity destroy call. */
4411 ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
Bryce Leea33c13d2018-02-08 14:37:06 -08004412 int configChanges, boolean getNonConfigInstance, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004413 ActivityClientRecord r = mActivities.get(token);
Craig Mautner88c05892013-06-28 09:47:45 -07004414 Class<? extends Activity> activityClass = null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004415 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004416 if (r != null) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08004417 activityClass = r.activity.getClass();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004418 r.activity.mConfigChangeFlags |= configChanges;
4419 if (finishing) {
4420 r.activity.mFinished = true;
4421 }
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004422
4423 performPauseActivityIfNeeded(r, "destroy");
4424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004425 if (!r.stopped) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004426 callActivityOnStop(r, false /* saveState */, "destroy");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004427 }
4428 if (getNonConfigInstance) {
4429 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004430 r.lastNonConfigurationInstances
4431 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004432 } catch (Exception e) {
4433 if (!mInstrumentation.onException(r.activity, e)) {
4434 throw new RuntimeException(
4435 "Unable to retain activity "
4436 + r.intent.getComponent().toShortString()
4437 + ": " + e.toString(), e);
4438 }
4439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004440 }
4441 try {
4442 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004443 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004444 if (!r.activity.mCalled) {
4445 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004446 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004447 " did not call through to super.onDestroy()");
4448 }
4449 if (r.window != null) {
4450 r.window.closeAllPanels();
4451 }
4452 } catch (SuperNotCalledException e) {
4453 throw e;
4454 } catch (Exception e) {
4455 if (!mInstrumentation.onException(r.activity, e)) {
4456 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004457 "Unable to destroy activity " + safeToComponentShortString(r.intent)
4458 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004459 }
4460 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004461 r.setState(ON_DESTROY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004462 }
4463 mActivities.remove(token);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08004464 StrictMode.decrementExpectedActivityCount(activityClass);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004465 return r;
4466 }
4467
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004468 private static String safeToComponentShortString(Intent intent) {
4469 ComponentName component = intent.getComponent();
4470 return component == null ? "[Unknown]" : component.toShortString();
4471 }
4472
Andrii Kulian446e8242017-10-26 15:17:29 -07004473 @Override
4474 public void handleDestroyActivity(IBinder token, boolean finishing, int configChanges,
Bryce Leea33c13d2018-02-08 14:37:06 -08004475 boolean getNonConfigInstance, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004476 ActivityClientRecord r = performDestroyActivity(token, finishing,
Bryce Leea33c13d2018-02-08 14:37:06 -08004477 configChanges, getNonConfigInstance, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004478 if (r != null) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004479 cleanUpPendingRemoveWindows(r, finishing);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004480 WindowManager wm = r.activity.getWindowManager();
4481 View v = r.activity.mDecor;
4482 if (v != null) {
4483 if (r.activity.mVisibleFromServer) {
4484 mNumVisibleActivities--;
4485 }
4486 IBinder wtoken = v.getWindowToken();
4487 if (r.activity.mWindowAdded) {
Robert Carr77bdfb52016-05-02 18:18:31 -07004488 if (r.mPreserveWindow) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004489 // Hold off on removing this until the new activity's
4490 // window is being added.
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004491 r.mPendingRemoveWindow = r.window;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004492 r.mPendingRemoveWindowManager = wm;
Andrii Kulianeac0ea52016-05-11 15:50:24 -07004493 // We can only keep the part of the view hierarchy that we control,
4494 // everything else must be removed, because it might not be able to
4495 // behave properly when activity is relaunching.
4496 r.window.clearContentView();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004497 } else {
4498 wm.removeViewImmediate(v);
4499 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004500 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004501 if (wtoken != null && r.mPendingRemoveWindow == null) {
Jeff Brown98365d72012-08-19 20:30:52 -07004502 WindowManagerGlobal.getInstance().closeAll(wtoken,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004503 r.activity.getClass().getName(), "Activity");
Andrii Kulianeac0ea52016-05-11 15:50:24 -07004504 } else if (r.mPendingRemoveWindow != null) {
4505 // We're preserving only one window, others should be closed so app views
4506 // will be detached before the final tear down. It should be done now because
4507 // some components (e.g. WebView) rely on detach callbacks to perform receiver
4508 // unregister and other cleanup.
4509 WindowManagerGlobal.getInstance().closeAllExceptView(token, v,
4510 r.activity.getClass().getName(), "Activity");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004511 }
4512 r.activity.mDecor = null;
4513 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004514 if (r.mPendingRemoveWindow == null) {
4515 // If we are delaying the removal of the activity window, then
4516 // we can't clean up all windows here. Note that we can't do
4517 // so later either, which means any windows that aren't closed
4518 // by the app will leak. Well we try to warning them a lot
4519 // about leaking windows, because that is a bug, so if they are
4520 // using this recreate facility then they get to live with leaks.
Jeff Brown98365d72012-08-19 20:30:52 -07004521 WindowManagerGlobal.getInstance().closeAll(token,
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004522 r.activity.getClass().getName(), "Activity");
4523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004524
4525 // Mocked out contexts won't be participating in the normal
4526 // process lifecycle, but if we're running with a proper
4527 // ApplicationContext we need to have it tear down things
4528 // cleanly.
4529 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08004530 if (c instanceof ContextImpl) {
4531 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004532 r.activity.getClass().getName(), "Activity");
4533 }
4534 }
4535 if (finishing) {
4536 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004537 ActivityManager.getService().activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004538 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004539 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004540 }
4541 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004542 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004543 }
4544
Andrii Kulianb372da62018-01-18 10:46:24 -08004545 @Override
4546 public ActivityClientRecord prepareRelaunchActivity(IBinder token,
Dianne Hackborn85d558c2014-11-04 10:31:54 -08004547 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
Andrii Kulianb372da62018-01-18 10:46:24 -08004548 int configChanges, MergedConfiguration config, boolean preserveWindow) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004549 ActivityClientRecord target = null;
Andrii Kulianb372da62018-01-18 10:46:24 -08004550 boolean scheduleRelaunch = false;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004551
Craig Mautner88c05892013-06-28 09:47:45 -07004552 synchronized (mResourcesManager) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004553 for (int i=0; i<mRelaunchingActivities.size(); i++) {
4554 ActivityClientRecord r = mRelaunchingActivities.get(i);
Filip Gruszczynskic3b61792016-01-22 16:43:48 -08004555 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: " + this + ", trying: " + r);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004556 if (r.token == token) {
4557 target = r;
4558 if (pendingResults != null) {
4559 if (r.pendingResults != null) {
4560 r.pendingResults.addAll(pendingResults);
4561 } else {
4562 r.pendingResults = pendingResults;
4563 }
4564 }
4565 if (pendingNewIntents != null) {
4566 if (r.pendingIntents != null) {
4567 r.pendingIntents.addAll(pendingNewIntents);
4568 } else {
4569 r.pendingIntents = pendingNewIntents;
4570 }
4571 }
4572 break;
4573 }
4574 }
4575
4576 if (target == null) {
Andrii Kulianb372da62018-01-18 10:46:24 -08004577 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: target is null");
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004578 target = new ActivityClientRecord();
4579 target.token = token;
4580 target.pendingResults = pendingResults;
4581 target.pendingIntents = pendingNewIntents;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004582 target.mPreserveWindow = preserveWindow;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004583 mRelaunchingActivities.add(target);
Andrii Kulianb372da62018-01-18 10:46:24 -08004584 scheduleRelaunch = true;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004585 }
Andrii Kulianb372da62018-01-18 10:46:24 -08004586 target.createdConfig = config.getGlobalConfiguration();
4587 target.overrideConfig = config.getOverrideConfiguration();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004588 target.pendingConfigChanges |= configChanges;
4589 }
Andrii Kulianb372da62018-01-18 10:46:24 -08004590
4591 return scheduleRelaunch ? target : null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004592 }
4593
Andrii Kulianb372da62018-01-18 10:46:24 -08004594 @Override
4595 public void handleRelaunchActivity(ActivityClientRecord tmp,
4596 PendingTransactionActions pendingActions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004597 // If we are getting ready to gc after going to the background, well
4598 // we are back active so skip it.
4599 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004600 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004601
4602 Configuration changedConfig = null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004603 int configChanges = 0;
Bob Leee5408332009-09-04 18:31:17 -07004604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004605 // First: make sure we have the most recent configuration and most
4606 // recent version of the activity, or skip it if some previous call
4607 // had taken a more recent version.
Craig Mautner88c05892013-06-28 09:47:45 -07004608 synchronized (mResourcesManager) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004609 int N = mRelaunchingActivities.size();
4610 IBinder token = tmp.token;
4611 tmp = null;
4612 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004613 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004614 if (r.token == token) {
4615 tmp = r;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004616 configChanges |= tmp.pendingConfigChanges;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004617 mRelaunchingActivities.remove(i);
4618 i--;
4619 N--;
4620 }
4621 }
Bob Leee5408332009-09-04 18:31:17 -07004622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004623 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004624 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004625 return;
4626 }
Bob Leee5408332009-09-04 18:31:17 -07004627
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004628 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
4629 + tmp.token + " with configChanges=0x"
4630 + Integer.toHexString(configChanges));
4631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004632 if (mPendingConfiguration != null) {
4633 changedConfig = mPendingConfiguration;
4634 mPendingConfiguration = null;
4635 }
4636 }
Bob Leee5408332009-09-04 18:31:17 -07004637
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08004638 if (tmp.createdConfig != null) {
4639 // If the activity manager is passing us its current config,
4640 // assume that is really what we want regardless of what we
4641 // may have pending.
4642 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004643 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
4644 && mConfiguration.diff(tmp.createdConfig) != 0)) {
4645 if (changedConfig == null
4646 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
4647 changedConfig = tmp.createdConfig;
4648 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08004649 }
4650 }
Tim Murraye1e6c662015-04-07 13:24:14 -07004651
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004652 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004653 + tmp.token + ": changedConfig=" + changedConfig);
Tim Murraye1e6c662015-04-07 13:24:14 -07004654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004655 // If there was a pending configuration change, execute it first.
4656 if (changedConfig != null) {
Dianne Hackborn908aecc2012-07-31 16:37:34 -07004657 mCurDefaultDisplayDpi = changedConfig.densityDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -07004658 updateDefaultDensity();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004659 handleConfigurationChanged(changedConfig, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004660 }
Bob Leee5408332009-09-04 18:31:17 -07004661
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004662 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004663 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004664 if (r == null) {
4665 return;
4666 }
Bob Leee5408332009-09-04 18:31:17 -07004667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004668 r.activity.mConfigChangeFlags |= configChanges;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004669 r.mPreserveWindow = tmp.mPreserveWindow;
Bob Leee5408332009-09-04 18:31:17 -07004670
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004671 r.activity.mChangingConfigurations = true;
4672
Robert Carr23fa16b2016-01-13 13:19:58 -08004673 // If we are preserving the main window across relaunches we would also like to preserve
4674 // the children. However the client side view system does not support preserving
4675 // the child views so we notify the window manager to expect these windows to
4676 // be replaced and defer requests to destroy or hide them. This way we can achieve
4677 // visual continuity. It's important that we do this here prior to pause and destroy
4678 // as that is when we may hide or remove the child views.
Robert Carr77bdfb52016-05-02 18:18:31 -07004679 //
4680 // There is another scenario, if we have decided locally to relaunch the app from a
4681 // call to recreate, then none of the windows will be prepared for replacement or
4682 // preserved by the server, so we want to notify it that we are preparing to replace
4683 // everything
Robert Carr23fa16b2016-01-13 13:19:58 -08004684 try {
Andrii Kulianb372da62018-01-18 10:46:24 -08004685 if (r.mPreserveWindow) {
Robert Carr77bdfb52016-05-02 18:18:31 -07004686 WindowManagerGlobal.getWindowSession().prepareToReplaceWindows(
Andrii Kulianb372da62018-01-18 10:46:24 -08004687 r.token, true /* childrenOnly */);
Robert Carr23fa16b2016-01-13 13:19:58 -08004688 }
4689 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004690 throw e.rethrowFromSystemServer();
Robert Carr23fa16b2016-01-13 13:19:58 -08004691 }
4692
Wale Ogunwale5527a502018-02-20 18:18:21 -08004693 handleRelaunchActivityInner(r, configChanges, tmp.pendingResults, tmp.pendingIntents,
4694 pendingActions, tmp.startsNotResumed, tmp.overrideConfig, "handleRelaunchActivity");
4695
4696 if (pendingActions != null) {
4697 // Only report a successful relaunch to WindowManager.
4698 pendingActions.setReportRelaunchToWindowManager(true);
Dianne Hackborne2b04802010-12-09 09:24:55 -08004699 }
Wale Ogunwale5527a502018-02-20 18:18:21 -08004700 }
4701
Andrii Kulian320e3b52018-05-03 16:26:25 -07004702 /**
4703 * Post a message to relaunch the activity. We do this instead of launching it immediately,
4704 * because this will destroy the activity from which it was called and interfere with the
4705 * lifecycle changes it was going through before. We need to make sure that we have finished
4706 * handling current transaction item before relaunching the activity.
4707 */
4708 void scheduleRelaunchActivity(IBinder token) {
4709 sendMessage(H.RELAUNCH_ACTIVITY, token);
4710 }
Bob Leee5408332009-09-04 18:31:17 -07004711
Andrii Kulian320e3b52018-05-03 16:26:25 -07004712 /** Performs the activity relaunch locally vs. requesting from system-server. */
4713 private void handleRelaunchActivityLocally(IBinder token) {
Wale Ogunwale5527a502018-02-20 18:18:21 -08004714 final ActivityClientRecord r = mActivities.get(token);
4715 if (r == null) {
Andrii Kulian320e3b52018-05-03 16:26:25 -07004716 Log.w(TAG, "Activity to relaunch no longer exists");
Wale Ogunwale5527a502018-02-20 18:18:21 -08004717 return;
4718 }
4719
4720 final int prevState = r.getLifecycleState();
4721
Andrii Kulian320e3b52018-05-03 16:26:25 -07004722 if (prevState < ON_RESUME || prevState > ON_STOP) {
4723 Log.w(TAG, "Activity state must be in [ON_RESUME..ON_STOP] in order to be relaunched,"
4724 + "current state is " + prevState);
Wale Ogunwale5527a502018-02-20 18:18:21 -08004725 return;
4726 }
4727
Wale Ogunwale5527a502018-02-20 18:18:21 -08004728
Andrii Kulian914aa7d2018-03-19 21:51:53 -07004729 // Initialize a relaunch request.
4730 final MergedConfiguration mergedConfiguration = new MergedConfiguration(
4731 r.createdConfig != null ? r.createdConfig : mConfiguration,
4732 r.overrideConfig);
4733 final ActivityRelaunchItem activityRelaunchItem = ActivityRelaunchItem.obtain(
4734 null /* pendingResults */, null /* pendingIntents */, 0 /* configChanges */,
4735 mergedConfiguration, r.mPreserveWindow);
4736 // Make sure to match the existing lifecycle state in the end of the transaction.
4737 final ActivityLifecycleItem lifecycleRequest =
4738 TransactionExecutorHelper.getLifecycleRequestForCurrentState(r);
4739 // Schedule the transaction.
4740 final ClientTransaction transaction = ClientTransaction.obtain(this.mAppThread, r.token);
4741 transaction.addCallback(activityRelaunchItem);
4742 transaction.setLifecycleStateRequest(lifecycleRequest);
4743 executeTransaction(transaction);
Wale Ogunwale5527a502018-02-20 18:18:21 -08004744 }
4745
4746 private void handleRelaunchActivityInner(ActivityClientRecord r, int configChanges,
4747 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingIntents,
4748 PendingTransactionActions pendingActions, boolean startsNotResumed,
4749 Configuration overrideConfig, String reason) {
Andrii Kulian770c4032018-05-02 18:40:59 -07004750 // Preserve last used intent, it may be set from Activity#setIntent().
4751 final Intent customIntent = r.activity.mIntent;
Wale Ogunwale5527a502018-02-20 18:18:21 -08004752 // Need to ensure state is saved.
4753 if (!r.paused) {
4754 performPauseActivity(r, false, reason, null /* pendingActions */);
4755 }
4756 if (!r.stopped) {
4757 callActivityOnStop(r, true /* saveState */, reason);
4758 }
4759
4760 handleDestroyActivity(r.token, false, configChanges, true, reason);
Bob Leee5408332009-09-04 18:31:17 -07004761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004762 r.activity = null;
4763 r.window = null;
4764 r.hideForNow = false;
4765 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07004766 // Merge any pending results and pending intents; don't just replace them
Wale Ogunwale5527a502018-02-20 18:18:21 -08004767 if (pendingResults != null) {
The Android Open Source Project10592532009-03-18 17:39:46 -07004768 if (r.pendingResults == null) {
Wale Ogunwale5527a502018-02-20 18:18:21 -08004769 r.pendingResults = pendingResults;
The Android Open Source Project10592532009-03-18 17:39:46 -07004770 } else {
Wale Ogunwale5527a502018-02-20 18:18:21 -08004771 r.pendingResults.addAll(pendingResults);
The Android Open Source Project10592532009-03-18 17:39:46 -07004772 }
4773 }
Wale Ogunwale5527a502018-02-20 18:18:21 -08004774 if (pendingIntents != null) {
The Android Open Source Project10592532009-03-18 17:39:46 -07004775 if (r.pendingIntents == null) {
Wale Ogunwale5527a502018-02-20 18:18:21 -08004776 r.pendingIntents = pendingIntents;
The Android Open Source Project10592532009-03-18 17:39:46 -07004777 } else {
Wale Ogunwale5527a502018-02-20 18:18:21 -08004778 r.pendingIntents.addAll(pendingIntents);
The Android Open Source Project10592532009-03-18 17:39:46 -07004779 }
4780 }
Wale Ogunwale5527a502018-02-20 18:18:21 -08004781 r.startsNotResumed = startsNotResumed;
4782 r.overrideConfig = overrideConfig;
Bob Leee5408332009-09-04 18:31:17 -07004783
Andrii Kulian770c4032018-05-02 18:40:59 -07004784 handleLaunchActivity(r, pendingActions, customIntent);
Andrii Kulianb372da62018-01-18 10:46:24 -08004785 }
Jorim Jaggife89d122015-12-22 16:28:44 +01004786
Andrii Kulianb372da62018-01-18 10:46:24 -08004787 @Override
4788 public void reportRelaunch(IBinder token, PendingTransactionActions pendingActions) {
4789 try {
4790 ActivityManager.getService().activityRelaunched(token);
4791 final ActivityClientRecord r = mActivities.get(token);
4792 if (pendingActions.shouldReportRelaunchToWindowManager() && r != null
4793 && r.window != null) {
4794 r.window.reportActivityRelaunched();
Jorim Jaggife89d122015-12-22 16:28:44 +01004795 }
Andrii Kulianb372da62018-01-18 10:46:24 -08004796 } catch (RemoteException e) {
4797 throw e.rethrowFromSystemServer();
Jorim Jaggife89d122015-12-22 16:28:44 +01004798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004799 }
4800
Andrii Kulian8ae79572018-01-26 15:36:06 -08004801 private void callActivityOnSaveInstanceState(ActivityClientRecord r) {
Craig Mautnera0026042014-04-23 11:45:37 -07004802 r.state = new Bundle();
4803 r.state.setAllowFds(false);
4804 if (r.isPersistable()) {
4805 r.persistentState = new PersistableBundle();
4806 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state,
4807 r.persistentState);
4808 } else {
4809 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
4810 }
4811 }
4812
Dianne Hackborn73c14162012-09-19 15:45:06 -07004813 ArrayList<ComponentCallbacks2> collectComponentCallbacks(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004814 boolean allActivities, Configuration newConfig) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07004815 ArrayList<ComponentCallbacks2> callbacks
4816 = new ArrayList<ComponentCallbacks2>();
Bob Leee5408332009-09-04 18:31:17 -07004817
Craig Mautner88c05892013-06-28 09:47:45 -07004818 synchronized (mResourcesManager) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004819 final int NAPP = mAllApplications.size();
4820 for (int i=0; i<NAPP; i++) {
Dianne Hackborn73c14162012-09-19 15:45:06 -07004821 callbacks.add(mAllApplications.get(i));
4822 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004823 final int NACT = mActivities.size();
4824 for (int i=0; i<NACT; i++) {
4825 ActivityClientRecord ar = mActivities.valueAt(i);
4826 Activity a = ar.activity;
4827 if (a != null) {
4828 Configuration thisConfig = applyConfigCompatMainThread(
4829 mCurDefaultDisplayDpi, newConfig,
Todd Kennedy233a0b12018-01-29 20:30:24 +00004830 ar.packageInfo.getCompatibilityInfo());
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004831 if (!ar.activity.mFinished && (allActivities || !ar.paused)) {
4832 // If the activity is currently resumed, its configuration
4833 // needs to change right now.
4834 callbacks.add(a);
4835 } else if (thisConfig != null) {
4836 // Otherwise, we will tell it about the change
4837 // the next time it is resumed or shown. Note that
4838 // the activity manager may, before then, decide the
4839 // activity needs to be destroyed to handle its new
4840 // configuration.
4841 if (DEBUG_CONFIGURATION) {
4842 Slog.v(TAG, "Setting activity "
4843 + ar.activityInfo.name + " newConfig=" + thisConfig);
Romain Guya998dff2012-03-23 18:58:36 -07004844 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004845 ar.newConfig = thisConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004846 }
4847 }
4848 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004849 final int NSVC = mServices.size();
4850 for (int i=0; i<NSVC; i++) {
4851 callbacks.add(mServices.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004852 }
4853 }
4854 synchronized (mProviderMap) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07004855 final int NPRV = mLocalProviders.size();
4856 for (int i=0; i<NPRV; i++) {
4857 callbacks.add(mLocalProviders.valueAt(i).mLocalProvider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004858 }
4859 }
Bob Leee5408332009-09-04 18:31:17 -07004860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004861 return callbacks;
4862 }
Bob Leee5408332009-09-04 18:31:17 -07004863
Adam Lesinski082614c2016-03-04 14:33:47 -08004864 /**
4865 * Updates the configuration for an Activity. The ActivityClientRecord's
4866 * {@link ActivityClientRecord#overrideConfig} is used to compute the final Configuration for
4867 * that Activity. {@link ActivityClientRecord#tmpConfig} is used as a temporary for delivering
4868 * the updated Configuration.
4869 * @param r ActivityClientRecord representing the Activity.
4870 * @param newBaseConfig The new configuration to use. This may be augmented with
4871 * {@link ActivityClientRecord#overrideConfig}.
Adam Lesinski082614c2016-03-04 14:33:47 -08004872 */
4873 private void performConfigurationChangedForActivity(ActivityClientRecord r,
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004874 Configuration newBaseConfig) {
4875 performConfigurationChangedForActivity(r, newBaseConfig,
4876 r.activity.getDisplay().getDisplayId(), false /* movedToDifferentDisplay */);
4877 }
4878
4879 /**
4880 * Updates the configuration for an Activity. The ActivityClientRecord's
4881 * {@link ActivityClientRecord#overrideConfig} is used to compute the final Configuration for
4882 * that Activity. {@link ActivityClientRecord#tmpConfig} is used as a temporary for delivering
4883 * the updated Configuration.
4884 * @param r ActivityClientRecord representing the Activity.
4885 * @param newBaseConfig The new configuration to use. This may be augmented with
4886 * {@link ActivityClientRecord#overrideConfig}.
4887 * @param displayId The id of the display where the Activity currently resides.
4888 * @param movedToDifferentDisplay Indicates if the activity was moved to different display.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004889 * @return {@link Configuration} instance sent to client, null if not sent.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004890 */
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004891 private Configuration performConfigurationChangedForActivity(ActivityClientRecord r,
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004892 Configuration newBaseConfig, int displayId, boolean movedToDifferentDisplay) {
Adam Lesinski082614c2016-03-04 14:33:47 -08004893 r.tmpConfig.setTo(newBaseConfig);
4894 if (r.overrideConfig != null) {
4895 r.tmpConfig.updateFrom(r.overrideConfig);
4896 }
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004897 final Configuration reportedConfig = performActivityConfigurationChanged(r.activity,
4898 r.tmpConfig, r.overrideConfig, displayId, movedToDifferentDisplay);
Adam Lesinski082614c2016-03-04 14:33:47 -08004899 freeTextLayoutCachesIfNeeded(r.activity.mCurrentConfig.diff(r.tmpConfig));
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004900 return reportedConfig;
Adam Lesinski082614c2016-03-04 14:33:47 -08004901 }
4902
4903 /**
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -07004904 * Creates a new Configuration only if override would modify base. Otherwise returns base.
4905 * @param base The base configuration.
4906 * @param override The update to apply to the base configuration. Can be null.
4907 * @return A Configuration representing base with override applied.
4908 */
4909 private static Configuration createNewConfigAndUpdateIfNotNull(@NonNull Configuration base,
4910 @Nullable Configuration override) {
4911 if (override == null) {
4912 return base;
4913 }
4914 Configuration newConfig = new Configuration(base);
4915 newConfig.updateFrom(override);
4916 return newConfig;
4917 }
4918
4919 /**
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004920 * Decides whether to update a component's configuration and whether to inform it.
Adam Lesinski082614c2016-03-04 14:33:47 -08004921 * @param cb The component callback to notify of configuration change.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004922 * @param newConfig The new configuration.
4923 */
4924 private void performConfigurationChanged(ComponentCallbacks2 cb, Configuration newConfig) {
4925 if (!REPORT_TO_ACTIVITY) {
4926 return;
4927 }
4928
4929 // ContextThemeWrappers may override the configuration for that context. We must check and
4930 // apply any overrides defined.
4931 Configuration contextThemeWrapperOverrideConfig = null;
4932 if (cb instanceof ContextThemeWrapper) {
4933 final ContextThemeWrapper contextThemeWrapper = (ContextThemeWrapper) cb;
4934 contextThemeWrapperOverrideConfig = contextThemeWrapper.getOverrideConfiguration();
4935 }
4936
4937 // Apply the ContextThemeWrapper override if necessary.
4938 // NOTE: Make sure the configurations are not modified, as they are treated as immutable
4939 // in many places.
4940 final Configuration configToReport = createNewConfigAndUpdateIfNotNull(
4941 newConfig, contextThemeWrapperOverrideConfig);
4942 cb.onConfigurationChanged(configToReport);
4943 }
4944
4945 /**
4946 * Decides whether to update an Activity's configuration and whether to inform it.
4947 * @param activity The activity to notify of configuration change.
Adam Lesinski082614c2016-03-04 14:33:47 -08004948 * @param newConfig The new configuration.
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -07004949 * @param amOverrideConfig The override config that differentiates the Activity's configuration
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004950 * from the base global configuration. This is supplied by
4951 * ActivityManager.
4952 * @param displayId Id of the display where activity currently resides.
4953 * @param movedToDifferentDisplay Indicates if the activity was moved to different display.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004954 * @return Configuration sent to client, null if no changes and not moved to different display.
Adam Lesinski082614c2016-03-04 14:33:47 -08004955 */
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004956 private Configuration performActivityConfigurationChanged(Activity activity,
4957 Configuration newConfig, Configuration amOverrideConfig, int displayId,
4958 boolean movedToDifferentDisplay) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004959 if (activity == null) {
4960 throw new IllegalArgumentException("No activity provided.");
4961 }
4962 final IBinder activityToken = activity.getActivityToken();
4963 if (activityToken == null) {
4964 throw new IllegalArgumentException("Activity token not set. Is the activity attached?");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004965 }
Bob Leee5408332009-09-04 18:31:17 -07004966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004967 boolean shouldChangeConfig = false;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004968 if (activity.mCurrentConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004969 shouldChangeConfig = true;
4970 } else {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004971 // If the new config is the same as the config this Activity is already running with and
4972 // the override config also didn't change, then don't bother calling
4973 // onConfigurationChanged.
Bryce Lee658d9842017-07-28 08:33:36 -07004974 final int diff = activity.mCurrentConfig.diffPublicOnly(newConfig);
4975
Andrii Kulian3b3c9142016-07-18 19:15:56 -07004976 if (diff != 0 || !mResourcesManager.isSameResourcesOverrideConfig(activityToken,
4977 amOverrideConfig)) {
Chong Zhang4951f9d2016-06-23 13:15:08 -07004978 // Always send the task-level config changes. For system-level configuration, if
4979 // this activity doesn't handle any of the config changes, then don't bother
4980 // calling onConfigurationChanged as we're going to destroy it.
4981 if (!mUpdatingSystemConfig
4982 || (~activity.mActivityInfo.getRealConfigChanged() & diff) == 0
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004983 || !REPORT_TO_ACTIVITY) {
Chong Zhang4951f9d2016-06-23 13:15:08 -07004984 shouldChangeConfig = true;
4985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004986 }
4987 }
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004988 if (!shouldChangeConfig && !movedToDifferentDisplay) {
4989 // Nothing significant, don't proceed with updating and reporting.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07004990 return null;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004991 }
4992
4993 // Propagate the configuration change to ResourcesManager and Activity.
4994
4995 // ContextThemeWrappers may override the configuration for that context. We must check and
4996 // apply any overrides defined.
4997 Configuration contextThemeWrapperOverrideConfig = activity.getOverrideConfiguration();
4998
4999 // We only update an Activity's configuration if this is not a global configuration change.
5000 // This must also be done before the callback, or else we violate the contract that the new
5001 // resources are available in ComponentCallbacks2#onConfigurationChanged(Configuration).
5002 // Also apply the ContextThemeWrapper override if necessary.
5003 // NOTE: Make sure the configurations are not modified, as they are treated as immutable in
5004 // many places.
5005 final Configuration finalOverrideConfig = createNewConfigAndUpdateIfNotNull(
5006 amOverrideConfig, contextThemeWrapperOverrideConfig);
5007 mResourcesManager.updateResourcesForActivity(activityToken, finalOverrideConfig,
5008 displayId, movedToDifferentDisplay);
5009
5010 activity.mConfigChangeFlags = 0;
5011 activity.mCurrentConfig = new Configuration(newConfig);
5012
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005013 // Apply the ContextThemeWrapper override if necessary.
5014 // NOTE: Make sure the configurations are not modified, as they are treated as immutable
5015 // in many places.
5016 final Configuration configToReport = createNewConfigAndUpdateIfNotNull(newConfig,
5017 contextThemeWrapperOverrideConfig);
5018
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005019 if (!REPORT_TO_ACTIVITY) {
5020 // Not configured to report to activity.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005021 return configToReport;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005022 }
5023
5024 if (movedToDifferentDisplay) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005025 activity.dispatchMovedToDisplay(displayId, configToReport);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005026 }
Bob Leee5408332009-09-04 18:31:17 -07005027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005028 if (shouldChangeConfig) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005029 activity.mCalled = false;
5030 activity.onConfigurationChanged(configToReport);
5031 if (!activity.mCalled) {
5032 throw new SuperNotCalledException("Activity " + activity.getLocalClassName() +
5033 " did not call through to super.onConfigurationChanged()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005034 }
5035 }
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005036
5037 return configToReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005038 }
5039
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07005040 public final void applyConfigurationToResources(Configuration config) {
Craig Mautner88c05892013-06-28 09:47:45 -07005041 synchronized (mResourcesManager) {
5042 mResourcesManager.applyConfigurationToResourcesLocked(config, null);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07005043 }
5044 }
5045
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005046 final Configuration applyCompatConfiguration(int displayDensity) {
Dianne Hackborn836e2622011-10-04 18:32:39 -07005047 Configuration config = mConfiguration;
5048 if (mCompatConfiguration == null) {
5049 mCompatConfiguration = new Configuration();
5050 }
5051 mCompatConfiguration.setTo(mConfiguration);
Adam Lesinski082614c2016-03-04 14:33:47 -08005052 if (mResourcesManager.applyCompatConfigurationLocked(displayDensity,
5053 mCompatConfiguration)) {
Dianne Hackborn836e2622011-10-04 18:32:39 -07005054 config = mCompatConfiguration;
5055 }
5056 return config;
5057 }
5058
Andrii Kulian446e8242017-10-26 15:17:29 -07005059 @Override
5060 public void handleConfigurationChanged(Configuration config) {
5061 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "configChanged");
5062 mCurDefaultDisplayDpi = config.densityDpi;
5063 mUpdatingSystemConfig = true;
5064 try {
5065 handleConfigurationChanged(config, null /* compat */);
5066 } finally {
5067 mUpdatingSystemConfig = false;
5068 }
5069 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
5070 }
5071
5072 private void handleConfigurationChanged(Configuration config, CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005073
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005074 int configDiff = 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005075
Bryce Lee658d9842017-07-28 08:33:36 -07005076 // This flag tracks whether the new configuration is fundamentally equivalent to the
5077 // existing configuration. This is necessary to determine whether non-activity
5078 // callbacks should receive notice when the only changes are related to non-public fields.
5079 // We do not gate calling {@link #performActivityConfigurationChanged} based on this flag
5080 // as that method uses the same check on the activity config override as well.
5081 final boolean equivalent = config != null && mConfiguration != null
5082 && (0 == mConfiguration.diffPublicOnly(config));
Todd Kennedy35a9a382018-01-25 13:25:37 -08005083 final Theme systemTheme = getSystemContext().getTheme();
5084 final Theme systemUiTheme = getSystemUiContext().getTheme();
Bryce Lee658d9842017-07-28 08:33:36 -07005085
Craig Mautner88c05892013-06-28 09:47:45 -07005086 synchronized (mResourcesManager) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005087 if (mPendingConfiguration != null) {
5088 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
5089 config = mPendingConfiguration;
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005090 mCurDefaultDisplayDpi = config.densityDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -07005091 updateDefaultDensity();
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005092 }
5093 mPendingConfiguration = null;
5094 }
5095
5096 if (config == null) {
5097 return;
5098 }
Tim Murraye1e6c662015-04-07 13:24:14 -07005099
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005100 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005101 + config);
Craig Mautner88c05892013-06-28 09:47:45 -07005102
5103 mResourcesManager.applyConfigurationToResourcesLocked(config, compat);
Adam Lesinskib61e4052016-05-19 18:23:05 -07005104 updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
5105 mResourcesManager.getConfiguration().getLocales());
Craig Mautner88c05892013-06-28 09:47:45 -07005106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005107 if (mConfiguration == null) {
5108 mConfiguration = new Configuration();
5109 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04005110 if (!mConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005111 return;
5112 }
Alan Viverettee54d2452015-05-06 10:41:43 -07005113
5114 configDiff = mConfiguration.updateFrom(config);
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005115 config = applyCompatConfiguration(mCurDefaultDisplayDpi);
Alan Viverette395cd012015-08-11 17:27:04 -04005116
Alan Viverette395cd012015-08-11 17:27:04 -04005117 if ((systemTheme.getChangingConfigurations() & configDiff) != 0) {
5118 systemTheme.rebase();
5119 }
Adam Lesinskia82b6262017-03-21 16:56:17 -07005120
Adam Lesinskia82b6262017-03-21 16:56:17 -07005121 if ((systemUiTheme.getChangingConfigurations() & configDiff) != 0) {
5122 systemUiTheme.rebase();
5123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005124 }
Dianne Hackborn73c14162012-09-19 15:45:06 -07005125
5126 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(false, config);
5127
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005128 freeTextLayoutCachesIfNeeded(configDiff);
5129
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005130 if (callbacks != null) {
5131 final int N = callbacks.size();
5132 for (int i=0; i<N; i++) {
Andrii Kulian701214b2016-04-07 09:36:33 -07005133 ComponentCallbacks2 cb = callbacks.get(i);
5134 if (cb instanceof Activity) {
5135 // If callback is an Activity - call corresponding method to consider override
5136 // config and avoid onConfigurationChanged if it hasn't changed.
5137 Activity a = (Activity) cb;
5138 performConfigurationChangedForActivity(mActivities.get(a.getActivityToken()),
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005139 config);
Bryce Lee658d9842017-07-28 08:33:36 -07005140 } else if (!equivalent) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005141 performConfigurationChanged(cb, config);
Andrii Kulian701214b2016-04-07 09:36:33 -07005142 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005144 }
5145 }
5146
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005147 void handleApplicationInfoChanged(@NonNull final ApplicationInfo ai) {
Adam Lesinskid33ef562017-01-19 14:49:59 -08005148 // Updates triggered by package installation go through a package update
5149 // receiver. Here we try to capture ApplicationInfo changes that are
5150 // caused by other sources, such as overlays. That means we want to be as conservative
5151 // about code changes as possible. Take the diff of the old ApplicationInfo and the new
5152 // to see if anything needs to change.
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005153 LoadedApk apk;
5154 LoadedApk resApk;
5155 // Update all affected loaded packages with new package information
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005156 synchronized (mResourcesManager) {
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005157 WeakReference<LoadedApk> ref = mPackages.get(ai.packageName);
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005158 apk = ref != null ? ref.get() : null;
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005159 ref = mResourcePackages.get(ai.packageName);
5160 resApk = ref != null ? ref.get() : null;
5161 }
5162 if (apk != null) {
5163 final ArrayList<String> oldPaths = new ArrayList<>();
5164 LoadedApk.makePaths(this, apk.getApplicationInfo(), oldPaths);
5165 apk.updateApplicationInfo(ai, oldPaths);
5166 }
5167 if (resApk != null) {
5168 final ArrayList<String> oldPaths = new ArrayList<>();
5169 LoadedApk.makePaths(this, resApk.getApplicationInfo(), oldPaths);
5170 resApk.updateApplicationInfo(ai, oldPaths);
5171 }
5172 synchronized (mResourcesManager) {
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005173 // Update all affected Resources objects to use new ResourcesImpl
5174 mResourcesManager.applyNewResourceDirsLocked(ai.sourceDir, ai.resourceDirs);
5175 }
5176
5177 ApplicationPackageManager.configurationChanged();
5178
5179 // Trigger a regular Configuration change event, only with a different assetsSeq number
5180 // so that we actually call through to all components.
Adam Lesinskia82b6262017-03-21 16:56:17 -07005181 // TODO(adamlesinski): Change this to make use of ActivityManager's upcoming ability to
5182 // store configurations per-process.
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005183 Configuration newConfig = new Configuration();
Adam Lesinskia82b6262017-03-21 16:56:17 -07005184 newConfig.assetsSeq = (mConfiguration != null ? mConfiguration.assetsSeq : 0) + 1;
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005185 handleConfigurationChanged(newConfig, null);
5186
Wale Ogunwale5527a502018-02-20 18:18:21 -08005187 relaunchAllActivities();
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005188 }
5189
Romain Guy46bfc482013-08-16 18:38:29 -07005190 static void freeTextLayoutCachesIfNeeded(int configDiff) {
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005191 if (configDiff != 0) {
5192 // Ask text layout engine to free its caches if there is a locale change
5193 boolean hasLocaleConfigChange = ((configDiff & ActivityInfo.CONFIG_LOCALE) != 0);
5194 if (hasLocaleConfigChange) {
5195 Canvas.freeTextLayoutCaches();
5196 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Cleared TextLayout Caches");
5197 }
5198 }
5199 }
5200
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005201 /**
5202 * Handle new activity configuration and/or move to a different display.
Andrii Kulian446e8242017-10-26 15:17:29 -07005203 * @param activityToken Target activity token.
5204 * @param overrideConfig Activity override config.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005205 * @param displayId Id of the display where activity was moved to, -1 if there was no move and
5206 * value didn't change.
5207 */
Andrii Kulian446e8242017-10-26 15:17:29 -07005208 @Override
5209 public void handleActivityConfigurationChanged(IBinder activityToken,
5210 Configuration overrideConfig, int displayId) {
5211 ActivityClientRecord r = mActivities.get(activityToken);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005212 // Check input params.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005213 if (r == null || r.activity == null) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005214 if (DEBUG_CONFIGURATION) Slog.w(TAG, "Not found target activity to report to: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005215 return;
5216 }
Andrii Kulian51c1b672017-04-07 18:39:32 -07005217 final boolean movedToDifferentDisplay = displayId != INVALID_DISPLAY
5218 && displayId != r.activity.getDisplay().getDisplayId();
Bob Leee5408332009-09-04 18:31:17 -07005219
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005220 // Perform updates.
Andrii Kulian446e8242017-10-26 15:17:29 -07005221 r.overrideConfig = overrideConfig;
Stephen Kiazykf903b732017-03-20 16:23:45 -07005222 final ViewRootImpl viewRoot = r.activity.mDecor != null
5223 ? r.activity.mDecor.getViewRootImpl() : null;
5224
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005225 if (movedToDifferentDisplay) {
5226 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity moved to display, activity:"
5227 + r.activityInfo.name + ", displayId=" + displayId
Andrii Kulian446e8242017-10-26 15:17:29 -07005228 + ", config=" + overrideConfig);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005229
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005230 final Configuration reportedConfig = performConfigurationChangedForActivity(r,
5231 mCompatConfiguration, displayId, true /* movedToDifferentDisplay */);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005232 if (viewRoot != null) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005233 viewRoot.onMovedToDisplay(displayId, reportedConfig);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005234 }
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005235 } else {
5236 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Andrii Kulian446e8242017-10-26 15:17:29 -07005237 + r.activityInfo.name + ", config=" + overrideConfig);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005238 performConfigurationChangedForActivity(r, mCompatConfiguration);
5239 }
Andrii Kulian44607962017-03-16 11:06:24 -07005240 // Notify the ViewRootImpl instance about configuration changes. It may have initiated this
5241 // update to make sure that resources are updated before updating itself.
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005242 if (viewRoot != null) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005243 viewRoot.updateConfiguration(displayId);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005244 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07005245 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005246 }
5247
Jeff Hao1b012d32014-08-20 10:35:34 -07005248 final void handleProfilerControl(boolean start, ProfilerInfo profilerInfo, int profileType) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005249 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005250 try {
Romain Guy7eabe552011-07-21 14:56:34 -07005251 switch (profileType) {
Jeff Hao1b012d32014-08-20 10:35:34 -07005252 default:
5253 mProfiler.setProfiler(profilerInfo);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005254 mProfiler.startProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07005255 break;
5256 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005257 } catch (RuntimeException e) {
Jeff Hao1b012d32014-08-20 10:35:34 -07005258 Slog.w(TAG, "Profiling failed on path " + profilerInfo.profileFile
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005259 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07005260 } finally {
Andreas Gampe2b073a02017-06-22 17:28:57 -07005261 profilerInfo.closeFd();
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005262 }
5263 } else {
Romain Guy7eabe552011-07-21 14:56:34 -07005264 switch (profileType) {
Romain Guy7eabe552011-07-21 14:56:34 -07005265 default:
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005266 mProfiler.stopProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07005267 break;
Romain Guy7eabe552011-07-21 14:56:34 -07005268 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005269 }
5270 }
Bob Leee5408332009-09-04 18:31:17 -07005271
Andreas Gampe4c79fea2016-01-28 20:11:41 -08005272 /**
5273 * Public entrypoint to stop profiling. This is required to end profiling when the app crashes,
5274 * so that profiler data won't be lost.
5275 *
5276 * @hide
5277 */
5278 public void stopProfiling() {
Amith Yamasanib1684432017-01-26 14:57:20 -08005279 if (mProfiler != null) {
5280 mProfiler.stopProfiling();
5281 }
Andreas Gampe4c79fea2016-01-28 20:11:41 -08005282 }
5283
Christopher Ferris8d652f82017-04-11 16:29:18 -07005284 static void handleDumpHeap(DumpHeapData dhd) {
Makoto Onuki4556b7b2017-07-07 14:58:58 -07005285 if (dhd.runGc) {
5286 System.gc();
5287 System.runFinalization();
5288 System.gc();
5289 }
Christopher Ferris8d652f82017-04-11 16:29:18 -07005290 if (dhd.managed) {
Andy McFadden824c5102010-07-09 16:26:57 -07005291 try {
5292 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
5293 } catch (IOException e) {
5294 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
5295 + " -- can the process access this path?");
5296 } finally {
5297 try {
5298 dhd.fd.close();
5299 } catch (IOException e) {
5300 Slog.w(TAG, "Failure closing profile fd", e);
5301 }
5302 }
Christopher Ferris8d652f82017-04-11 16:29:18 -07005303 } else if (dhd.mallocInfo) {
5304 Debug.dumpNativeMallocInfo(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07005305 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07005306 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07005307 }
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005308 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005309 ActivityManager.getService().dumpHeapFinished(dhd.path);
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005310 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005311 throw e.rethrowFromSystemServer();
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005312 }
Andy McFadden824c5102010-07-09 16:26:57 -07005313 }
5314
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005315 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005316 boolean hasPkgInfo = false;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005317 switch (cmd) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005318 case ApplicationThreadConstants.PACKAGE_REMOVED:
5319 case ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL:
Todd Kennedy39bfee52016-02-24 10:28:21 -08005320 {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005321 final boolean killApp = cmd == ApplicationThreadConstants.PACKAGE_REMOVED;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005322 if (packages == null) {
5323 break;
5324 }
5325 synchronized (mResourcesManager) {
5326 for (int i = packages.length - 1; i >= 0; i--) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005327 if (!hasPkgInfo) {
Todd Kennedy39bfee52016-02-24 10:28:21 -08005328 WeakReference<LoadedApk> ref = mPackages.get(packages[i]);
5329 if (ref != null && ref.get() != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005330 hasPkgInfo = true;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005331 } else {
5332 ref = mResourcePackages.get(packages[i]);
5333 if (ref != null && ref.get() != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005334 hasPkgInfo = true;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005335 }
5336 }
5337 }
5338 if (killApp) {
5339 mPackages.remove(packages[i]);
5340 mResourcePackages.remove(packages[i]);
5341 }
5342 }
5343 }
5344 break;
5345 }
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005346 case ApplicationThreadConstants.PACKAGE_REPLACED:
Todd Kennedy39bfee52016-02-24 10:28:21 -08005347 {
5348 if (packages == null) {
5349 break;
5350 }
5351 synchronized (mResourcesManager) {
5352 for (int i = packages.length - 1; i >= 0; i--) {
5353 WeakReference<LoadedApk> ref = mPackages.get(packages[i]);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005354 LoadedApk pkgInfo = ref != null ? ref.get() : null;
5355 if (pkgInfo != null) {
5356 hasPkgInfo = true;
mark_chen89764e32014-12-12 15:38:48 +08005357 } else {
5358 ref = mResourcePackages.get(packages[i]);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005359 pkgInfo = ref != null ? ref.get() : null;
5360 if (pkgInfo != null) {
5361 hasPkgInfo = true;
mark_chen89764e32014-12-12 15:38:48 +08005362 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005363 }
Todd Kennedy39bfee52016-02-24 10:28:21 -08005364 // If the package is being replaced, yet it still has a valid
5365 // LoadedApk object, the package was updated with _DONT_KILL.
5366 // Adjust it's internal references to the application info and
5367 // resources.
Todd Kennedy233a0b12018-01-29 20:30:24 +00005368 if (pkgInfo != null) {
Todd Kennedy39bfee52016-02-24 10:28:21 -08005369 try {
5370 final String packageName = packages[i];
5371 final ApplicationInfo aInfo =
5372 sPackageManager.getApplicationInfo(
5373 packageName,
Svet Ganov6ce92392017-09-27 16:04:10 -07005374 PackageManager.GET_SHARED_LIBRARY_FILES,
Todd Kennedy39bfee52016-02-24 10:28:21 -08005375 UserHandle.myUserId());
5376
5377 if (mActivities.size() > 0) {
5378 for (ActivityClientRecord ar : mActivities.values()) {
5379 if (ar.activityInfo.applicationInfo.packageName
5380 .equals(packageName)) {
5381 ar.activityInfo.applicationInfo = aInfo;
Todd Kennedy233a0b12018-01-29 20:30:24 +00005382 ar.packageInfo = pkgInfo;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005383 }
5384 }
5385 }
Todd Kennedyb9656a92018-05-02 10:59:45 +01005386 final ArrayList<String> oldPaths = new ArrayList<>();
5387 LoadedApk.makePaths(this, pkgInfo.getApplicationInfo(), oldPaths);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005388 pkgInfo.updateApplicationInfo(aInfo, oldPaths);
Todd Kennedy39bfee52016-02-24 10:28:21 -08005389 } catch (RemoteException e) {
5390 }
5391 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005392 }
5393 }
Todd Kennedy39bfee52016-02-24 10:28:21 -08005394 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005395 }
5396 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00005397 ApplicationPackageManager.handlePackageBroadcast(cmd, packages, hasPkgInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005398 }
Tim Murraye1e6c662015-04-07 13:24:14 -07005399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005400 final void handleLowMemory() {
Dianne Hackborn73c14162012-09-19 15:45:06 -07005401 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(true, null);
Bob Leee5408332009-09-04 18:31:17 -07005402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005403 final int N = callbacks.size();
5404 for (int i=0; i<N; i++) {
5405 callbacks.get(i).onLowMemory();
5406 }
5407
Chris Tatece229052009-03-25 16:44:52 -07005408 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
5409 if (Process.myUid() != Process.SYSTEM_UID) {
5410 int sqliteReleased = SQLiteDatabase.releaseMemory();
5411 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
5412 }
Bob Leee5408332009-09-04 18:31:17 -07005413
Mike Reedcaf0df12009-04-27 14:32:05 -04005414 // Ask graphics to free up as much as possible (font/image caches)
5415 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005416
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005417 // Ask text layout engine to free also as much as possible
5418 Canvas.freeTextLayoutCaches();
5419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005420 BinderInternal.forceGc("mem");
5421 }
5422
Jorim Jaggib29e3182018-04-30 18:51:56 +02005423 private void handleTrimMemory(int level) {
5424 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "trimMemory");
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07005425 if (DEBUG_MEMORY_TRIM) Slog.v(TAG, "Trimming memory to level: " + level);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005426
Dianne Hackborn73c14162012-09-19 15:45:06 -07005427 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(true, null);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005428
5429 final int N = callbacks.size();
Romain Guya998dff2012-03-23 18:58:36 -07005430 for (int i = 0; i < N; i++) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005431 callbacks.get(i).onTrimMemory(level);
5432 }
Romain Guy19f86e82012-04-23 15:19:07 -07005433
John Reckf47a5942014-06-30 16:20:04 -07005434 WindowManagerGlobal.getInstance().trimMemory(level);
Jorim Jaggib29e3182018-04-30 18:51:56 +02005435 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005436 }
5437
Jesse Hall317fa5a2017-05-23 15:46:55 -07005438 private void setupGraphicsSupport(Context context) {
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005439 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setupGraphicsSupport");
Romain Guya9582652011-11-10 14:20:10 -08005440
Jesse Hall317fa5a2017-05-23 15:46:55 -07005441 // The system package doesn't have real data directories, so don't set up cache paths.
5442 if (!"android".equals(context.getPackageName())) {
5443 // This cache location probably points at credential-encrypted
5444 // storage which may not be accessible yet; assign it anyway instead
5445 // of pointing at device-encrypted storage.
5446 final File cacheDir = context.getCacheDir();
5447 if (cacheDir != null) {
5448 // Provide a usable directory for temporary files
5449 System.setProperty("java.io.tmpdir", cacheDir.getAbsolutePath());
5450 } else {
5451 Log.v(TAG, "Unable to initialize \"java.io.tmpdir\" property "
5452 + "due to missing cache directory");
Romain Guya9582652011-11-10 14:20:10 -08005453 }
Jesse Hall317fa5a2017-05-23 15:46:55 -07005454
5455 // Setup a location to store generated/compiled graphics code.
5456 final Context deviceContext = context.createDeviceProtectedStorageContext();
5457 final File codeCacheDir = deviceContext.getCodeCacheDir();
5458 if (codeCacheDir != null) {
5459 try {
5460 int uid = Process.myUid();
5461 String[] packages = getPackageManager().getPackagesForUid(uid);
5462 if (packages != null) {
Romain Guycecbe072017-07-18 15:42:06 -07005463 ThreadedRenderer.setupDiskCache(codeCacheDir);
5464 RenderScriptCacheDir.setupDiskCache(codeCacheDir);
Jesse Hall317fa5a2017-05-23 15:46:55 -07005465 }
5466 } catch (RemoteException e) {
5467 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
5468 throw e.rethrowFromSystemServer();
5469 }
5470 } else {
5471 Log.w(TAG, "Unable to use shader/script cache: missing code-cache directory");
5472 }
Romain Guya9582652011-11-10 14:20:10 -08005473 }
Jesse Hall317fa5a2017-05-23 15:46:55 -07005474
Cody Northrop86cedcb2017-10-20 09:03:13 -06005475 GraphicsEnvironment.getInstance().setup(context);
Jesse Hall317fa5a2017-05-23 15:46:55 -07005476 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborndde331c2012-08-03 14:01:57 -07005477 }
5478
5479 private void updateDefaultDensity() {
Alan Viverette2ac46f12016-02-04 16:58:14 -05005480 final int densityDpi = mCurDefaultDisplayDpi;
5481 if (!mDensityCompatMode
5482 && densityDpi != Configuration.DENSITY_DPI_UNDEFINED
5483 && densityDpi != DisplayMetrics.DENSITY_DEVICE) {
5484 DisplayMetrics.DENSITY_DEVICE = densityDpi;
5485 Bitmap.setDefaultDensity(densityDpi);
Dianne Hackborndde331c2012-08-03 14:01:57 -07005486 }
5487 }
5488
Todd Kennedye713efc2016-05-10 13:45:40 -07005489 /**
5490 * Returns the correct library directory for the current ABI.
5491 * <p>
5492 * If we're dealing with a multi-arch application that has both 32 and 64 bit shared
5493 * libraries, we might need to choose the secondary depending on what the current
5494 * runtime's instruction set is.
5495 */
5496 private String getInstrumentationLibrary(ApplicationInfo appInfo, InstrumentationInfo insInfo) {
Patrick Baumanneb595802018-04-17 09:49:55 -07005497 if (appInfo.primaryCpuAbi != null && appInfo.secondaryCpuAbi != null
5498 && appInfo.secondaryCpuAbi.equals(insInfo.secondaryCpuAbi)) {
Todd Kennedye713efc2016-05-10 13:45:40 -07005499 // Get the instruction set supported by the secondary ABI. In the presence
5500 // of a native bridge this might be different than the one secondary ABI used.
5501 String secondaryIsa =
5502 VMRuntime.getInstructionSet(appInfo.secondaryCpuAbi);
5503 final String secondaryDexCodeIsa =
5504 SystemProperties.get("ro.dalvik.vm.isa." + secondaryIsa);
5505 secondaryIsa = secondaryDexCodeIsa.isEmpty() ? secondaryIsa : secondaryDexCodeIsa;
5506
5507 final String runtimeIsa = VMRuntime.getRuntime().vmInstructionSet();
5508 if (runtimeIsa.equals(secondaryIsa)) {
5509 return insInfo.secondaryNativeLibraryDir;
5510 }
5511 }
5512 return insInfo.nativeLibraryDir;
5513 }
5514
Adam Lesinskib61e4052016-05-19 18:23:05 -07005515 /**
5516 * The LocaleList set for the app's resources may have been shuffled so that the preferred
5517 * Locale is at position 0. We must find the index of this preferred Locale in the
5518 * original LocaleList.
5519 */
5520 private void updateLocaleListFromAppContext(Context context, LocaleList newLocaleList) {
5521 final Locale bestLocale = context.getResources().getConfiguration().getLocales().get(0);
5522 final int newLocaleListSize = newLocaleList.size();
5523 for (int i = 0; i < newLocaleListSize; i++) {
5524 if (bestLocale.equals(newLocaleList.get(i))) {
5525 LocaleList.setDefault(newLocaleList, i);
5526 return;
5527 }
5528 }
Adam Lesinski27d30162016-05-25 16:45:14 -07005529
5530 // The app may have overridden the LocaleList with its own Locale
5531 // (not present in the available list). Push the chosen Locale
5532 // to the front of the list.
5533 LocaleList.setDefault(new LocaleList(bestLocale, newLocaleList));
Adam Lesinskib61e4052016-05-19 18:23:05 -07005534 }
5535
Romain Guy65b345f2011-07-27 18:51:50 -07005536 private void handleBindApplication(AppBindData data) {
Calin Juravle8f5770d2016-04-12 14:12:04 +01005537 // Register the UI Thread as a sensitive thread to the runtime.
5538 VMRuntime.registerSensitiveThread();
Man Caocfa78b22015-06-11 20:14:34 -07005539 if (data.trackAllocation) {
5540 DdmVmInternal.enableRecentAllocations(true);
5541 }
5542
Dianne Hackbornd98885c2016-03-01 17:13:03 -08005543 // Note when this process has started.
5544 Process.setStartTimes(SystemClock.elapsedRealtime(), SystemClock.uptimeMillis());
5545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005546 mBoundApplication = data;
5547 mConfiguration = new Configuration(data.config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07005548 mCompatConfiguration = new Configuration(data.config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005549
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005550 mProfiler = new Profiler();
Andreas Gampeab8a63b2018-01-05 13:55:15 -08005551 String agent = null;
Jeff Hao1b012d32014-08-20 10:35:34 -07005552 if (data.initProfilerInfo != null) {
5553 mProfiler.profileFile = data.initProfilerInfo.profileFile;
5554 mProfiler.profileFd = data.initProfilerInfo.profileFd;
5555 mProfiler.samplingInterval = data.initProfilerInfo.samplingInterval;
5556 mProfiler.autoStopProfiler = data.initProfilerInfo.autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -08005557 mProfiler.streamingOutput = data.initProfilerInfo.streamingOutput;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08005558 if (data.initProfilerInfo.attachAgentDuringBind) {
5559 agent = data.initProfilerInfo.agent;
5560 }
Jeff Hao1b012d32014-08-20 10:35:34 -07005561 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005563 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08005564 Process.setArgV0(data.processName);
Siva Velusamyd693dfa2012-09-10 14:36:58 -07005565 android.ddm.DdmHandleAppName.setAppName(data.processName,
5566 UserHandle.myUserId());
Mathew Inwood37b6ca82018-05-02 10:42:23 +01005567 VMRuntime.setProcessPackageName(data.appInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005568
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005569 if (mProfiler.profileFd != null) {
5570 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07005571 }
5572
Joe Onoratod630f102011-03-17 18:42:26 -07005573 // If the app is Honeycomb MR1 or earlier, switch its AsyncTask
5574 // implementation to use the pool executor. Normally, we use the
5575 // serialized executor as the default. This has to happen in the
5576 // main thread so the main looper is set right.
Dianne Hackborn81e92762011-10-09 16:00:21 -07005577 if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
Joe Onoratod630f102011-03-17 18:42:26 -07005578 AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
5579 }
5580
Dianne Hackborn7895bc22014-09-05 15:09:03 -07005581 Message.updateCheckRecycle(data.appInfo.targetSdkVersion);
5582
Leon Scroggins III8290eab2018-03-19 10:51:44 -04005583 // Prior to P, internal calls to decode Bitmaps used BitmapFactory,
5584 // which may scale up to account for density. In P, we switched to
5585 // ImageDecoder, which skips the upscale to save memory. ImageDecoder
5586 // needs to still scale up in older apps, in case they rely on the
5587 // size of the Bitmap without considering its density.
5588 ImageDecoder.sApiLevel = data.appInfo.targetSdkVersion;
5589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005590 /*
5591 * Before spawning a new process, reset the time zone to be the system time zone.
5592 * This needs to be done because the system time zone could have changed after the
5593 * the spawning of this process. Without doing this this process would have the incorrect
5594 * system time zone.
5595 */
5596 TimeZone.setDefault(null);
5597
Adam Lesinskib61e4052016-05-19 18:23:05 -07005598 /*
5599 * Set the LocaleList. This may change once we create the App Context.
5600 */
5601 LocaleList.setDefault(data.config.getLocales());
5602
5603 synchronized (mResourcesManager) {
5604 /*
5605 * Update the system configuration since its preloaded and might not
5606 * reflect configuration changes. The configuration object passed
5607 * in AppBindData can be safely assumed to be up to date
5608 */
5609 mResourcesManager.applyConfigurationToResourcesLocked(data.config, data.compatInfo);
5610 mCurDefaultDisplayDpi = data.config.densityDpi;
5611
5612 // This calls mResourcesManager so keep it within the synchronized block.
5613 applyCompatConfiguration(mCurDefaultDisplayDpi);
5614 }
5615
Todd Kennedy233a0b12018-01-29 20:30:24 +00005616 data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005617
Andreas Gampeab8a63b2018-01-05 13:55:15 -08005618 if (agent != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005619 handleAttachAgent(agent, data.info);
Andreas Gampeab8a63b2018-01-05 13:55:15 -08005620 }
5621
Dianne Hackborndde331c2012-08-03 14:01:57 -07005622 /**
5623 * Switch this process to density compatibility mode if needed.
5624 */
5625 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
5626 == 0) {
5627 mDensityCompatMode = true;
5628 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
5629 }
5630 updateDefaultDensity();
5631
Neil Fullerc66ec402016-11-14 16:06:42 +00005632 final String use24HourSetting = mCoreSettings.getString(Settings.System.TIME_12_24);
5633 Boolean is24Hr = null;
5634 if (use24HourSetting != null) {
5635 is24Hr = "24".equals(use24HourSetting) ? Boolean.TRUE : Boolean.FALSE;
5636 }
5637 // null : use locale default for 12/24 hour formatting,
5638 // false : use 12 hour format,
5639 // true : use 24 hour format.
Narayan Kamathccb2a0862013-12-19 14:49:36 +00005640 DateFormat.set24HourTimePref(is24Hr);
5641
Jon Miranda836c0a82014-08-11 12:32:26 -07005642 View.mDebugViewAttributes =
5643 mCoreSettings.getInt(Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0;
5644
Jeff Sharkey89182982017-11-01 19:02:56 -06005645 StrictMode.initThreadDefaults(data.appInfo);
5646 StrictMode.initVmDefaults(data.appInfo);
Jeff Sharkey344744b2016-01-28 19:03:30 -07005647
Svet Ganov37e43272016-09-09 16:01:32 -07005648 // We deprecated Build.SERIAL and only apps that target pre NMR1
5649 // SDK can see it. Since access to the serial is now behind a
5650 // permission we push down the value and here we fix it up
5651 // before any app code has been loaded.
5652 try {
5653 Field field = Build.class.getDeclaredField("SERIAL");
5654 field.setAccessible(true);
5655 field.set(Build.class, data.buildSerial);
5656 } catch (NoSuchFieldException | IllegalAccessException e) {
5657 /* ignore */
5658 }
5659
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005660 if (data.debugMode != ApplicationThreadConstants.DEBUG_OFF) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005661 // XXX should have option to change the port.
5662 Debug.changeDebugPort(8100);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005663 if (data.debugMode == ApplicationThreadConstants.DEBUG_WAIT) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005664 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005665 + " is waiting for the debugger on port 8100...");
5666
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005667 IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005668 try {
5669 mgr.showWaitingForDebugger(mAppThread, true);
5670 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005671 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005672 }
5673
5674 Debug.waitForDebugger();
5675
5676 try {
5677 mgr.showWaitingForDebugger(mAppThread, false);
5678 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005679 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005680 }
5681
5682 } else {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005683 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005684 + " can be debugged on port 8100...");
5685 }
5686 }
5687
Jamie Gennisf9c7d6b2013-03-25 14:18:25 -07005688 // Allow application-generated systrace messages if we're debuggable.
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04005689 boolean isAppDebuggable = (data.appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
5690 Trace.setAppTracingAllowed(isAppDebuggable);
John Reck56428472018-03-16 17:27:17 -07005691 ThreadedRenderer.setDebuggingEnabled(isAppDebuggable || Build.IS_DEBUGGABLE);
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04005692 if (isAppDebuggable && data.enableBinderTracking) {
5693 Binder.enableTracing();
5694 }
Jamie Gennisf9c7d6b2013-03-25 14:18:25 -07005695
Robert Greenwalt434203a2010-10-11 16:00:27 -07005696 /**
5697 * Initialize the default http proxy in this process for the reasons we set the time zone.
5698 */
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005699 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Setup proxies");
Alan Viverettebe64eae2015-09-03 14:56:04 -04005700 final IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08005701 if (b != null) {
5702 // In pre-boot mode (doing initial launch to collect password), not
5703 // all system is up. This includes the connectivity service, so don't
5704 // crash if we can't get it.
Alan Viverettebe64eae2015-09-03 14:56:04 -04005705 final IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08005706 try {
Paul Jensencee9b512015-05-06 07:32:40 -04005707 final ProxyInfo proxyInfo = service.getProxyForNetwork(null);
Jason Monk207900c2014-04-25 15:00:09 -04005708 Proxy.setHttpProxySystemProperty(proxyInfo);
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005709 } catch (RemoteException e) {
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005710 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005711 throw e.rethrowFromSystemServer();
5712 }
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08005713 }
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005714 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Robert Greenwalt434203a2010-10-11 16:00:27 -07005715
Alan Viverette2107d692015-09-03 14:55:27 -04005716 // Instrumentation info affects the class loader, so load it before
5717 // setting up the app context.
5718 final InstrumentationInfo ii;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005719 if (data.instrumentationName != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 try {
Alan Viverette2107d692015-09-03 14:55:27 -04005721 ii = new ApplicationPackageManager(null, getPackageManager())
5722 .getInstrumentationInfo(data.instrumentationName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005723 } catch (PackageManager.NameNotFoundException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 throw new RuntimeException(
Alan Viverette2107d692015-09-03 14:55:27 -04005725 "Unable to find instrumentation info for: " + data.instrumentationName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 }
5727
Patrick Baumanneb595802018-04-17 09:49:55 -07005728 // Warn of potential ABI mismatches.
5729 if (!Objects.equals(data.appInfo.primaryCpuAbi, ii.primaryCpuAbi)
5730 || !Objects.equals(data.appInfo.secondaryCpuAbi, ii.secondaryCpuAbi)) {
5731 Slog.w(TAG, "Package uses different ABI(s) than its instrumentation: "
5732 + "package[" + data.appInfo.packageName + "]: "
5733 + data.appInfo.primaryCpuAbi + ", " + data.appInfo.secondaryCpuAbi
5734 + " instrumentation[" + ii.packageName + "]: "
5735 + ii.primaryCpuAbi + ", " + ii.secondaryCpuAbi);
5736 }
5737
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07005738 mInstrumentationPackageName = ii.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005739 mInstrumentationAppDir = ii.sourceDir;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07005740 mInstrumentationSplitAppDirs = ii.splitSourceDirs;
Todd Kennedye713efc2016-05-10 13:45:40 -07005741 mInstrumentationLibDir = getInstrumentationLibrary(data.appInfo, ii);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005742 mInstrumentedAppDir = data.info.getAppDir();
5743 mInstrumentedSplitAppDirs = data.info.getSplitAppDirs();
5744 mInstrumentedLibDir = data.info.getLibDir();
Alan Viverette2107d692015-09-03 14:55:27 -04005745 } else {
5746 ii = null;
5747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748
Todd Kennedy233a0b12018-01-29 20:30:24 +00005749 final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
Adam Lesinskib61e4052016-05-19 18:23:05 -07005750 updateLocaleListFromAppContext(appContext,
5751 mResourcesManager.getConfiguration().getLocales());
Seigo Nonakac14dd782016-03-30 23:09:16 +09005752
Jesse Hall317fa5a2017-05-23 15:46:55 -07005753 if (!Process.isIsolated()) {
Jeff Sharkey89182982017-11-01 19:02:56 -06005754 final int oldMask = StrictMode.allowThreadDiskWritesMask();
5755 try {
5756 setupGraphicsSupport(appContext);
5757 } finally {
5758 StrictMode.setThreadPolicyMask(oldMask);
5759 }
John Reck56428472018-03-16 17:27:17 -07005760 } else {
5761 ThreadedRenderer.setIsolatedProcess(true);
Michael Lentine2ba303f2016-02-01 20:44:34 -06005762 }
Michael Lentine03d8f7682016-01-31 15:37:11 -06005763
Calin Juravle37dfc8e2017-03-13 19:02:32 -07005764 // If we use profiles, setup the dex reporter to notify package manager
5765 // of any relevant dex loads. The idle maintenance job will use the information
5766 // reported to optimize the loaded dex files.
5767 // Note that we only need one global reporter per app.
5768 // Make sure we do this before calling onCreate so that we can capture the
5769 // complete application startup.
5770 if (SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false)) {
Calin Juravlef5a7bfc2017-03-13 23:30:30 -07005771 BaseDexClassLoader.setReporter(DexLoadReporter.getInstance());
Calin Juravle37dfc8e2017-03-13 19:02:32 -07005772 }
5773
Chad Brubaker78d47122015-11-17 22:26:58 -08005774 // Install the Network Security Config Provider. This must happen before the application
5775 // code is loaded to prevent issues with instances of TLS objects being created before
5776 // the provider is installed.
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005777 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "NetworkSecurityConfigProvider.install");
Chad Brubaker276ee962016-06-08 12:57:46 -07005778 NetworkSecurityConfigProvider.install(appContext);
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005779 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Chad Brubaker78d47122015-11-17 22:26:58 -08005780
Alan Viverette2107d692015-09-03 14:55:27 -04005781 // Continue loading instrumentation.
5782 if (ii != null) {
Dianne Hackbornf4ef6eb2017-12-07 13:57:21 -08005783 ApplicationInfo instrApp;
5784 try {
5785 instrApp = getPackageManager().getApplicationInfo(ii.packageName, 0,
5786 UserHandle.myUserId());
5787 } catch (RemoteException e) {
5788 instrApp = null;
5789 }
5790 if (instrApp == null) {
5791 instrApp = new ApplicationInfo();
5792 }
Jeff Sharkey15447792015-11-05 16:18:51 -08005793 ii.copyTo(instrApp);
Fyodor Kupolovaf38b8e2015-12-02 16:16:07 -08005794 instrApp.initForUser(UserHandle.myUserId());
Todd Kennedy233a0b12018-01-29 20:30:24 +00005795 final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07005796 appContext.getClassLoader(), false, true, false);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005797 final ContextImpl instrContext = ContextImpl.createAppContext(this, pi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005798
5799 try {
Alan Viverettebe64eae2015-09-03 14:56:04 -04005800 final ClassLoader cl = instrContext.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04005801 mInstrumentation = (Instrumentation)
5802 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005803 } catch (Exception e) {
5804 throw new RuntimeException(
5805 "Unable to instantiate instrumentation "
5806 + data.instrumentationName + ": " + e.toString(), e);
5807 }
5808
Alan Viverettebe64eae2015-09-03 14:56:04 -04005809 final ComponentName component = new ComponentName(ii.packageName, ii.name);
5810 mInstrumentation.init(this, instrContext, appContext, component,
5811 data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005812
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005813 if (mProfiler.profileFile != null && !ii.handleProfiling
5814 && mProfiler.profileFd == null) {
5815 mProfiler.handlingProfiling = true;
Alan Viverettebe64eae2015-09-03 14:56:04 -04005816 final File file = new File(mProfiler.profileFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005817 file.getParentFile().mkdirs();
5818 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
5819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005820 } else {
5821 mInstrumentation = new Instrumentation();
Jason Monka80bfb52017-11-16 17:15:37 -05005822 mInstrumentation.basicInit(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005823 }
5824
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08005825 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
Dianne Hackbornde398512011-01-18 18:45:21 -08005826 dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
Mathieu Chartier24cee072015-01-08 14:42:20 -08005827 } else {
5828 // Small heap, clamp to the current growth limit and let the heap release
5829 // pages after the growth limit to the non growth limit capacity. b/18387825
5830 dalvik.system.VMRuntime.getRuntime().clampGrowthLimit();
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08005831 }
5832
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005833 // Allow disk access during application and provider setup. This could
Jeff Sharkey7c501672012-02-28 12:08:37 -08005834 // block processing ordered broadcasts, but later processing would
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005835 // probably end up doing the same disk access.
Kurt Nelson5e154362017-06-29 17:20:56 -07005836 Application app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08005837 final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
Kurt Nelson571c3f62017-07-10 11:09:04 -07005838 final StrictMode.ThreadPolicy writesAllowedPolicy = StrictMode.getThreadPolicy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005839 try {
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005840 // If the app is being launched for full backup or restore, bring it up in
5841 // a restricted environment with the base application class.
Todd Kennedy233a0b12018-01-29 20:30:24 +00005842 app = data.info.makeApplication(data.restrictedBackupMode, null);
Svetoslav Ganov24c90452017-12-27 15:17:14 -08005843
5844 // Propagate autofill compat state
5845 app.setAutofillCompatibilityEnabled(data.autofillCompatibilityEnabled);
5846
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005847 mInitialApplication = app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08005848
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005849 // don't bring up providers in restricted mode; they may depend on the
5850 // app's custom Application class
5851 if (!data.restrictedBackupMode) {
Jeff Sharkey3e195892016-03-05 19:48:59 -07005852 if (!ArrayUtils.isEmpty(data.providers)) {
5853 installContentProviders(app, data.providers);
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005854 // For process that contains content providers, we want to
5855 // ensure that the JIT is enabled "at some point".
5856 mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
5857 }
5858 }
5859
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005860 // Do this after providers, since instrumentation tests generally start their
5861 // test thread at this point, and we don't want that racing.
5862 try {
5863 mInstrumentation.onCreate(data.instrumentationArgs);
5864 }
5865 catch (Exception e) {
5866 throw new RuntimeException(
5867 "Exception thrown in onCreate() of "
5868 + data.instrumentationName + ": " + e.toString(), e);
5869 }
Kurt Nelson571c3f62017-07-10 11:09:04 -07005870 try {
5871 mInstrumentation.callApplicationOnCreate(app);
5872 } catch (Exception e) {
5873 if (!mInstrumentation.onException(app, e)) {
5874 throw new RuntimeException(
5875 "Unable to create application " + app.getClass().getName()
5876 + ": " + e.toString(), e);
5877 }
5878 }
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08005879 } finally {
Kurt Nelson571c3f62017-07-10 11:09:04 -07005880 // If the app targets < O-MR1, or doesn't change the thread policy
5881 // during startup, clobber the policy to maintain behavior of b/36951662
Jeff Sharkeyaa1a9112018-04-10 15:18:12 -06005882 if (data.appInfo.targetSdkVersion < Build.VERSION_CODES.O_MR1
Kurt Nelson571c3f62017-07-10 11:09:04 -07005883 || StrictMode.getThreadPolicy().equals(writesAllowedPolicy)) {
5884 StrictMode.setThreadPolicy(savedPolicy);
Kurt Nelson5e154362017-06-29 17:20:56 -07005885 }
5886 }
5887
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00005888 // Preload fonts resources
Seigo Nonaka54084b62017-04-24 14:46:23 -07005889 FontsContract.setApplicationContextForResources(appContext);
Torne (Richard Coles)85ecae52018-01-30 18:13:00 -05005890 if (!Process.isIsolated()) {
5891 try {
5892 final ApplicationInfo info =
5893 getPackageManager().getApplicationInfo(
5894 data.appInfo.packageName,
5895 PackageManager.GET_META_DATA /*flags*/,
5896 UserHandle.myUserId());
5897 if (info.metaData != null) {
5898 final int preloadedFontsResource = info.metaData.getInt(
5899 ApplicationInfo.METADATA_PRELOADED_FONTS, 0);
5900 if (preloadedFontsResource != 0) {
5901 data.info.getResources().preloadFonts(preloadedFontsResource);
5902 }
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00005903 }
Torne (Richard Coles)85ecae52018-01-30 18:13:00 -05005904 } catch (RemoteException e) {
5905 throw e.rethrowFromSystemServer();
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00005906 }
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00005907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005908 }
5909
5910 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005911 IActivityManager am = ActivityManager.getService();
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005912 if (mProfiler.profileFile != null && mProfiler.handlingProfiling
5913 && mProfiler.profileFd == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005914 Debug.stopMethodTracing();
5915 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005916 //Slog.i(TAG, "am: " + ActivityManager.getService()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005917 // + ", app thr: " + mAppThread);
5918 try {
5919 am.finishInstrumentation(mAppThread, resultCode, results);
5920 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005921 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005922 }
5923 }
5924
Romain Guy65b345f2011-07-27 18:51:50 -07005925 private void installContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005926 Context context, List<ProviderInfo> providers) {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07005927 final ArrayList<ContentProviderHolder> results = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005928
Romain Guya998dff2012-03-23 18:58:36 -07005929 for (ProviderInfo cpi : providers) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08005930 if (DEBUG_PROVIDER) {
5931 StringBuilder buf = new StringBuilder(128);
5932 buf.append("Pub ");
5933 buf.append(cpi.authority);
5934 buf.append(": ");
5935 buf.append(cpi.name);
5936 Log.i(TAG, buf.toString());
5937 }
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07005938 ContentProviderHolder cph = installProvider(context, null, cpi,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005939 false /*noisy*/, true /*noReleaseNeeded*/, true /*stable*/);
5940 if (cph != null) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005941 cph.noReleaseNeeded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942 results.add(cph);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005943 }
5944 }
5945
5946 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005947 ActivityManager.getService().publishContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005948 getApplicationThread(), results);
5949 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005950 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005951 }
5952 }
5953
Jeff Sharkey6d515712012-09-20 16:06:08 -07005954 public final IContentProvider acquireProvider(
5955 Context c, String auth, int userId, boolean stable) {
Wale Ogunwale1d646122015-04-24 14:45:14 -07005956 final IContentProvider provider = acquireExistingProvider(c, auth, userId, stable);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005957 if (provider != null) {
5958 return provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 }
5960
Wale Ogunwale1d646122015-04-24 14:45:14 -07005961 // There is a possible race here. Another thread may try to acquire
5962 // the same provider at the same time. When this happens, we want to ensure
5963 // that the first one wins.
5964 // Note that we cannot hold the lock while acquiring and installing the
5965 // provider since it might take a long time to run and it could also potentially
5966 // be re-entrant in the case where the provider is in the same process.
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07005967 ContentProviderHolder holder = null;
Wale Ogunwale1d646122015-04-24 14:45:14 -07005968 try {
Makoto Onukib6c79ea2018-05-31 11:03:56 -07005969 synchronized (getGetProviderLock(auth, userId)) {
5970 holder = ActivityManager.getService().getContentProvider(
5971 getApplicationThread(), auth, userId, stable);
5972 }
Wale Ogunwale1d646122015-04-24 14:45:14 -07005973 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005974 throw ex.rethrowFromSystemServer();
Wale Ogunwale67fe0a42015-04-24 14:44:54 -07005975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 if (holder == null) {
Jeff Sharkey6d515712012-09-20 16:06:08 -07005977 Slog.e(TAG, "Failed to find provider info for " + auth);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005978 return null;
5979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005980
Jeff Brownddaa9ac2011-11-11 20:16:14 -08005981 // Install provider will increment the reference count for us, and break
5982 // any ties in the race.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07005983 holder = installProvider(c, holder, holder.info,
5984 true /*noisy*/, holder.noReleaseNeeded, stable);
5985 return holder.provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005986 }
5987
Makoto Onukib6c79ea2018-05-31 11:03:56 -07005988 private Object getGetProviderLock(String auth, int userId) {
5989 final ProviderKey key = new ProviderKey(auth, userId);
5990 synchronized (mGetProviderLocks) {
5991 Object lock = mGetProviderLocks.get(key);
5992 if (lock == null) {
5993 lock = key;
5994 mGetProviderLocks.put(key, lock);
5995 }
5996 return lock;
5997 }
5998 }
5999
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006000 private final void incProviderRefLocked(ProviderRefCount prc, boolean stable) {
6001 if (stable) {
6002 prc.stableCount += 1;
6003 if (prc.stableCount == 1) {
6004 // We are acquiring a new stable reference on the provider.
6005 int unstableDelta;
6006 if (prc.removePending) {
6007 // We have a pending remove operation, which is holding the
6008 // last unstable reference. At this point we are converting
6009 // that unstable reference to our new stable reference.
6010 unstableDelta = -1;
6011 // Cancel the removal of the provider.
6012 if (DEBUG_PROVIDER) {
6013 Slog.v(TAG, "incProviderRef: stable "
6014 + "snatched provider from the jaws of death");
6015 }
6016 prc.removePending = false;
Guobin Zhang9e3e52662013-03-21 13:57:11 +08006017 // There is a race! It fails to remove the message, which
6018 // will be handled in completeRemoveProvider().
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006019 mH.removeMessages(H.REMOVE_PROVIDER, prc);
6020 } else {
6021 unstableDelta = 0;
6022 }
6023 try {
6024 if (DEBUG_PROVIDER) {
6025 Slog.v(TAG, "incProviderRef Now stable - "
6026 + prc.holder.info.name + ": unstableDelta="
6027 + unstableDelta);
6028 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006029 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006030 prc.holder.connection, 1, unstableDelta);
6031 } catch (RemoteException e) {
6032 //do nothing content provider object is dead any way
6033 }
6034 }
6035 } else {
6036 prc.unstableCount += 1;
6037 if (prc.unstableCount == 1) {
6038 // We are acquiring a new unstable reference on the provider.
6039 if (prc.removePending) {
6040 // Oh look, we actually have a remove pending for the
6041 // provider, which is still holding the last unstable
6042 // reference. We just need to cancel that to take new
6043 // ownership of the reference.
6044 if (DEBUG_PROVIDER) {
6045 Slog.v(TAG, "incProviderRef: unstable "
6046 + "snatched provider from the jaws of death");
6047 }
6048 prc.removePending = false;
6049 mH.removeMessages(H.REMOVE_PROVIDER, prc);
6050 } else {
6051 // First unstable ref, increment our count in the
6052 // activity manager.
6053 try {
6054 if (DEBUG_PROVIDER) {
6055 Slog.v(TAG, "incProviderRef: Now unstable - "
6056 + prc.holder.info.name);
6057 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006058 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006059 prc.holder.connection, 0, 1);
6060 } catch (RemoteException e) {
6061 //do nothing content provider object is dead any way
6062 }
6063 }
6064 }
6065 }
6066 }
6067
Jeff Sharkey6d515712012-09-20 16:06:08 -07006068 public final IContentProvider acquireExistingProvider(
6069 Context c, String auth, int userId, boolean stable) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006070 synchronized (mProviderMap) {
Wale Ogunwale1d646122015-04-24 14:45:14 -07006071 final ProviderKey key = new ProviderKey(auth, userId);
Jeff Sharkey6d515712012-09-20 16:06:08 -07006072 final ProviderClientRecord pr = mProviderMap.get(key);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006073 if (pr == null) {
6074 return null;
6075 }
6076
6077 IContentProvider provider = pr.mProvider;
6078 IBinder jBinder = provider.asBinder();
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006079 if (!jBinder.isBinderAlive()) {
6080 // The hosting process of the provider has died; we can't
6081 // use this one.
Wale Ogunwale1d646122015-04-24 14:45:14 -07006082 Log.i(TAG, "Acquiring provider " + auth + " for user " + userId
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006083 + ": existing object's process dead");
6084 handleUnstableProviderDiedLocked(jBinder, true);
6085 return null;
6086 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006087
6088 // Only increment the ref count if we have one. If we don't then the
6089 // provider is not reference counted and never needs to be released.
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006090 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006091 if (prc != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006092 incProviderRefLocked(prc, stable);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006093 }
6094 return provider;
6095 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006096 }
6097
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006098 public final boolean releaseProvider(IContentProvider provider, boolean stable) {
6099 if (provider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006100 return false;
6101 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006103 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006104 synchronized (mProviderMap) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006106 if (prc == null) {
6107 // The provider has no ref count, no release is needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006108 return false;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006109 }
6110
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006111 boolean lastRef = false;
6112 if (stable) {
6113 if (prc.stableCount == 0) {
6114 if (DEBUG_PROVIDER) Slog.v(TAG,
6115 "releaseProvider: stable ref count already 0, how?");
6116 return false;
6117 }
6118 prc.stableCount -= 1;
6119 if (prc.stableCount == 0) {
6120 // What we do at this point depends on whether there are
6121 // any unstable refs left: if there are, we just tell the
6122 // activity manager to decrement its stable count; if there
6123 // aren't, we need to enqueue this provider to be removed,
6124 // and convert to holding a single unstable ref while
6125 // doing so.
6126 lastRef = prc.unstableCount == 0;
6127 try {
6128 if (DEBUG_PROVIDER) {
6129 Slog.v(TAG, "releaseProvider: No longer stable w/lastRef="
6130 + lastRef + " - " + prc.holder.info.name);
6131 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006132 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006133 prc.holder.connection, -1, lastRef ? 1 : 0);
6134 } catch (RemoteException e) {
6135 //do nothing content provider object is dead any way
6136 }
6137 }
6138 } else {
6139 if (prc.unstableCount == 0) {
6140 if (DEBUG_PROVIDER) Slog.v(TAG,
6141 "releaseProvider: unstable ref count already 0, how?");
6142 return false;
6143 }
6144 prc.unstableCount -= 1;
6145 if (prc.unstableCount == 0) {
6146 // If this is the last reference, we need to enqueue
6147 // this provider to be removed instead of telling the
6148 // activity manager to remove it at this point.
6149 lastRef = prc.stableCount == 0;
6150 if (!lastRef) {
6151 try {
6152 if (DEBUG_PROVIDER) {
6153 Slog.v(TAG, "releaseProvider: No longer unstable - "
6154 + prc.holder.info.name);
6155 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006156 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006157 prc.holder.connection, 0, -1);
6158 } catch (RemoteException e) {
6159 //do nothing content provider object is dead any way
6160 }
6161 }
6162 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006163 }
6164
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006165 if (lastRef) {
6166 if (!prc.removePending) {
6167 // Schedule the actual remove asynchronously, since we don't know the context
6168 // this will be called in.
6169 // TODO: it would be nice to post a delayed message, so
6170 // if we come back and need the same provider quickly
6171 // we will still have it available.
6172 if (DEBUG_PROVIDER) {
6173 Slog.v(TAG, "releaseProvider: Enqueueing pending removal - "
6174 + prc.holder.info.name);
6175 }
6176 prc.removePending = true;
6177 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, prc);
6178 mH.sendMessage(msg);
6179 } else {
6180 Slog.w(TAG, "Duplicate remove pending of provider " + prc.holder.info.name);
6181 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006182 }
6183 return true;
6184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 }
6186
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006187 final void completeRemoveProvider(ProviderRefCount prc) {
6188 synchronized (mProviderMap) {
6189 if (!prc.removePending) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006190 // There was a race! Some other client managed to acquire
6191 // the provider before the removal was completed.
6192 // Abort the removal. We will do it later.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006193 if (DEBUG_PROVIDER) Slog.v(TAG, "completeRemoveProvider: lost the race, "
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006194 + "provider still in use");
6195 return;
6196 }
6197
Guobin Zhang9e3e52662013-03-21 13:57:11 +08006198 // More complicated race!! Some client managed to acquire the
6199 // provider and release it before the removal was completed.
6200 // Continue the removal, and abort the next remove message.
6201 prc.removePending = false;
6202
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006203 final IBinder jBinder = prc.holder.provider.asBinder();
6204 ProviderRefCount existingPrc = mProviderRefCountMap.get(jBinder);
6205 if (existingPrc == prc) {
6206 mProviderRefCountMap.remove(jBinder);
6207 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006208
Dianne Hackbornadd005c2013-07-17 18:43:12 -07006209 for (int i=mProviderMap.size()-1; i>=0; i--) {
6210 ProviderClientRecord pr = mProviderMap.valueAt(i);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006211 IBinder myBinder = pr.mProvider.asBinder();
6212 if (myBinder == jBinder) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07006213 mProviderMap.removeAt(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006214 }
6215 }
6216 }
6217
6218 try {
6219 if (DEBUG_PROVIDER) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006220 Slog.v(TAG, "removeProvider: Invoking ActivityManagerService."
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006221 + "removeContentProvider(" + prc.holder.info.name + ")");
6222 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006223 ActivityManager.getService().removeContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006224 prc.holder.connection, false);
6225 } catch (RemoteException e) {
6226 //do nothing content provider object is dead any way
6227 }
6228 }
6229
6230 final void handleUnstableProviderDied(IBinder provider, boolean fromClient) {
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006231 synchronized (mProviderMap) {
6232 handleUnstableProviderDiedLocked(provider, fromClient);
6233 }
6234 }
6235
6236 final void handleUnstableProviderDiedLocked(IBinder provider, boolean fromClient) {
6237 ProviderRefCount prc = mProviderRefCountMap.get(provider);
6238 if (prc != null) {
6239 if (DEBUG_PROVIDER) Slog.v(TAG, "Cleaning up dead provider "
6240 + provider + " " + prc.holder.info.name);
6241 mProviderRefCountMap.remove(provider);
You Kimbc74de62013-10-01 00:13:26 +09006242 for (int i=mProviderMap.size()-1; i>=0; i--) {
6243 ProviderClientRecord pr = mProviderMap.valueAt(i);
6244 if (pr != null && pr.mProvider.asBinder() == provider) {
6245 Slog.i(TAG, "Removing dead content provider:" + pr.mProvider.toString());
6246 mProviderMap.removeAt(i);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006247 }
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006248 }
You Kimbc74de62013-10-01 00:13:26 +09006249
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006250 if (fromClient) {
6251 // We found out about this due to execution in our client
6252 // code. Tell the activity manager about it now, to ensure
6253 // that the next time we go to do anything with the provider
6254 // it knows it is dead (so we don't race with its death
6255 // notification).
6256 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006257 ActivityManager.getService().unstableProviderDied(
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006258 prc.holder.connection);
6259 } catch (RemoteException e) {
6260 //do nothing content provider object is dead any way
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006261 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07006262 }
6263 }
6264 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006265
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006266 final void appNotRespondingViaProvider(IBinder provider) {
6267 synchronized (mProviderMap) {
6268 ProviderRefCount prc = mProviderRefCountMap.get(provider);
6269 if (prc != null) {
6270 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006271 ActivityManager.getService()
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006272 .appNotRespondingViaProvider(prc.holder.connection);
6273 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006274 throw e.rethrowFromSystemServer();
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006275 }
6276 }
6277 }
6278 }
6279
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006280 private ProviderClientRecord installProviderAuthoritiesLocked(IContentProvider provider,
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006281 ContentProvider localProvider, ContentProviderHolder holder) {
Andreas Gampe18e99c12015-03-06 15:29:06 -08006282 final String auths[] = holder.info.authority.split(";");
Jeff Sharkey6d515712012-09-20 16:06:08 -07006283 final int userId = UserHandle.getUserId(holder.info.applicationInfo.uid);
6284
Jeff Sharkey0a17db12016-11-04 11:23:46 -06006285 if (provider != null) {
6286 // If this provider is hosted by the core OS and cannot be upgraded,
6287 // then I guess we're okay doing blocking calls to it.
6288 for (String auth : auths) {
6289 switch (auth) {
6290 case ContactsContract.AUTHORITY:
6291 case CallLog.AUTHORITY:
6292 case CallLog.SHADOW_AUTHORITY:
6293 case BlockedNumberContract.AUTHORITY:
6294 case CalendarContract.AUTHORITY:
6295 case Downloads.Impl.AUTHORITY:
Jeff Sharkeycb621622016-11-11 14:04:32 -07006296 case "telephony":
Jeff Sharkey0a17db12016-11-04 11:23:46 -06006297 Binder.allowBlocking(provider.asBinder());
6298 }
6299 }
6300 }
6301
Jeff Sharkey6d515712012-09-20 16:06:08 -07006302 final ProviderClientRecord pcr = new ProviderClientRecord(
6303 auths, provider, localProvider, holder);
6304 for (String auth : auths) {
6305 final ProviderKey key = new ProviderKey(auth, userId);
6306 final ProviderClientRecord existing = mProviderMap.get(key);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006307 if (existing != null) {
6308 Slog.w(TAG, "Content provider " + pcr.mHolder.info.name
Jeff Sharkey6d515712012-09-20 16:06:08 -07006309 + " already published as " + auth);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006310 } else {
Jeff Sharkey6d515712012-09-20 16:06:08 -07006311 mProviderMap.put(key, pcr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006312 }
6313 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006314 return pcr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006315 }
6316
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006317 /**
6318 * Installs the provider.
6319 *
6320 * Providers that are local to the process or that come from the system server
6321 * may be installed permanently which is indicated by setting noReleaseNeeded to true.
6322 * Other remote providers are reference counted. The initial reference count
6323 * for all reference counted providers is one. Providers that are not reference
6324 * counted do not have a reference count (at all).
6325 *
6326 * This method detects when a provider has already been installed. When this happens,
6327 * it increments the reference count of the existing provider (if appropriate)
6328 * and returns the existing provider. This can happen due to concurrent
6329 * attempts to acquire the same provider.
6330 */
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006331 private ContentProviderHolder installProvider(Context context,
6332 ContentProviderHolder holder, ProviderInfo info,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006333 boolean noisy, boolean noReleaseNeeded, boolean stable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006334 ContentProvider localProvider = null;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006335 IContentProvider provider;
Dianne Hackborn5f48fca2012-05-30 11:06:31 -07006336 if (holder == null || holder.provider == null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006337 if (DEBUG_PROVIDER || noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006338 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006339 + info.name);
6340 }
6341 Context c = null;
6342 ApplicationInfo ai = info.applicationInfo;
6343 if (context.getPackageName().equals(ai.packageName)) {
6344 c = context;
6345 } else if (mInitialApplication != null &&
6346 mInitialApplication.getPackageName().equals(ai.packageName)) {
6347 c = mInitialApplication;
6348 } else {
6349 try {
6350 c = context.createPackageContext(ai.packageName,
6351 Context.CONTEXT_INCLUDE_CODE);
6352 } catch (PackageManager.NameNotFoundException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07006353 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006354 }
6355 }
6356 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08006357 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006358 ai.packageName +
6359 " while loading content provider " +
6360 info.name);
6361 return null;
6362 }
Adam Lesinski4e862812016-11-21 16:02:24 -08006363
6364 if (info.splitName != null) {
6365 try {
6366 c = c.createContextForSplit(info.splitName);
6367 } catch (NameNotFoundException e) {
6368 throw new RuntimeException(e);
6369 }
6370 }
6371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006372 try {
6373 final java.lang.ClassLoader cl = c.getClassLoader();
Todd Kennedy233a0b12018-01-29 20:30:24 +00006374 LoadedApk packageInfo = peekPackageInfo(ai.packageName, true);
6375 if (packageInfo == null) {
Jason Monka80bfb52017-11-16 17:15:37 -05006376 // System startup case.
Todd Kennedy233a0b12018-01-29 20:30:24 +00006377 packageInfo = getSystemContext().mPackageInfo;
Jason Monka80bfb52017-11-16 17:15:37 -05006378 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00006379 localProvider = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05006380 .instantiateProvider(cl, info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006381 provider = localProvider.getIContentProvider();
6382 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08006383 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006384 info.name + " from sourceDir " +
6385 info.applicationInfo.sourceDir);
6386 return null;
6387 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006388 if (DEBUG_PROVIDER) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006389 TAG, "Instantiating local provider " + info.name);
6390 // XXX Need to create the correct context for this provider.
6391 localProvider.attachInfo(c, info);
6392 } catch (java.lang.Exception e) {
6393 if (!mInstrumentation.onException(null, e)) {
6394 throw new RuntimeException(
6395 "Unable to get provider " + info.name
6396 + ": " + e.toString(), e);
6397 }
6398 return null;
6399 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006400 } else {
6401 provider = holder.provider;
6402 if (DEBUG_PROVIDER) Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403 + info.name);
6404 }
6405
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006406 ContentProviderHolder retHolder;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006407
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006408 synchronized (mProviderMap) {
6409 if (DEBUG_PROVIDER) Slog.v(TAG, "Checking to add " + provider
6410 + " / " + info.name);
6411 IBinder jBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006412 if (localProvider != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006413 ComponentName cname = new ComponentName(info.packageName, info.name);
6414 ProviderClientRecord pr = mLocalProvidersByName.get(cname);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006415 if (pr != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006416 if (DEBUG_PROVIDER) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006417 Slog.v(TAG, "installProvider: lost the race, "
6418 + "using existing local provider");
6419 }
6420 provider = pr.mProvider;
6421 } else {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006422 holder = new ContentProviderHolder(info);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006423 holder.provider = provider;
6424 holder.noReleaseNeeded = true;
6425 pr = installProviderAuthoritiesLocked(provider, localProvider, holder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006426 mLocalProviders.put(jBinder, pr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006427 mLocalProvidersByName.put(cname, pr);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006428 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006429 retHolder = pr.mHolder;
6430 } else {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006431 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
6432 if (prc != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006433 if (DEBUG_PROVIDER) {
6434 Slog.v(TAG, "installProvider: lost the race, updating ref count");
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006435 }
Wale Ogunwale1d646122015-04-24 14:45:14 -07006436 // We need to transfer our new reference to the existing
6437 // ref count, releasing the old one... but only if
6438 // release is needed (that is, it is not running in the
6439 // system process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006440 if (!noReleaseNeeded) {
6441 incProviderRefLocked(prc, stable);
Wale Ogunwale1d646122015-04-24 14:45:14 -07006442 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006443 ActivityManager.getService().removeContentProvider(
Wale Ogunwale1d646122015-04-24 14:45:14 -07006444 holder.connection, stable);
6445 } catch (RemoteException e) {
6446 //do nothing content provider object is dead any way
6447 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006448 }
6449 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006450 ProviderClientRecord client = installProviderAuthoritiesLocked(
6451 provider, localProvider, holder);
6452 if (noReleaseNeeded) {
6453 prc = new ProviderRefCount(holder, client, 1000, 1000);
6454 } else {
6455 prc = stable
6456 ? new ProviderRefCount(holder, client, 1, 0)
6457 : new ProviderRefCount(holder, client, 0, 1);
6458 }
6459 mProviderRefCountMap.put(jBinder, prc);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006460 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006461 retHolder = prc.holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 }
6463 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006464 return retHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006465 }
6466
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04006467 private void handleRunIsolatedEntryPoint(String entryPoint, String[] entryPointArgs) {
6468 try {
6469 Method main = Class.forName(entryPoint).getMethod("main", String[].class);
6470 main.invoke(null, new Object[]{entryPointArgs});
6471 } catch (ReflectiveOperationException e) {
6472 throw new AndroidRuntimeException("runIsolatedEntryPoint failed", e);
6473 }
6474 // The process will be empty after this method returns; exit the VM now.
6475 System.exit(0);
6476 }
6477
Sudheer Shankaf6690102017-10-16 10:20:32 -07006478 private void attach(boolean system, long startSeq) {
Jeff Sharkey66a017b2013-01-17 18:18:22 -08006479 sCurrentActivityThread = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006480 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006481 if (!system) {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07006482 ViewRootImpl.addFirstDrawHandler(new Runnable() {
Craig Mautner88c05892013-06-28 09:47:45 -07006483 @Override
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08006484 public void run() {
6485 ensureJitEnabled();
6486 }
6487 });
Siva Velusamyd693dfa2012-09-10 14:36:58 -07006488 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
6489 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006490 RuntimeInit.setApplicationObject(mAppThread.asBinder());
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006491 final IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 try {
Sudheer Shankaf6690102017-10-16 10:20:32 -07006493 mgr.attachApplication(mAppThread, startSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006494 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006495 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006496 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006497 // Watch for getting close to heap limit.
6498 BinderInternal.addGcWatcher(new Runnable() {
6499 @Override public void run() {
6500 if (!mSomeActivitiesChanged) {
6501 return;
6502 }
6503 Runtime runtime = Runtime.getRuntime();
6504 long dalvikMax = runtime.maxMemory();
6505 long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
6506 if (dalvikUsed > ((3*dalvikMax)/4)) {
6507 if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
6508 + " total=" + (runtime.totalMemory()/1024)
6509 + " used=" + (dalvikUsed/1024));
6510 mSomeActivitiesChanged = false;
6511 try {
6512 mgr.releaseSomeActivities(mAppThread);
6513 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006514 throw e.rethrowFromSystemServer();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006515 }
6516 }
6517 }
6518 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006519 } else {
6520 // Don't set application object here -- if the system crashes,
6521 // we can't display an alert, we just want to die die die.
Siva Velusamyd693dfa2012-09-10 14:36:58 -07006522 android.ddm.DdmHandleAppName.setAppName("system_process",
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006523 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 try {
6525 mInstrumentation = new Instrumentation();
Jason Monka80bfb52017-11-16 17:15:37 -05006526 mInstrumentation.basicInit(this);
Jeff Browndefd4a62014-03-10 21:24:37 -07006527 ContextImpl context = ContextImpl.createAppContext(
Todd Kennedy233a0b12018-01-29 20:30:24 +00006528 this, getSystemContext().mPackageInfo);
6529 mInitialApplication = context.mPackageInfo.makeApplication(true, null);
Jeff Brown7fc8e352014-09-16 18:06:47 -07006530 mInitialApplication.onCreate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531 } catch (Exception e) {
6532 throw new RuntimeException(
6533 "Unable to instantiate Application():" + e.toString(), e);
6534 }
6535 }
Geremy Condrab7faaf42012-09-19 18:07:42 -07006536
6537 // add dropbox logging to libcore
6538 DropBox.setReporter(new DropBoxReporter());
6539
Andrii Kulian44607962017-03-16 11:06:24 -07006540 ViewRootImpl.ConfigChangedCallback configChangedCallback
6541 = (Configuration globalConfig) -> {
6542 synchronized (mResourcesManager) {
6543 // We need to apply this change to the resources immediately, because upon returning
6544 // the view hierarchy will be informed about it.
6545 if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,
6546 null /* compat */)) {
6547 updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
6548 mResourcesManager.getConfiguration().getLocales());
Adam Lesinskib61e4052016-05-19 18:23:05 -07006549
Andrii Kulian44607962017-03-16 11:06:24 -07006550 // This actually changed the resources! Tell everyone about it.
6551 if (mPendingConfiguration == null
6552 || mPendingConfiguration.isOtherSeqNewer(globalConfig)) {
6553 mPendingConfiguration = globalConfig;
6554 sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08006555 }
6556 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08006557 }
Andrii Kulian44607962017-03-16 11:06:24 -07006558 };
6559 ViewRootImpl.addConfigCallback(configChangedCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006560 }
6561
Romain Guy5e9120d2012-01-30 12:17:22 -08006562 public static ActivityThread systemMain() {
Alan Viverette5e1565e2014-07-29 16:14:25 -07006563 // The system process on low-memory devices do not get to use hardware
6564 // accelerated drawing, since this can add too much overhead to the
6565 // process.
6566 if (!ActivityManager.isHighEndGfx()) {
John Reck51aaf902015-12-02 15:08:07 -08006567 ThreadedRenderer.disable(true);
John Reck73840ea2014-09-22 07:39:18 -07006568 } else {
John Reck51aaf902015-12-02 15:08:07 -08006569 ThreadedRenderer.enableForegroundTrimming();
Alan Viverette5e1565e2014-07-29 16:14:25 -07006570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006571 ActivityThread thread = new ActivityThread();
Sudheer Shankaf6690102017-10-16 10:20:32 -07006572 thread.attach(true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006573 return thread;
6574 }
6575
Jeff Brown10e89712011-07-08 18:52:57 -07006576 public final void installSystemProviders(List<ProviderInfo> providers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006577 if (providers != null) {
Jeff Brown10e89712011-07-08 18:52:57 -07006578 installContentProviders(mInitialApplication, providers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006579 }
6580 }
6581
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006582 public int getIntCoreSetting(String key, int defaultValue) {
Craig Mautner88c05892013-06-28 09:47:45 -07006583 synchronized (mResourcesManager) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08006584 if (mCoreSettings != null) {
6585 return mCoreSettings.getInt(key, defaultValue);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006586 }
Craig Mautner88c05892013-06-28 09:47:45 -07006587 return defaultValue;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006588 }
6589 }
6590
Geremy Condra69689a72012-09-11 16:57:17 -07006591 private static class EventLoggingReporter implements EventLogger.Reporter {
6592 @Override
6593 public void report (int code, Object... list) {
6594 EventLog.writeEvent(code, list);
6595 }
6596 }
6597
Geremy Condrab7faaf42012-09-19 18:07:42 -07006598 private class DropBoxReporter implements DropBox.Reporter {
6599
6600 private DropBoxManager dropBox;
6601
Narayan Kamath7f062242015-04-08 13:24:13 +01006602 public DropBoxReporter() {}
Geremy Condrab7faaf42012-09-19 18:07:42 -07006603
6604 @Override
6605 public void addData(String tag, byte[] data, int flags) {
Narayan Kamath7f062242015-04-08 13:24:13 +01006606 ensureInitialized();
Geremy Condrab7faaf42012-09-19 18:07:42 -07006607 dropBox.addData(tag, data, flags);
6608 }
6609
6610 @Override
6611 public void addText(String tag, String data) {
Narayan Kamath7f062242015-04-08 13:24:13 +01006612 ensureInitialized();
Geremy Condrab7faaf42012-09-19 18:07:42 -07006613 dropBox.addText(tag, data);
6614 }
Narayan Kamath7f062242015-04-08 13:24:13 +01006615
6616 private synchronized void ensureInitialized() {
6617 if (dropBox == null) {
6618 dropBox = (DropBoxManager) getSystemContext().getSystemService(Context.DROPBOX_SERVICE);
6619 }
6620 }
Geremy Condrab7faaf42012-09-19 18:07:42 -07006621 }
6622
Romain Guy65b345f2011-07-27 18:51:50 -07006623 public static void main(String[] args) {
Narayan Kamathfbb32f62015-06-12 15:34:35 +01006624 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
Bob Leee5408332009-09-04 18:31:17 -07006625
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08006626 // CloseGuard defaults to true and can be quite spammy. We
6627 // disable it here, but selectively enable it later (via
6628 // StrictMode) on debug builds, but using DropBox, not logs.
6629 CloseGuard.setEnabled(false);
6630
Andreas Gamped281b422016-07-08 03:50:27 +00006631 Environment.initForCurrentUser();
Jeff Sharkeyb049e212012-09-07 23:16:01 -07006632
Geremy Condra69689a72012-09-11 16:57:17 -07006633 // Set the reporter for event logging in libcore
6634 EventLogger.setReporter(new EventLoggingReporter());
6635
Robin Lee3d076af2014-04-25 14:57:49 +01006636 // Make sure TrustedCertificateStore looks in the right place for CA certificates
6637 final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
6638 TrustedCertificateStore.setDefaultUserDirectory(configDir);
6639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006640 Process.setArgV0("<pre-initialized>");
6641
6642 Looper.prepareMainLooper();
6643
Sudheer Shankaf6690102017-10-16 10:20:32 -07006644 // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
6645 // It will be in the format "seq=114"
6646 long startSeq = 0;
6647 if (args != null) {
6648 for (int i = args.length - 1; i >= 0; --i) {
6649 if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
6650 startSeq = Long.parseLong(
6651 args[i].substring(PROC_START_SEQ_IDENT.length()));
6652 }
6653 }
6654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006655 ActivityThread thread = new ActivityThread();
Sudheer Shankaf6690102017-10-16 10:20:32 -07006656 thread.attach(false, startSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006657
Vairavan Srinivasan7335cfd2012-08-18 18:36:03 -07006658 if (sMainThreadHandler == null) {
6659 sMainThreadHandler = thread.getHandler();
6660 }
6661
Dianne Hackborn287952c2010-09-22 22:34:31 -07006662 if (false) {
6663 Looper.myLooper().setMessageLogging(new
6664 LogPrinter(Log.DEBUG, "ActivityThread"));
6665 }
6666
Narayan Kamathfbb32f62015-06-12 15:34:35 +01006667 // End of event ActivityThreadMain.
6668 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006669 Looper.loop();
6670
Jeff Brown10e89712011-07-08 18:52:57 -07006671 throw new RuntimeException("Main thread loop unexpectedly exited");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006672 }
Chris Craikfc294242016-12-13 18:10:46 -08006673
6674 // ------------------ Regular JNI ------------------------
6675
6676 private native void nDumpGraphicsInfo(FileDescriptor fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006677}