blob: 4450ff2730ba64b6c9c9f5e6f71c657d11c6e1a6 [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
Riddle Hsu50e34002019-04-12 20:42:05 +080019import static android.app.ActivityManager.PROCESS_STATE_UNKNOWN;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080020import static android.app.servertransaction.ActivityLifecycleItem.ON_CREATE;
21import static android.app.servertransaction.ActivityLifecycleItem.ON_DESTROY;
22import static android.app.servertransaction.ActivityLifecycleItem.ON_PAUSE;
23import static android.app.servertransaction.ActivityLifecycleItem.ON_RESUME;
24import static android.app.servertransaction.ActivityLifecycleItem.ON_START;
25import static android.app.servertransaction.ActivityLifecycleItem.ON_STOP;
26import static android.app.servertransaction.ActivityLifecycleItem.PRE_ON_CREATE;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -060027import static android.content.ContentResolver.DEPRECATE_DATA_COLUMNS;
28import static android.content.ContentResolver.DEPRECATE_DATA_PREFIX;
Andrii Kulianb047b8b2017-02-08 18:38:26 -080029import static android.view.Display.INVALID_DISPLAY;
30
Adrian Roos03dd48c2019-03-19 17:17:37 -040031import static com.android.internal.annotations.VisibleForTesting.Visibility.PACKAGE;
32
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -070033import android.annotation.NonNull;
34import android.annotation.Nullable;
Mathew Inwood61e8ae62018-08-14 14:17:44 +010035import android.annotation.UnsupportedAppUsage;
Dianne Hackborn69c6adc2015-06-02 10:52:59 -070036import android.app.assist.AssistContent;
37import android.app.assist.AssistStructure;
Christopher Tate45281862010-03-05 15:46:30 -080038import android.app.backup.BackupAgent;
Andrii Kulian914aa7d2018-03-19 21:51:53 -070039import android.app.servertransaction.ActivityLifecycleItem;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080040import android.app.servertransaction.ActivityLifecycleItem.LifecycleState;
Andrii Kulian914aa7d2018-03-19 21:51:53 -070041import android.app.servertransaction.ActivityRelaunchItem;
Andrii Kulian446e8242017-10-26 15:17:29 -070042import android.app.servertransaction.ActivityResultItem;
43import android.app.servertransaction.ClientTransaction;
Riddle Hsud3062cb2018-06-30 02:06:42 +080044import android.app.servertransaction.ClientTransactionItem;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080045import android.app.servertransaction.PendingTransactionActions;
46import android.app.servertransaction.PendingTransactionActions.StopInfo;
47import android.app.servertransaction.TransactionExecutor;
Andrii Kulian914aa7d2018-03-19 21:51:53 -070048import android.app.servertransaction.TransactionExecutorHelper;
Felipe Lemea4f39cd2019-02-19 15:08:59 -080049import android.content.AutofillOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.content.BroadcastReceiver;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070051import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.content.ComponentName;
Felipe Leme326f15a2019-02-19 09:42:24 -080053import android.content.ContentCaptureOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.content.ContentProvider;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -060055import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.Context;
57import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070058import android.content.IIntentReceiver;
Jesse Hall317fa5a2017-05-23 15:46:55 -070059import android.content.Intent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.content.pm.ActivityInfo;
61import android.content.pm.ApplicationInfo;
62import android.content.pm.IPackageManager;
63import android.content.pm.InstrumentationInfo;
Christopher Tate346acb12012-10-15 19:20:25 -070064import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.content.pm.PackageManager;
Sen Hubde75702010-05-28 01:54:03 -070066import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070067import android.content.pm.ParceledListSlice;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.content.pm.ProviderInfo;
69import android.content.pm.ServiceInfo;
70import android.content.res.AssetManager;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -070071import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.content.res.Configuration;
73import android.content.res.Resources;
Alan Viverettee54d2452015-05-06 10:41:43 -070074import android.content.res.Resources.Theme;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.database.sqlite.SQLiteDatabase;
76import android.database.sqlite.SQLiteDebug;
Vasu Noric3849202010-03-09 10:47:25 -080077import android.database.sqlite.SQLiteDebug.DbStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.graphics.Bitmap;
79import android.graphics.Canvas;
John Reck8785ceb2018-10-29 16:45:58 -070080import android.graphics.HardwareRenderer;
Leon Scroggins III8290eab2018-03-19 10:51:44 -040081import android.graphics.ImageDecoder;
Jeff Brownbd6e1502012-08-28 03:27:37 -070082import android.hardware.display.DisplayManagerGlobal;
Paul Jensene0bef712014-12-10 15:12:18 -050083import android.net.ConnectivityManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070084import android.net.IConnectivityManager;
85import android.net.Proxy;
Jason Monk83520b92014-05-09 15:16:06 -040086import android.net.Uri;
Joe Onoratod630f102011-03-17 18:42:26 -070087import android.os.AsyncTask;
Amith Yamasani742a6712011-05-04 14:49:28 -070088import android.os.Binder;
Jeff Sharkey344744b2016-01-28 19:03:30 -070089import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.os.Bundle;
Sunny Goyald40c3452019-03-20 12:46:55 -070091import android.os.CancellationSignal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.os.Debug;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070093import android.os.Environment;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -060094import android.os.FileUtils;
Jesse Hallb12249b2016-12-12 12:53:02 -080095import android.os.GraphicsEnvironment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import android.os.Handler;
Jeff Sharkey8439ac02017-12-12 17:26:23 -070097import android.os.HandlerExecutor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import android.os.IBinder;
Sunny Goyald40c3452019-03-20 12:46:55 -070099import android.os.ICancellationSignal;
Adam Lesinskib61e4052016-05-19 18:23:05 -0700100import android.os.LocaleList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import android.os.Looper;
102import android.os.Message;
103import android.os.MessageQueue;
Dianne Hackbornfabb70b2014-11-11 12:22:36 -0800104import android.os.Parcel;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700105import android.os.ParcelFileDescriptor;
Craig Mautnera0026042014-04-23 11:45:37 -0700106import android.os.PersistableBundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import android.os.Process;
Makoto Onuki2c6657f2018-06-06 15:24:02 -0700108import android.os.RemoteCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import android.os.RemoteException;
110import android.os.ServiceManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700111import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.os.SystemClock;
Jeff Brownefd43bd2012-09-21 17:02:35 -0700113import android.os.SystemProperties;
Dianne Hackborn1ded0b12012-04-26 14:14:50 -0700114import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700115import android.os.UserHandle;
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600116import android.provider.BlockedNumberContract;
117import android.provider.CalendarContract;
118import android.provider.CallLog;
119import android.provider.ContactsContract;
120import android.provider.Downloads;
Seigo Nonaka54084b62017-04-24 14:46:23 -0700121import android.provider.FontsContract;
Narayan Kamathccb2a0862013-12-19 14:49:36 +0000122import android.provider.Settings;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700123import android.renderscript.RenderScriptCacheDir;
Chad Brubakerc72875b2016-04-27 16:35:11 -0700124import android.security.NetworkSecurityPolicy;
Chad Brubaker78d47122015-11-17 22:26:58 -0800125import android.security.net.config.NetworkSecurityConfigProvider;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -0600126import android.system.ErrnoException;
127import android.system.OsConstants;
128import android.system.StructStat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129import android.util.AndroidRuntimeException;
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700130import android.util.ArrayMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import android.util.DisplayMetrics;
132import android.util.EventLog;
133import android.util.Log;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700134import android.util.LogPrinter;
Andrii Kulianb372da62018-01-18 10:46:24 -0800135import android.util.MergedConfiguration;
Craig Mautnereb8abf72014-07-02 15:04:09 -0700136import android.util.Pair;
Jeff Brown6754ba22011-12-14 20:20:01 -0800137import android.util.PrintWriterPrinter;
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800138import android.util.Slog;
Annie Mengd5827872019-01-30 20:28:57 +0000139import android.util.SparseArray;
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -0700140import android.util.SparseIntArray;
Adam Powell14874662013-07-18 19:42:41 -0700141import android.util.SuperNotCalledException;
Kweku Adams4be0b1a2019-04-25 16:16:34 -0700142import android.util.UtilConfig;
Kweku Adams598e9a22017-11-02 17:12:20 -0700143import android.util.proto.ProtoOutputStream;
Jorim Jaggib29e3182018-04-30 18:51:56 +0200144import android.view.Choreographer;
Adam Lesinski3ad1b482016-04-01 16:41:41 -0700145import android.view.ContextThemeWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146import android.view.Display;
John Reck51aaf902015-12-02 15:08:07 -0800147import android.view.ThreadedRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148import android.view.View;
149import android.view.ViewDebug;
150import android.view.ViewManager;
Dianne Hackborn6dd005b2011-07-18 13:22:50 -0700151import android.view.ViewRootImpl;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152import android.view.Window;
153import android.view.WindowManager;
Jeff Brown98365d72012-08-19 20:30:52 -0700154import android.view.WindowManagerGlobal;
Richard Uhler2c036192016-09-14 09:48:31 +0100155import android.webkit.WebView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700157import com.android.internal.annotations.GuardedBy;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800158import com.android.internal.annotations.VisibleForTesting;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700159import com.android.internal.app.IVoiceInteractor;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800160import com.android.internal.content.ReferrerIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161import com.android.internal.os.BinderInternal;
162import com.android.internal.os.RuntimeInit;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700163import com.android.internal.os.SomeArgs;
Jeff Sharkey3e195892016-03-05 19:48:59 -0700164import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -0700165import com.android.internal.util.FastPrintWriter;
Sunny Goyald40c3452019-03-20 12:46:55 -0700166import com.android.internal.util.Preconditions;
Jorim Jaggib29e3182018-04-30 18:51:56 +0200167import com.android.internal.util.function.pooled.PooledLambda;
Kenny Root12e75222013-04-23 22:34:24 -0700168import com.android.org.conscrypt.OpenSSLSocketImpl;
Robin Lee3d076af2014-04-25 14:57:49 +0100169import com.android.org.conscrypt.TrustedCertificateStore;
Yi Jin6c6e9ca2018-03-20 16:53:35 -0700170import com.android.server.am.MemInfoDumpProto;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700171
Jesse Hall317fa5a2017-05-23 15:46:55 -0700172import dalvik.system.CloseGuard;
173import dalvik.system.VMDebug;
174import dalvik.system.VMRuntime;
175
Jeff Sharkeybc2ae002018-07-31 10:45:37 -0600176import libcore.io.ForwardingOs;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700177import libcore.io.IoUtils;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -0600178import libcore.io.Os;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700179import libcore.net.event.NetworkEventDispatcher;
180
181import org.apache.harmony.dalvik.ddmc.DdmVmInternal;
182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183import java.io.File;
184import java.io.FileDescriptor;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -0600185import java.io.FileNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700187import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188import java.io.PrintWriter;
189import java.lang.ref.WeakReference;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -0400190import java.lang.reflect.Method;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700191import java.net.InetAddress;
Jeff Sharkey416d4622019-02-27 22:14:16 -0700192import java.nio.file.Files;
Alex Lightc4caca12019-08-12 10:58:29 -0700193import java.nio.file.Path;
Narayan Kamathccb2a0862013-12-19 14:49:36 +0000194import java.text.DateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195import java.util.ArrayList;
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -0600196import java.util.Arrays;
Riddle Hsud3062cb2018-06-30 02:06:42 +0800197import java.util.Collections;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198import java.util.List;
Adam Lesinskib61e4052016-05-19 18:23:05 -0700199import java.util.Locale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200import java.util.Map;
Kenny Roote6585b32013-12-13 12:00:26 -0800201import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202import java.util.TimeZone;
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700203import java.util.concurrent.Executor;
Riddle Hsu50e34002019-04-12 20:42:05 +0800204import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700206final class RemoteServiceException extends AndroidRuntimeException {
207 public RemoteServiceException(String msg) {
208 super(msg);
209 }
210}
211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212/**
213 * This manages the execution of the main thread in an
214 * application process, scheduling and executing activities,
215 * broadcasts, and other operations on it as the activity
216 * manager requests.
217 *
218 * {@hide}
219 */
Andrii Kulian446e8242017-10-26 15:17:29 -0700220public final class ActivityThread extends ClientTransactionHandler {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700221 /** @hide */
222 public static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700223 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
Joe Onorato43a17652011-04-06 19:22:23 -0700224 static final boolean localLOGV = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700225 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborne829fef2010-10-26 17:44:01 -0700226 /** @hide */
227 public static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700228 private static final boolean DEBUG_RESULTS = false;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700229 private static final boolean DEBUG_BACKUP = false;
Craig Mautner88c05892013-06-28 09:47:45 -0700230 public static final boolean DEBUG_CONFIGURATION = false;
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800231 private static final boolean DEBUG_SERVICE = false;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800232 public static final boolean DEBUG_MEMORY_TRIM = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700233 private static final boolean DEBUG_PROVIDER = false;
Andrii Kulianb372da62018-01-18 10:46:24 -0800234 public static final boolean DEBUG_ORDER = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
Riddle Hsu4e8e3b02019-04-12 17:37:10 +0800236 /**
Riddle Hsu50e34002019-04-12 20:42:05 +0800237 * If the activity doesn't become idle in time, the timeout will ensure to apply the pending top
238 * process state.
239 */
240 private static final long PENDING_TOP_PROCESS_STATE_TIMEOUT = 1000;
241 /**
Riddle Hsu4e8e3b02019-04-12 17:37:10 +0800242 * The delay to release the provider when it has no more references. It reduces the number of
243 * transactions for acquiring and releasing provider if the client accesses the provider
244 * frequently in a short time.
245 */
246 private static final long CONTENT_PROVIDER_RETAIN_TIME = 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248
Dianne Hackborn455625e2015-01-21 09:55:13 -0800249 /** Type for IActivityManager.serviceDoneExecuting: anonymous operation */
250 public static final int SERVICE_DONE_EXECUTING_ANON = 0;
251 /** Type for IActivityManager.serviceDoneExecuting: done with an onStart call */
252 public static final int SERVICE_DONE_EXECUTING_START = 1;
253 /** Type for IActivityManager.serviceDoneExecuting: done stopping (destroying) service */
254 public static final int SERVICE_DONE_EXECUTING_STOP = 2;
255
Filip Gruszczynskica664812015-12-04 12:43:36 -0800256 // Whether to invoke an activity callback after delivering new configuration.
257 private static final boolean REPORT_TO_ACTIVITY = true;
258
Riddle Hsu50e34002019-04-12 20:42:05 +0800259 /** Use foreground GC policy (less pause time) and higher JIT weight. */
260 private static final int VM_PROCESS_STATE_JANK_PERCEPTIBLE = 0;
261 /** Use background GC policy and default JIT threshold. */
262 private static final int VM_PROCESS_STATE_JANK_IMPERCEPTIBLE = 1;
263
Sudheer Shanka84a48952017-03-08 18:19:01 -0800264 /**
265 * Denotes an invalid sequence number corresponding to a process state change.
266 */
267 public static final long INVALID_PROC_STATE_SEQ = -1;
268
Sudheer Shankaf6690102017-10-16 10:20:32 -0700269 /**
270 * Identifier for the sequence no. associated with this process start. It will be provided
271 * as one of the arguments when the process starts.
272 */
273 public static final String PROC_START_SEQ_IDENT = "seq=";
274
Sudheer Shanka84a48952017-03-08 18:19:01 -0800275 private final Object mNetworkPolicyLock = new Object();
276
277 /**
278 * Denotes the sequence number of the process state change for which the main thread needs
279 * to block until the network rules are updated for it.
280 *
281 * Value of {@link #INVALID_PROC_STATE_SEQ} indicates there is no need for blocking.
282 */
283 @GuardedBy("mNetworkPolicyLock")
284 private long mNetworkBlockSeq = INVALID_PROC_STATE_SEQ;
285
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100286 @UnsupportedAppUsage
Jeff Browndefd4a62014-03-10 21:24:37 -0700287 private ContextImpl mSystemContext;
Adam Lesinskia82b6262017-03-21 16:56:17 -0700288 private ContextImpl mSystemUiContext;
Bob Leee5408332009-09-04 18:31:17 -0700289
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100290 @UnsupportedAppUsage
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700291 static volatile IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100293 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700294 final ApplicationThread mAppThread = new ApplicationThread();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100295 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700296 final Looper mLooper = Looper.myLooper();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100297 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700298 final H mH = new H();
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700299 final Executor mExecutor = new HandlerExecutor(mH);
Garfield Tan0443b372019-01-04 15:00:13 -0800300 /**
301 * Maps from activity token to local record of running activities in this process.
302 *
303 * This variable is readable if the code is running in activity thread or holding {@link
304 * #mResourcesManager}. It's only writable if the code is running in activity thread and holding
305 * {@link #mResourcesManager}.
306 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100307 @UnsupportedAppUsage
Dianne Hackborn782d4982015-07-08 17:36:37 -0700308 final ArrayMap<IBinder, ActivityClientRecord> mActivities = new ArrayMap<>();
Riddle Hsu66b74a82018-07-26 00:20:12 +0800309 /** The activities to be truly destroyed (not include relaunch). */
Riddle Hsud3062cb2018-06-30 02:06:42 +0800310 final Map<IBinder, ClientTransactionItem> mActivitiesToBeDestroyed =
311 Collections.synchronizedMap(new ArrayMap<IBinder, ClientTransactionItem>());
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700312 // List of new activities (via ActivityRecord.nextIdle) that should
313 // be reported when next we idle.
314 ActivityClientRecord mNewActivities = null;
315 // Number of activities that are currently visible on-screen.
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100316 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700317 int mNumVisibleActivities = 0;
Riddle Hsu50e34002019-04-12 20:42:05 +0800318 private final AtomicInteger mNumLaunchingActivities = new AtomicInteger();
319 @GuardedBy("mAppThread")
320 private int mLastProcessState = PROCESS_STATE_UNKNOWN;
321 @GuardedBy("mAppThread")
322 private int mPendingProcessState = PROCESS_STATE_UNKNOWN;
Amith Yamasani4f128e42016-05-10 11:44:12 -0700323 ArrayList<WeakReference<AssistStructure>> mLastAssistStructures = new ArrayList<>();
324 private int mLastSessionId;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100325 @UnsupportedAppUsage
Dianne Hackborn782d4982015-07-08 17:36:37 -0700326 final ArrayMap<IBinder, Service> mServices = new ArrayMap<>();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100327 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700328 AppBindData mBoundApplication;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700329 Profiler mProfiler;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100330 @UnsupportedAppUsage
Dianne Hackborn908aecc2012-07-31 16:37:34 -0700331 int mCurDefaultDisplayDpi;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100332 @UnsupportedAppUsage
Dianne Hackborndde331c2012-08-03 14:01:57 -0700333 boolean mDensityCompatMode;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100334 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700335 Configuration mConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700336 Configuration mCompatConfiguration;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100337 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700338 Application mInitialApplication;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100339 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700340 final ArrayList<Application> mAllApplications
341 = new ArrayList<Application>();
Annie Mengd5827872019-01-30 20:28:57 +0000342 /**
343 * Bookkeeping of instantiated backup agents indexed first by user id, then by package name.
344 * Indexing by user id supports parallel backups across users on system packages as they run in
345 * the same process with the same package name. Indexing by package name supports multiple
346 * distinct applications running in the same process.
347 */
348 private final SparseArray<ArrayMap<String, BackupAgent>> mBackupAgentsByUser =
349 new SparseArray<>();
Jeff Sharkey66a017b2013-01-17 18:18:22 -0800350 /** Reference to singleton {@link ActivityThread} */
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100351 @UnsupportedAppUsage
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700352 private static volatile ActivityThread sCurrentActivityThread;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100353 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700354 Instrumentation mInstrumentation;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700355 String mInstrumentationPackageName = null;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100356 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700357 String mInstrumentationAppDir = null;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700358 String[] mInstrumentationSplitAppDirs = null;
359 String mInstrumentationLibDir = null;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100360 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700361 String mInstrumentedAppDir = null;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700362 String[] mInstrumentedSplitAppDirs = null;
363 String mInstrumentedLibDir = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700364 boolean mSystemThread = false;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700365 boolean mSomeActivitiesChanged = false;
Chong Zhang4951f9d2016-06-23 13:15:08 -0700366 boolean mUpdatingSystemConfig = false;
David Brazdild960cc42018-01-31 07:59:17 +0000367 /* package */ boolean mHiddenApiWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100369 // These can be accessed by multiple threads; mResourcesManager is the lock.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700370 // XXX For now we keep around information about all packages we have
371 // seen, not removing entries from this map.
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800372 // NOTE: The activity and window managers need to call in to
Dianne Hackborn2f0b1752011-05-31 17:59:49 -0700373 // ActivityThread to do things like update resource configurations,
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800374 // which means this lock gets held while the activity and window managers
375 // holds their own lock. Thus you MUST NEVER call back into the activity manager
376 // or window manager or anything that depends on them while holding this lock.
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700377 // These LoadedApk are only valid for the userId that we're running as.
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100378 @GuardedBy("mResourcesManager")
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100379 @UnsupportedAppUsage
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100380 final ArrayMap<String, WeakReference<LoadedApk>> mPackages = new ArrayMap<>();
381 @GuardedBy("mResourcesManager")
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100382 @UnsupportedAppUsage
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100383 final ArrayMap<String, WeakReference<LoadedApk>> mResourcePackages = new ArrayMap<>();
384 @GuardedBy("mResourcesManager")
385 final ArrayList<ActivityClientRecord> mRelaunchingActivities = new ArrayList<>();
386 @GuardedBy("mResourcesManager")
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100387 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700388 Configuration mPendingConfiguration = null;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800389 // An executor that performs multi-step transactions.
390 private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391
Mathew Inwood8c854f82018-09-14 12:35:36 +0100392 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Craig Mautner88c05892013-06-28 09:47:45 -0700393 private final ResourcesManager mResourcesManager;
394
Svet Ganov3b6be082019-04-28 10:21:01 -0700395 // Registry of remote cancellation transports pending a reply with reply handles.
396 @GuardedBy("this")
397 private @Nullable Map<SafeCancellationTransport, CancellationSignal> mRemoteCancellations;
398
Jeff Sharkey6d515712012-09-20 16:06:08 -0700399 private static final class ProviderKey {
400 final String authority;
401 final int userId;
402
403 public ProviderKey(String authority, int userId) {
404 this.authority = authority;
405 this.userId = userId;
406 }
407
408 @Override
409 public boolean equals(Object o) {
410 if (o instanceof ProviderKey) {
411 final ProviderKey other = (ProviderKey) o;
Kenny Roote6585b32013-12-13 12:00:26 -0800412 return Objects.equals(authority, other.authority) && userId == other.userId;
Jeff Sharkey6d515712012-09-20 16:06:08 -0700413 }
414 return false;
415 }
416
417 @Override
418 public int hashCode() {
419 return ((authority != null) ? authority.hashCode() : 0) ^ userId;
420 }
421 }
422
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700423 // The lock of mProviderMap protects the following variables.
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100424 @UnsupportedAppUsage
Wale Ogunwale1d646122015-04-24 14:45:14 -0700425 final ArrayMap<ProviderKey, ProviderClientRecord> mProviderMap
426 = new ArrayMap<ProviderKey, ProviderClientRecord>();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100427 @UnsupportedAppUsage
Wale Ogunwale1d646122015-04-24 14:45:14 -0700428 final ArrayMap<IBinder, ProviderRefCount> mProviderRefCountMap
429 = new ArrayMap<IBinder, ProviderRefCount>();
Mathew Inwood8c854f82018-09-14 12:35:36 +0100430 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Wale Ogunwale1d646122015-04-24 14:45:14 -0700431 final ArrayMap<IBinder, ProviderClientRecord> mLocalProviders
432 = new ArrayMap<IBinder, ProviderClientRecord>();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100433 @UnsupportedAppUsage
Wale Ogunwale1d646122015-04-24 14:45:14 -0700434 final ArrayMap<ComponentName, ProviderClientRecord> mLocalProvidersByName
435 = new ArrayMap<ComponentName, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436
Makoto Onukib6c79ea2018-05-31 11:03:56 -0700437 // Mitigation for b/74523247: Used to serialize calls to AM.getContentProvider().
438 // Note we never removes items from this map but that's okay because there are only so many
439 // users and so many authorities.
440 // TODO Remove it once we move CPR.wait() from AMS to the client side.
441 @GuardedBy("mGetProviderLocks")
442 final ArrayMap<ProviderKey, Object> mGetProviderLocks = new ArrayMap<>();
443
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700444 final ArrayMap<Activity, ArrayList<OnActivityPausedListener>> mOnPauseListeners
Wale Ogunwale1d646122015-04-24 14:45:14 -0700445 = new ArrayMap<Activity, ArrayList<OnActivityPausedListener>>();
Jeff Hamilton52d32032011-01-08 15:31:26 -0600446
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700447 final GcIdler mGcIdler = new GcIdler();
Tim Murray59f3dc12018-10-22 15:26:08 -0700448 final PurgeIdler mPurgeIdler = new PurgeIdler();
449
450 boolean mPurgeIdlerScheduled = false;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700451 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452
Mathew Inwood8c854f82018-09-14 12:35:36 +0100453 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700454 static volatile Handler sMainThreadHandler; // set once in main()
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700455
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800456 Bundle mCoreSettings = null;
457
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800458 /** Activity client record, used for bookkeeping for the real {@link Activity} instance. */
459 public static final class ActivityClientRecord {
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100460 @UnsupportedAppUsage
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800461 public IBinder token;
Sunny Goyald40c3452019-03-20 12:46:55 -0700462 public IBinder assistToken;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700463 int ident;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100464 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465 Intent intent;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800466 String referrer;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700467 IVoiceInteractor voiceInteractor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 Bundle state;
Craig Mautnera0026042014-04-23 11:45:37 -0700469 PersistableBundle persistentState;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100470 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 Activity activity;
472 Window window;
473 Activity parent;
474 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700475 Activity.NonConfigurationInstances lastNonConfigurationInstances;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800476 // TODO(lifecycler): Use mLifecycleState instead.
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100477 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 boolean paused;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100479 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 boolean stopped;
481 boolean hideForNow;
482 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700483 Configuration createdConfig;
Wale Ogunwale60454db2015-01-23 16:05:07 -0800484 Configuration overrideConfig;
Garfield Tan0443b372019-01-04 15:00:13 -0800485 // Used to save the last reported configuration from server side so that activity
486 // configuration transactions can always use the latest configuration.
487 @GuardedBy("this")
488 private Configuration mPendingOverrideConfig;
Wale Ogunwalec2607b42015-02-07 16:16:59 -0800489 // Used for consolidating configs before sending on to Activity.
490 private Configuration tmpConfig = new Configuration();
Andrii Kulian44607962017-03-16 11:06:24 -0700491 // Callback used for updating activity override config.
492 ViewRootImpl.ActivityConfigCallback configCallback;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700493 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494
Andrii Kuliand70cdb92019-01-08 15:03:50 -0800495 // Indicates whether this activity is currently the topmost resumed one in the system.
496 // This holds the last reported value from server.
497 boolean isTopResumedActivity;
498 // This holds the value last sent to the activity. This is needed, because an update from
499 // server may come at random time, but we always need to report changes between ON_RESUME
500 // and ON_PAUSE to the app.
501 boolean lastReportedTopResumedState;
502
Jeff Hao1b012d32014-08-20 10:35:34 -0700503 ProfilerInfo profilerInfo;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700504
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100505 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 ActivityInfo activityInfo;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100507 @UnsupportedAppUsage
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400508 CompatibilityInfo compatInfo;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100509 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +0000510 public LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511
512 List<ResultInfo> pendingResults;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800513 List<ReferrerIntent> pendingIntents;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514
515 boolean startsNotResumed;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800516 public final boolean isForward;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800517 int pendingConfigChanges;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800518
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700519 Window mPendingRemoveWindow;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800520 WindowManager mPendingRemoveWindowManager;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100521 @UnsupportedAppUsage
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700522 boolean mPreserveWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800524 @LifecycleState
525 private int mLifecycleState = PRE_ON_CREATE;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700526
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800527 @VisibleForTesting
Mathew Inwood8c854f82018-09-14 12:35:36 +0100528 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800529 public ActivityClientRecord() {
530 this.isForward = false;
531 init();
532 }
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700533
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800534 public ActivityClientRecord(IBinder token, Intent intent, int ident,
535 ActivityInfo info, Configuration overrideConfig, CompatibilityInfo compatInfo,
536 String referrer, IVoiceInteractor voiceInteractor, Bundle state,
537 PersistableBundle persistentState, List<ResultInfo> pendingResults,
538 List<ReferrerIntent> pendingNewIntents, boolean isForward,
Sunny Goyald40c3452019-03-20 12:46:55 -0700539 ProfilerInfo profilerInfo, ClientTransactionHandler client,
540 IBinder assistToken) {
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800541 this.token = token;
Sunny Goyald40c3452019-03-20 12:46:55 -0700542 this.assistToken = assistToken;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800543 this.ident = ident;
544 this.intent = intent;
545 this.referrer = referrer;
546 this.voiceInteractor = voiceInteractor;
547 this.activityInfo = info;
548 this.compatInfo = compatInfo;
549 this.state = state;
550 this.persistentState = persistentState;
551 this.pendingResults = pendingResults;
552 this.pendingIntents = pendingNewIntents;
553 this.isForward = isForward;
554 this.profilerInfo = profilerInfo;
555 this.overrideConfig = overrideConfig;
Todd Kennedy233a0b12018-01-29 20:30:24 +0000556 this.packageInfo = client.getPackageInfoNoCheck(activityInfo.applicationInfo,
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800557 compatInfo);
558 init();
559 }
560
561 /** Common initializer for all constructors. */
562 private void init() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 parent = null;
564 embeddedID = null;
565 paused = false;
566 stopped = false;
567 hideForNow = false;
568 nextIdle = null;
Andrii Kulian44607962017-03-16 11:06:24 -0700569 configCallback = (Configuration overrideConfig, int newDisplayId) -> {
570 if (activity == null) {
571 throw new IllegalStateException(
572 "Received config update for non-existing activity");
573 }
Andrii Kulian446e8242017-10-26 15:17:29 -0700574 activity.mMainThread.handleActivityConfigurationChanged(token, overrideConfig,
575 newDisplayId);
Andrii Kulian44607962017-03-16 11:06:24 -0700576 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 }
578
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800579 /** Get the current lifecycle state. */
580 public int getLifecycleState() {
581 return mLifecycleState;
582 }
583
584 /** Update the current lifecycle state for internal bookkeeping. */
585 public void setState(@LifecycleState int newLifecycleState) {
586 mLifecycleState = newLifecycleState;
587 switch (mLifecycleState) {
588 case ON_CREATE:
589 paused = true;
590 stopped = true;
591 break;
592 case ON_START:
593 paused = true;
594 stopped = false;
595 break;
596 case ON_RESUME:
597 paused = false;
598 stopped = false;
599 break;
600 case ON_PAUSE:
601 paused = true;
602 stopped = false;
603 break;
604 case ON_STOP:
605 paused = true;
606 stopped = true;
607 break;
608 }
609 }
610
Andrii Kulian391161f2018-01-29 10:50:02 -0800611 private boolean isPreHoneycomb() {
612 return activity != null && activity.getApplicationInfo().targetSdkVersion
613 < android.os.Build.VERSION_CODES.HONEYCOMB;
614 }
615
616 private boolean isPreP() {
617 return activity != null && activity.getApplicationInfo().targetSdkVersion
618 < android.os.Build.VERSION_CODES.P;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800619 }
620
Craig Mautnera0026042014-04-23 11:45:37 -0700621 public boolean isPersistable() {
Craig Mautner43e52ed2014-06-16 17:18:52 -0700622 return activityInfo.persistableMode == ActivityInfo.PERSIST_ACROSS_REBOOTS;
Craig Mautnera0026042014-04-23 11:45:37 -0700623 }
624
Andrii Kulian914aa7d2018-03-19 21:51:53 -0700625 public boolean isVisibleFromServer() {
626 return activity != null && activity.mVisibleFromServer;
627 }
628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 public String toString() {
Dianne Hackbornb61a0262012-05-14 17:19:18 -0700630 ComponentName componentName = intent != null ? intent.getComponent() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 return "ActivityRecord{"
632 + Integer.toHexString(System.identityHashCode(this))
633 + " token=" + token + " " + (componentName == null
634 ? "no component name" : componentName.toShortString())
635 + "}";
636 }
Andrii Kulian58178f22016-03-16 13:44:56 -0700637
638 public String getStateString() {
639 StringBuilder sb = new StringBuilder();
640 sb.append("ActivityClientRecord{");
641 sb.append("paused=").append(paused);
642 sb.append(", stopped=").append(stopped);
643 sb.append(", hideForNow=").append(hideForNow);
644 sb.append(", startsNotResumed=").append(startsNotResumed);
645 sb.append(", isForward=").append(isForward);
646 sb.append(", pendingConfigChanges=").append(pendingConfigChanges);
Andrii Kulian58178f22016-03-16 13:44:56 -0700647 sb.append(", preserveWindow=").append(mPreserveWindow);
648 if (activity != null) {
649 sb.append(", Activity{");
650 sb.append("resumed=").append(activity.mResumed);
651 sb.append(", stopped=").append(activity.mStopped);
652 sb.append(", finished=").append(activity.isFinishing());
653 sb.append(", destroyed=").append(activity.isDestroyed());
654 sb.append(", startedActivity=").append(activity.mStartedActivity);
Andrii Kulian58178f22016-03-16 13:44:56 -0700655 sb.append(", changingConfigurations=").append(activity.mChangingConfigurations);
Andrii Kulian58178f22016-03-16 13:44:56 -0700656 sb.append("}");
657 }
658 sb.append("}");
659 return sb.toString();
660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 }
662
Wale Ogunwale1d646122015-04-24 14:45:14 -0700663 final class ProviderClientRecord {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700664 final String[] mNames;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100665 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 final IContentProvider mProvider;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100667 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 final ContentProvider mLocalProvider;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100669 @UnsupportedAppUsage
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700670 final ContentProviderHolder mHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700672 ProviderClientRecord(String[] names, IContentProvider provider,
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700673 ContentProvider localProvider, ContentProviderHolder holder) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700674 mNames = names;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 mProvider = provider;
676 mLocalProvider = localProvider;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700677 mHolder = holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 }
679 }
680
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400681 static final class ReceiverData extends BroadcastReceiver.PendingResult {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700682 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700683 boolean ordered, boolean sticky, IBinder token, int sendingUser) {
684 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky,
riddle_hsu1f5ac4d2015-01-03 15:38:21 +0800685 token, sendingUser, intent.getFlags());
Dianne Hackborne829fef2010-10-26 17:44:01 -0700686 this.intent = intent;
687 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700688
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100689 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 Intent intent;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100691 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 ActivityInfo info;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100693 @UnsupportedAppUsage
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400694 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 public String toString() {
696 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700697 info.packageName + " resultCode=" + getResultCode()
698 + " resultData=" + getResultData() + " resultExtras="
699 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 }
701 }
702
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400703 static final class CreateBackupAgentData {
Christopher Tate181fafa2009-05-14 11:12:14 -0700704 ApplicationInfo appInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400705 CompatibilityInfo compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700706 int backupMode;
Ruslan Tkhakokhov063180f2019-01-28 20:29:46 +0000707 int userId;
Christopher Tate181fafa2009-05-14 11:12:14 -0700708 public String toString() {
709 return "CreateBackupAgentData{appInfo=" + appInfo
710 + " backupAgent=" + appInfo.backupAgentName
Ruslan Tkhakokhov063180f2019-01-28 20:29:46 +0000711 + " mode=" + backupMode + " userId=" + userId + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700712 }
713 }
Bob Leee5408332009-09-04 18:31:17 -0700714
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400715 static final class CreateServiceData {
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100716 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 IBinder token;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100718 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 ServiceInfo info;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100720 @UnsupportedAppUsage
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400721 CompatibilityInfo compatInfo;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100722 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 Intent intent;
724 public String toString() {
725 return "CreateServiceData{token=" + token + " className="
726 + info.name + " packageName=" + info.packageName
727 + " intent=" + intent + "}";
728 }
729 }
730
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400731 static final class BindServiceData {
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100732 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 IBinder token;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100734 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 Intent intent;
736 boolean rebind;
737 public String toString() {
738 return "BindServiceData{token=" + token + " intent=" + intent + "}";
739 }
740 }
741
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400742 static final class ServiceArgsData {
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100743 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 IBinder token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700745 boolean taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700747 int flags;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100748 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 Intent args;
750 public String toString() {
751 return "ServiceArgsData{token=" + token + " startId=" + startId
752 + " args=" + args + "}";
753 }
754 }
755
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400756 static final class AppBindData {
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100757 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +0000758 LoadedApk info;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100759 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 String processName;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100761 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 ApplicationInfo appInfo;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100763 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 List<ProviderInfo> providers;
765 ComponentName instrumentationName;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100766 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 Bundle instrumentationArgs;
768 IInstrumentationWatcher instrumentationWatcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800769 IUiAutomationConnection instrumentationUiAutomationConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 int debugMode;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400771 boolean enableBinderTracking;
Man Caocfa78b22015-06-11 20:14:34 -0700772 boolean trackAllocation;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100773 @UnsupportedAppUsage
Christopher Tate181fafa2009-05-14 11:12:14 -0700774 boolean restrictedBackupMode;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100775 @UnsupportedAppUsage
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700776 boolean persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 Configuration config;
Mathew Inwood8c854f82018-09-14 12:35:36 +0100778 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400779 CompatibilityInfo compatInfo;
Svet Ganov37e43272016-09-09 16:01:32 -0700780 String buildSerial;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700781
782 /** Initial values for {@link Profiler}. */
Jeff Hao1b012d32014-08-20 10:35:34 -0700783 ProfilerInfo initProfilerInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700784
Felipe Lemea4f39cd2019-02-19 15:08:59 -0800785 AutofillOptions autofillOptions;
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800786
Felipe Leme326f15a2019-02-19 09:42:24 -0800787 /**
788 * Content capture options for the application - when null, it means ContentCapture is not
789 * enabled for the package.
790 */
791 @Nullable
792 ContentCaptureOptions contentCaptureOptions;
793
Mathew Inwooda1b39022019-06-24 12:07:22 +0100794 long[] disabledCompatChanges;
795
Felipe Leme326f15a2019-02-19 09:42:24 -0800796 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 public String toString() {
798 return "AppBindData{appInfo=" + appInfo + "}";
799 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700800 }
801
802 static final class Profiler {
803 String profileFile;
804 ParcelFileDescriptor profileFd;
Jeff Hao1b012d32014-08-20 10:35:34 -0700805 int samplingInterval;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700806 boolean autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800807 boolean streamingOutput;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700808 boolean profiling;
809 boolean handlingProfiling;
Jeff Hao1b012d32014-08-20 10:35:34 -0700810 public void setProfiler(ProfilerInfo profilerInfo) {
811 ParcelFileDescriptor fd = profilerInfo.profileFd;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700812 if (profiling) {
813 if (fd != null) {
814 try {
815 fd.close();
816 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700817 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700818 }
819 }
820 return;
821 }
822 if (profileFd != null) {
823 try {
824 profileFd.close();
825 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700826 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700827 }
828 }
Jeff Hao1b012d32014-08-20 10:35:34 -0700829 profileFile = profilerInfo.profileFile;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700830 profileFd = fd;
Jeff Hao1b012d32014-08-20 10:35:34 -0700831 samplingInterval = profilerInfo.samplingInterval;
832 autoStopProfiler = profilerInfo.autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800833 streamingOutput = profilerInfo.streamingOutput;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700834 }
835 public void startProfiling() {
836 if (profileFd == null || profiling) {
837 return;
838 }
839 try {
Andreas Gampeeff06392016-05-10 12:51:45 -0700840 int bufferSize = SystemProperties.getInt("debug.traceview-buffer-size-mb", 8);
Jeff Hao1b012d32014-08-20 10:35:34 -0700841 VMDebug.startMethodTracing(profileFile, profileFd.getFileDescriptor(),
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800842 bufferSize * 1024 * 1024, 0, samplingInterval != 0, samplingInterval,
843 streamingOutput);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700844 profiling = true;
845 } catch (RuntimeException e) {
Andreas Gampe4f689242018-03-14 23:13:28 -0700846 Slog.w(TAG, "Profiling failed on path " + profileFile, e);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700847 try {
848 profileFd.close();
849 profileFd = null;
850 } catch (IOException e2) {
851 Slog.w(TAG, "Failure closing profile fd", e2);
852 }
853 }
854 }
855 public void stopProfiling() {
856 if (profiling) {
857 profiling = false;
858 Debug.stopMethodTracing();
859 if (profileFd != null) {
860 try {
861 profileFd.close();
862 } catch (IOException e) {
863 }
864 }
865 profileFd = null;
866 profileFile = null;
867 }
868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 }
870
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400871 static final class DumpComponentInfo {
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700872 ParcelFileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700873 IBinder token;
Dianne Hackborn30d71892010-12-11 10:37:55 -0800874 String prefix;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 String[] args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 }
877
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400878 static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800879 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 String what;
881 String who;
882 }
883
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400884 static final class DumpHeapData {
Kweku Adams4af1b502019-05-23 16:23:48 -0700885 // Whether to dump the native or managed heap.
Christopher Ferris8d652f82017-04-11 16:29:18 -0700886 public boolean managed;
887 public boolean mallocInfo;
Makoto Onuki4556b7b2017-07-07 14:58:58 -0700888 public boolean runGc;
Andy McFadden824c5102010-07-09 16:26:57 -0700889 String path;
890 ParcelFileDescriptor fd;
Makoto Onuki2c6657f2018-06-06 15:24:02 -0700891 RemoteCallback finishCallback;
Andy McFadden824c5102010-07-09 16:26:57 -0700892 }
893
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400894 static final class UpdateCompatibilityData {
895 String pkg;
896 CompatibilityInfo info;
897 }
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800898
Adam Skorydfc7fd72013-08-05 19:23:41 -0700899 static final class RequestAssistContextExtras {
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800900 IBinder activityToken;
901 IBinder requestToken;
902 int requestType;
Amith Yamasani4f128e42016-05-10 11:44:12 -0700903 int sessionId;
Svet Ganovfd31f852017-04-26 15:54:27 -0700904 int flags;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800905 }
Anwar Ghuloum3a8ce1b2013-04-26 16:18:28 -0700906
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700907 private class ApplicationThread extends IApplicationThread.Stub {
Vasu Nori3c7131f2010-09-21 14:36:57 -0700908 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700909
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800910 public final void scheduleSleeping(IBinder token, boolean sleeping) {
Jeff Brown9ef09972013-10-15 20:49:59 -0700911 sendMessage(H.SLEEPING, token, sleeping ? 1 : 0);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800912 }
913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 public final void scheduleReceiver(Intent intent, ActivityInfo info,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400915 CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700916 boolean sync, int sendingUser, int processState) {
917 updateProcessState(processState, false);
Dianne Hackborne829fef2010-10-26 17:44:01 -0700918 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700919 sync, false, mAppThread.asBinder(), sendingUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 r.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400921 r.compatInfo = compatInfo;
Jeff Brown9ef09972013-10-15 20:49:59 -0700922 sendMessage(H.RECEIVER, r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 }
924
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400925 public final void scheduleCreateBackupAgent(ApplicationInfo app,
Ruslan Tkhakokhov063180f2019-01-28 20:29:46 +0000926 CompatibilityInfo compatInfo, int backupMode, int userId) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700927 CreateBackupAgentData d = new CreateBackupAgentData();
928 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400929 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700930 d.backupMode = backupMode;
Ruslan Tkhakokhov063180f2019-01-28 20:29:46 +0000931 d.userId = userId;
Christopher Tate181fafa2009-05-14 11:12:14 -0700932
Jeff Brown9ef09972013-10-15 20:49:59 -0700933 sendMessage(H.CREATE_BACKUP_AGENT, d);
Christopher Tate181fafa2009-05-14 11:12:14 -0700934 }
935
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400936 public final void scheduleDestroyBackupAgent(ApplicationInfo app,
Annie Mengd5827872019-01-30 20:28:57 +0000937 CompatibilityInfo compatInfo, int userId) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700938 CreateBackupAgentData d = new CreateBackupAgentData();
939 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400940 d.compatInfo = compatInfo;
Annie Mengd5827872019-01-30 20:28:57 +0000941 d.userId = userId;
Christopher Tate181fafa2009-05-14 11:12:14 -0700942
Jeff Brown9ef09972013-10-15 20:49:59 -0700943 sendMessage(H.DESTROY_BACKUP_AGENT, d);
Christopher Tate181fafa2009-05-14 11:12:14 -0700944 }
945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 public final void scheduleCreateService(IBinder token,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700947 ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
948 updateProcessState(processState, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 CreateServiceData s = new CreateServiceData();
950 s.token = token;
951 s.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400952 s.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953
Jeff Brown9ef09972013-10-15 20:49:59 -0700954 sendMessage(H.CREATE_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 }
956
957 public final void scheduleBindService(IBinder token, Intent intent,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700958 boolean rebind, int processState) {
959 updateProcessState(processState, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 BindServiceData s = new BindServiceData();
961 s.token = token;
962 s.intent = intent;
963 s.rebind = rebind;
964
Amith Yamasani742a6712011-05-04 14:49:28 -0700965 if (DEBUG_SERVICE)
966 Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
967 + Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
Jeff Brown9ef09972013-10-15 20:49:59 -0700968 sendMessage(H.BIND_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 }
970
971 public final void scheduleUnbindService(IBinder token, Intent intent) {
972 BindServiceData s = new BindServiceData();
973 s.token = token;
974 s.intent = intent;
975
Jeff Brown9ef09972013-10-15 20:49:59 -0700976 sendMessage(H.UNBIND_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 }
978
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -0700979 public final void scheduleServiceArgs(IBinder token, ParceledListSlice args) {
980 List<ServiceStartArgs> list = args.getList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -0700982 for (int i = 0; i < list.size(); i++) {
983 ServiceStartArgs ssa = list.get(i);
984 ServiceArgsData s = new ServiceArgsData();
985 s.token = token;
986 s.taskRemoved = ssa.taskRemoved;
987 s.startId = ssa.startId;
988 s.flags = ssa.flags;
989 s.args = ssa.args;
990
991 sendMessage(H.SERVICE_ARGS, s);
992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 }
994
995 public final void scheduleStopService(IBinder token) {
Jeff Brown9ef09972013-10-15 20:49:59 -0700996 sendMessage(H.STOP_SERVICE, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 }
998
Jeff Hao1b012d32014-08-20 10:35:34 -0700999 public final void bindApplication(String processName, ApplicationInfo appInfo,
1000 List<ProviderInfo> providers, ComponentName instrumentationName,
1001 ProfilerInfo profilerInfo, Bundle instrumentationArgs,
1002 IInstrumentationWatcher instrumentationWatcher,
Svetoslav Ganov80943d82013-01-02 10:25:37 -08001003 IUiAutomationConnection instrumentationUiConnection, int debugMode,
Pablo Ceballosa4d4e822015-10-05 10:27:52 -07001004 boolean enableBinderTracking, boolean trackAllocation,
1005 boolean isRestrictedBackupMode, boolean persistent, Configuration config,
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001006 CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
Felipe Lemea4f39cd2019-02-19 15:08:59 -08001007 String buildSerial, AutofillOptions autofillOptions,
Mathew Inwood3020e052019-07-22 09:40:58 +01001008 ContentCaptureOptions contentCaptureOptions,
Mathew Inwooda1b39022019-06-24 12:07:22 +01001009 long[] disabledCompatChanges) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 if (services != null) {
Makoto Onuki45895652018-05-07 14:43:05 -07001011 if (false) {
1012 // Test code to make sure the app could see the passed-in services.
1013 for (Object oname : services.keySet()) {
1014 if (services.get(oname) == null) {
1015 continue; // AM just passed in a null service.
1016 }
1017 String name = (String) oname;
1018
1019 // See b/79378449 about the following exemption.
1020 switch (name) {
1021 case "package":
1022 case Context.WINDOW_SERVICE:
1023 continue;
1024 }
1025
1026 if (ServiceManager.getService(name) == null) {
1027 Log.wtf(TAG, "Service " + name + " should be accessible by this app");
1028 }
1029 }
1030 }
1031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 // Setup the service cache in the ServiceManager
1033 ServiceManager.initServiceCache(services);
1034 }
1035
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08001036 setCoreSettings(coreSettings);
1037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 AppBindData data = new AppBindData();
1039 data.processName = processName;
1040 data.appInfo = appInfo;
1041 data.providers = providers;
1042 data.instrumentationName = instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 data.instrumentationArgs = instrumentationArgs;
1044 data.instrumentationWatcher = instrumentationWatcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -08001045 data.instrumentationUiAutomationConnection = instrumentationUiConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 data.debugMode = debugMode;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001047 data.enableBinderTracking = enableBinderTracking;
Man Caocfa78b22015-06-11 20:14:34 -07001048 data.trackAllocation = trackAllocation;
Christopher Tate181fafa2009-05-14 11:12:14 -07001049 data.restrictedBackupMode = isRestrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -07001050 data.persistent = persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 data.config = config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001052 data.compatInfo = compatInfo;
Jeff Hao1b012d32014-08-20 10:35:34 -07001053 data.initProfilerInfo = profilerInfo;
Svet Ganov37e43272016-09-09 16:01:32 -07001054 data.buildSerial = buildSerial;
Mathew Inwooda1b39022019-06-24 12:07:22 +01001055 data.disabledCompatChanges = disabledCompatChanges;
Jeff Brown9ef09972013-10-15 20:49:59 -07001056 sendMessage(H.BIND_APPLICATION, data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 }
1058
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001059 public final void runIsolatedEntryPoint(String entryPoint, String[] entryPointArgs) {
1060 SomeArgs args = SomeArgs.obtain();
1061 args.arg1 = entryPoint;
1062 args.arg2 = entryPointArgs;
1063 sendMessage(H.RUN_ISOLATED_ENTRY_POINT, args);
1064 }
1065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 public final void scheduleExit() {
Jeff Brown9ef09972013-10-15 20:49:59 -07001067 sendMessage(H.EXIT_APPLICATION, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 }
1069
Christopher Tate5e1ab332009-09-01 20:32:49 -07001070 public final void scheduleSuicide() {
Jeff Brown9ef09972013-10-15 20:49:59 -07001071 sendMessage(H.SUICIDE, null);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001072 }
1073
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001074 public void scheduleApplicationInfoChanged(ApplicationInfo ai) {
Winson Chung6ee17422019-05-07 13:22:15 -07001075 mH.removeMessages(H.APPLICATION_INFO_CHANGED, ai);
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001076 sendMessage(H.APPLICATION_INFO_CHANGED, ai);
1077 }
1078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 public void updateTimeZone() {
1080 TimeZone.setDefault(null);
1081 }
1082
Robert Greenwalt03595d02010-11-02 14:08:23 -07001083 public void clearDnsCache() {
1084 // a non-standard API to get this to libcore
1085 InetAddress.clearDnsCache();
Paul Jensene401d172014-09-12 10:47:39 -04001086 // Allow libcore to perform the necessary actions as it sees fit upon a network
1087 // configuration change.
1088 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Robert Greenwalt03595d02010-11-02 14:08:23 -07001089 }
1090
Irina Dumitrescu18622d32018-12-05 16:19:47 +00001091 public void updateHttpProxy() {
Irina Dumitrescu34a27c42019-04-15 19:20:38 +01001092 ActivityThread.updateHttpProxy(
Chalard Jean100df0a2018-05-15 23:11:45 +09001093 getApplication() != null ? getApplication() : getSystemContext());
Robert Greenwalt434203a2010-10-11 16:00:27 -07001094 }
1095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 public void processInBackground() {
1097 mH.removeMessages(H.GC_WHEN_IDLE);
1098 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
1099 }
1100
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001101 public void dumpService(ParcelFileDescriptor pfd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07001102 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001103 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001104 data.fd = pfd.dup();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001105 data.token = servicetoken;
1106 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001107 sendMessage(H.DUMP_SERVICE, data, 0, 0, true /*async*/);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001108 } catch (IOException e) {
1109 Slog.w(TAG, "dumpService failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001110 } finally {
1111 IoUtils.closeQuietly(pfd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 }
1113 }
1114
1115 // This function exists to make sure all receiver dispatching is
1116 // correctly ordered, since these are one-way calls and the binder driver
1117 // applies transaction ordering per object for such calls.
1118 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07001119 int resultCode, String dataStr, Bundle extras, boolean ordered,
Dianne Hackborna413dc02013-07-12 12:02:55 -07001120 boolean sticky, int sendingUser, int processState) throws RemoteException {
1121 updateProcessState(processState, false);
Dianne Hackborn20e80982012-08-31 19:00:44 -07001122 receiver.performReceive(intent, resultCode, dataStr, extras, ordered,
1123 sticky, sendingUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 }
Bob Leee5408332009-09-04 18:31:17 -07001125
Wale Ogunwalec2607b42015-02-07 16:16:59 -08001126 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 public void scheduleLowMemory() {
Jeff Brown9ef09972013-10-15 20:49:59 -07001128 sendMessage(H.LOW_MEMORY, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 }
1130
Wale Ogunwale60454db2015-01-23 16:05:07 -08001131 @Override
Jeff Hao1b012d32014-08-20 10:35:34 -07001132 public void profilerControl(boolean start, ProfilerInfo profilerInfo, int profileType) {
1133 sendMessage(H.PROFILER_CONTROL, profilerInfo, start ? 1 : 0, profileType);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001134 }
1135
Makoto Onuki4556b7b2017-07-07 14:58:58 -07001136 @Override
Christopher Ferris8d652f82017-04-11 16:29:18 -07001137 public void dumpHeap(boolean managed, boolean mallocInfo, boolean runGc, String path,
Makoto Onuki2c6657f2018-06-06 15:24:02 -07001138 ParcelFileDescriptor fd, RemoteCallback finishCallback) {
Andy McFadden824c5102010-07-09 16:26:57 -07001139 DumpHeapData dhd = new DumpHeapData();
Christopher Ferris8d652f82017-04-11 16:29:18 -07001140 dhd.managed = managed;
1141 dhd.mallocInfo = mallocInfo;
Makoto Onuki4556b7b2017-07-07 14:58:58 -07001142 dhd.runGc = runGc;
Andy McFadden824c5102010-07-09 16:26:57 -07001143 dhd.path = path;
Kweku Adams4af1b502019-05-23 16:23:48 -07001144 try {
1145 // Since we're going to dump the heap asynchronously, dup the file descriptor before
1146 // it's closed on returning from the IPC call.
1147 dhd.fd = fd.dup();
1148 } catch (IOException e) {
1149 Slog.e(TAG, "Failed to duplicate heap dump file descriptor", e);
1150 return;
1151 }
Makoto Onuki2c6657f2018-06-06 15:24:02 -07001152 dhd.finishCallback = finishCallback;
Christopher Ferris8d652f82017-04-11 16:29:18 -07001153 sendMessage(H.DUMP_HEAP, dhd, 0, 0, true /*async*/);
Andy McFadden824c5102010-07-09 16:26:57 -07001154 }
1155
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001156 public void attachAgent(String agent) {
1157 sendMessage(H.ATTACH_AGENT, agent);
1158 }
1159
Alex Light2d0691c2019-10-03 14:36:57 -07001160 public void attachStartupAgents(String dataDir) {
1161 sendMessage(H.ATTACH_STARTUP_AGENTS, dataDir);
1162 }
1163
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001164 public void setSchedulingGroup(int group) {
1165 // Note: do this immediately, since going into the foreground
1166 // should happen regardless of what pending work we have to do
1167 // and the activity manager will wait for us to report back that
1168 // we are done before sending us to the background.
1169 try {
1170 Process.setProcessGroup(Process.myPid(), group);
1171 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001172 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001173 }
1174 }
Bob Leee5408332009-09-04 18:31:17 -07001175
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001176 public void dispatchPackageBroadcast(int cmd, String[] packages) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001177 sendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001178 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001179
1180 public void scheduleCrash(String msg) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001181 sendMessage(H.SCHEDULE_CRASH, msg);
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001182 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07001183
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001184 public void dumpActivity(ParcelFileDescriptor pfd, IBinder activitytoken,
Dianne Hackborn30d71892010-12-11 10:37:55 -08001185 String prefix, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07001186 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001187 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001188 data.fd = pfd.dup();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001189 data.token = activitytoken;
1190 data.prefix = prefix;
1191 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001192 sendMessage(H.DUMP_ACTIVITY, data, 0, 0, true /*async*/);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001193 } catch (IOException e) {
1194 Slog.w(TAG, "dumpActivity failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001195 } finally {
1196 IoUtils.closeQuietly(pfd);
Dianne Hackborn625ac272010-09-17 18:29:22 -07001197 }
1198 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07001199
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001200 public void dumpProvider(ParcelFileDescriptor pfd, IBinder providertoken,
Marco Nelissen18cb2872011-11-15 11:19:53 -08001201 String[] args) {
1202 DumpComponentInfo data = new DumpComponentInfo();
1203 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001204 data.fd = pfd.dup();
Marco Nelissen18cb2872011-11-15 11:19:53 -08001205 data.token = providertoken;
1206 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001207 sendMessage(H.DUMP_PROVIDER, data, 0, 0, true /*async*/);
Marco Nelissen18cb2872011-11-15 11:19:53 -08001208 } catch (IOException e) {
1209 Slog.w(TAG, "dumpProvider failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001210 } finally {
1211 IoUtils.closeQuietly(pfd);
Marco Nelissen18cb2872011-11-15 11:19:53 -08001212 }
1213 }
1214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001216 public void dumpMemInfo(ParcelFileDescriptor pfd, Debug.MemoryInfo mem, boolean checkin,
Colin Crossc4fb5f92016-02-02 16:51:15 -08001217 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
1218 boolean dumpUnreachable, String[] args) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001219 FileOutputStream fout = new FileOutputStream(pfd.getFileDescriptor());
Dianne Hackborn8c841092013-06-24 13:46:13 -07001220 PrintWriter pw = new FastPrintWriter(fout);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001221 try {
Colin Crossc4fb5f92016-02-02 16:51:15 -08001222 dumpMemInfo(pw, mem, checkin, dumpFullInfo, dumpDalvik, dumpSummaryOnly, dumpUnreachable);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001223 } finally {
Chet Haase9c1e23b2011-03-24 10:51:31 -07001224 pw.flush();
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001225 IoUtils.closeQuietly(pfd);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001226 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001227 }
1228
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001229 private void dumpMemInfo(PrintWriter pw, Debug.MemoryInfo memInfo, boolean checkin,
Colin Crossc4fb5f92016-02-02 16:51:15 -08001230 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly, boolean dumpUnreachable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 long nativeMax = Debug.getNativeHeapSize() / 1024;
1232 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1233 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 Runtime runtime = Runtime.getRuntime();
Mathieu Chartierd288a262015-07-10 13:44:42 -07001236 runtime.gc(); // Do GC since countInstancesOfClass counts unreachable objects.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 long dalvikMax = runtime.totalMemory() / 1024;
1238 long dalvikFree = runtime.freeMemory() / 1024;
1239 long dalvikAllocated = dalvikMax - dalvikFree;
Richard Uhler2c036192016-09-14 09:48:31 +01001240
1241 Class[] classesToCount = new Class[] {
1242 ContextImpl.class,
1243 Activity.class,
1244 WebView.class,
1245 OpenSSLSocketImpl.class
1246 };
1247 long[] instanceCounts = VMDebug.countInstancesOfClasses(classesToCount, true);
1248 long appContextInstanceCount = instanceCounts[0];
1249 long activityInstanceCount = instanceCounts[1];
1250 long webviewInstanceCount = instanceCounts[2];
1251 long openSslSocketCount = instanceCounts[3];
1252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 long viewInstanceCount = ViewDebug.getViewInstanceCount();
Romain Guy65b345f2011-07-27 18:51:50 -07001254 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 int globalAssetCount = AssetManager.getGlobalAssetCount();
1256 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1257 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1258 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1259 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Dianne Hackbornfabb70b2014-11-11 12:22:36 -08001260 long parcelSize = Parcel.getGlobalAllocSize();
1261 long parcelCount = Parcel.getGlobalAllocCount();
Vasu Noric3849202010-03-09 10:47:25 -08001262 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -07001263
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07001264 dumpMemInfoTable(pw, memInfo, checkin, dumpFullInfo, dumpDalvik, dumpSummaryOnly,
1265 Process.myPid(),
Dianne Hackborne77187d2013-10-25 16:32:41 -07001266 (mBoundApplication != null) ? mBoundApplication.processName : "unknown",
1267 nativeMax, nativeAllocated, nativeFree,
1268 dalvikMax, dalvikAllocated, dalvikFree);
1269
Dianne Hackbornb437e092011-08-05 17:50:29 -07001270 if (checkin) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 // NOTE: if you change anything significant below, also consider changing
1272 // ACTIVITY_THREAD_CHECKIN_VERSION.
Anwar Ghuloum3c615062013-05-13 14:18:02 -07001273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 // Object counts
1275 pw.print(viewInstanceCount); pw.print(',');
1276 pw.print(viewRootInstanceCount); pw.print(',');
1277 pw.print(appContextInstanceCount); pw.print(',');
1278 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 pw.print(globalAssetCount); pw.print(',');
1281 pw.print(globalAssetManagerCount); pw.print(',');
1282 pw.print(binderLocalObjectCount); pw.print(',');
1283 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 pw.print(binderDeathObjectCount); pw.print(',');
1286 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 // SQL
Vasu Noric3849202010-03-09 10:47:25 -08001289 pw.print(stats.memoryUsed / 1024); pw.print(',');
Jeff Brown2a293b62012-01-19 14:02:22 -08001290 pw.print(stats.memoryUsed / 1024); pw.print(',');
1291 pw.print(stats.pageCacheOverflow / 1024); pw.print(',');
Dianne Hackbornb437e092011-08-05 17:50:29 -07001292 pw.print(stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001293 for (int i = 0; i < stats.dbStats.size(); i++) {
1294 DbStats dbStats = stats.dbStats.get(i);
Dianne Hackbornb437e092011-08-05 17:50:29 -07001295 pw.print(','); pw.print(dbStats.dbName);
1296 pw.print(','); pw.print(dbStats.pageSize);
1297 pw.print(','); pw.print(dbStats.dbSize);
1298 pw.print(','); pw.print(dbStats.lookaside);
1299 pw.print(','); pw.print(dbStats.cache);
1300 pw.print(','); pw.print(dbStats.cache);
Vasu Noric3849202010-03-09 10:47:25 -08001301 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07001302 pw.println();
Bob Leee5408332009-09-04 18:31:17 -07001303
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001304 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 }
Bob Leee5408332009-09-04 18:31:17 -07001306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 pw.println(" ");
1308 pw.println(" Objects");
Romain Guy65b345f2011-07-27 18:51:50 -07001309 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRootImpl:",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 viewRootInstanceCount);
1311
1312 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
1313 "Activities:", activityInstanceCount);
1314
1315 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
1316 "AssetManagers:", globalAssetManagerCount);
1317
1318 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
1319 "Proxy Binders:", binderProxyObjectCount);
Dianne Hackbornfabb70b2014-11-11 12:22:36 -08001320 printRow(pw, TWO_COUNT_COLUMNS, "Parcel memory:", parcelSize/1024,
1321 "Parcel count:", parcelCount);
1322 printRow(pw, TWO_COUNT_COLUMNS, "Death Recipients:", binderDeathObjectCount,
1323 "OpenSSL Sockets:", openSslSocketCount);
Richard Uhler2c036192016-09-14 09:48:31 +01001324 printRow(pw, ONE_COUNT_COLUMN, "WebViews:", webviewInstanceCount);
Bob Leee5408332009-09-04 18:31:17 -07001325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 // SQLite mem info
1327 pw.println(" ");
1328 pw.println(" SQL");
Jeff Brown2a293b62012-01-19 14:02:22 -08001329 printRow(pw, ONE_COUNT_COLUMN, "MEMORY_USED:", stats.memoryUsed / 1024);
1330 printRow(pw, TWO_COUNT_COLUMNS, "PAGECACHE_OVERFLOW:",
1331 stats.pageCacheOverflow / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001332 pw.println(" ");
1333 int N = stats.dbStats.size();
1334 if (N > 0) {
1335 pw.println(" DATABASES");
Kweku Adams983829f2017-12-06 14:53:50 -08001336 printRow(pw, DB_INFO_FORMAT, "pgsz", "dbsz", "Lookaside(b)", "cache",
Vasu Nori3c7131f2010-09-21 14:36:57 -07001337 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -08001338 for (int i = 0; i < N; i++) {
1339 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -07001340 printRow(pw, DB_INFO_FORMAT,
1341 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
1342 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
1343 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
1344 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -08001345 }
1346 }
Bob Leee5408332009-09-04 18:31:17 -07001347
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001348 // Asset details.
1349 String assetAlloc = AssetManager.getAssetAllocations();
1350 if (assetAlloc != null) {
1351 pw.println(" ");
1352 pw.println(" Asset Allocations");
1353 pw.print(assetAlloc);
1354 }
Colin Crossc4fb5f92016-02-02 16:51:15 -08001355
1356 // Unreachable native memory
1357 if (dumpUnreachable) {
1358 boolean showContents = ((mBoundApplication != null)
1359 && ((mBoundApplication.appInfo.flags&ApplicationInfo.FLAG_DEBUGGABLE) != 0))
1360 || android.os.Build.IS_DEBUGGABLE;
1361 pw.println(" ");
1362 pw.println(" Unreachable memory");
1363 pw.print(Debug.getUnreachableMemory(100, showContents));
1364 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001365 }
1366
1367 @Override
Kweku Adams983829f2017-12-06 14:53:50 -08001368 public void dumpMemInfoProto(ParcelFileDescriptor pfd, Debug.MemoryInfo mem,
1369 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
1370 boolean dumpUnreachable, String[] args) {
1371 ProtoOutputStream proto = new ProtoOutputStream(pfd.getFileDescriptor());
1372 try {
1373 dumpMemInfo(proto, mem, dumpFullInfo, dumpDalvik, dumpSummaryOnly, dumpUnreachable);
1374 } finally {
1375 proto.flush();
1376 IoUtils.closeQuietly(pfd);
1377 }
1378 }
1379
1380 private void dumpMemInfo(ProtoOutputStream proto, Debug.MemoryInfo memInfo,
1381 boolean dumpFullInfo, boolean dumpDalvik,
1382 boolean dumpSummaryOnly, boolean dumpUnreachable) {
1383 long nativeMax = Debug.getNativeHeapSize() / 1024;
1384 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1385 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1386
1387 Runtime runtime = Runtime.getRuntime();
1388 runtime.gc(); // Do GC since countInstancesOfClass counts unreachable objects.
1389 long dalvikMax = runtime.totalMemory() / 1024;
1390 long dalvikFree = runtime.freeMemory() / 1024;
1391 long dalvikAllocated = dalvikMax - dalvikFree;
1392
1393 Class[] classesToCount = new Class[] {
1394 ContextImpl.class,
1395 Activity.class,
1396 WebView.class,
1397 OpenSSLSocketImpl.class
1398 };
1399 long[] instanceCounts = VMDebug.countInstancesOfClasses(classesToCount, true);
1400 long appContextInstanceCount = instanceCounts[0];
1401 long activityInstanceCount = instanceCounts[1];
1402 long webviewInstanceCount = instanceCounts[2];
1403 long openSslSocketCount = instanceCounts[3];
1404
1405 long viewInstanceCount = ViewDebug.getViewInstanceCount();
1406 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
1407 int globalAssetCount = AssetManager.getGlobalAssetCount();
1408 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1409 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1410 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1411 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
1412 long parcelSize = Parcel.getGlobalAllocSize();
1413 long parcelCount = Parcel.getGlobalAllocCount();
1414 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
1415
Yi Jin2b30f322018-02-20 15:41:47 -08001416 final long mToken = proto.start(MemInfoDumpProto.AppData.PROCESS_MEMORY);
1417 proto.write(MemInfoDumpProto.ProcessMemory.PID, Process.myPid());
1418 proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME,
Kweku Adams983829f2017-12-06 14:53:50 -08001419 (mBoundApplication != null) ? mBoundApplication.processName : "unknown");
1420 dumpMemInfoTable(proto, memInfo, dumpDalvik, dumpSummaryOnly,
1421 nativeMax, nativeAllocated, nativeFree,
1422 dalvikMax, dalvikAllocated, dalvikFree);
1423 proto.end(mToken);
1424
Yi Jin2b30f322018-02-20 15:41:47 -08001425 final long oToken = proto.start(MemInfoDumpProto.AppData.OBJECTS);
1426 proto.write(MemInfoDumpProto.AppData.ObjectStats.VIEW_INSTANCE_COUNT,
1427 viewInstanceCount);
1428 proto.write(MemInfoDumpProto.AppData.ObjectStats.VIEW_ROOT_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001429 viewRootInstanceCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001430 proto.write(MemInfoDumpProto.AppData.ObjectStats.APP_CONTEXT_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001431 appContextInstanceCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001432 proto.write(MemInfoDumpProto.AppData.ObjectStats.ACTIVITY_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001433 activityInstanceCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001434 proto.write(MemInfoDumpProto.AppData.ObjectStats.GLOBAL_ASSET_COUNT,
1435 globalAssetCount);
1436 proto.write(MemInfoDumpProto.AppData.ObjectStats.GLOBAL_ASSET_MANAGER_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001437 globalAssetManagerCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001438 proto.write(MemInfoDumpProto.AppData.ObjectStats.LOCAL_BINDER_OBJECT_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001439 binderLocalObjectCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001440 proto.write(MemInfoDumpProto.AppData.ObjectStats.PROXY_BINDER_OBJECT_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001441 binderProxyObjectCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001442 proto.write(MemInfoDumpProto.AppData.ObjectStats.PARCEL_MEMORY_KB,
1443 parcelSize / 1024);
1444 proto.write(MemInfoDumpProto.AppData.ObjectStats.PARCEL_COUNT, parcelCount);
1445 proto.write(MemInfoDumpProto.AppData.ObjectStats.BINDER_OBJECT_DEATH_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001446 binderDeathObjectCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001447 proto.write(MemInfoDumpProto.AppData.ObjectStats.OPEN_SSL_SOCKET_COUNT,
1448 openSslSocketCount);
1449 proto.write(MemInfoDumpProto.AppData.ObjectStats.WEBVIEW_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001450 webviewInstanceCount);
1451 proto.end(oToken);
1452
1453 // SQLite mem info
Yi Jin2b30f322018-02-20 15:41:47 -08001454 final long sToken = proto.start(MemInfoDumpProto.AppData.SQL);
1455 proto.write(MemInfoDumpProto.AppData.SqlStats.MEMORY_USED_KB,
1456 stats.memoryUsed / 1024);
1457 proto.write(MemInfoDumpProto.AppData.SqlStats.PAGECACHE_OVERFLOW_KB,
Kweku Adams983829f2017-12-06 14:53:50 -08001458 stats.pageCacheOverflow / 1024);
Yi Jin2b30f322018-02-20 15:41:47 -08001459 proto.write(MemInfoDumpProto.AppData.SqlStats.MALLOC_SIZE_KB,
1460 stats.largestMemAlloc / 1024);
Kweku Adams983829f2017-12-06 14:53:50 -08001461 int n = stats.dbStats.size();
1462 for (int i = 0; i < n; i++) {
1463 DbStats dbStats = stats.dbStats.get(i);
1464
Yi Jin2b30f322018-02-20 15:41:47 -08001465 final long dToken = proto.start(MemInfoDumpProto.AppData.SqlStats.DATABASES);
1466 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.NAME, dbStats.dbName);
1467 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.PAGE_SIZE, dbStats.pageSize);
1468 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.DB_SIZE, dbStats.dbSize);
1469 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.LOOKASIDE_B,
1470 dbStats.lookaside);
1471 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.CACHE, dbStats.cache);
Kweku Adams983829f2017-12-06 14:53:50 -08001472 proto.end(dToken);
1473 }
1474 proto.end(sToken);
1475
1476 // Asset details.
1477 String assetAlloc = AssetManager.getAssetAllocations();
1478 if (assetAlloc != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08001479 proto.write(MemInfoDumpProto.AppData.ASSET_ALLOCATIONS, assetAlloc);
Kweku Adams983829f2017-12-06 14:53:50 -08001480 }
1481
1482 // Unreachable native memory
1483 if (dumpUnreachable) {
1484 int flags = mBoundApplication == null ? 0 : mBoundApplication.appInfo.flags;
1485 boolean showContents = (flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0
1486 || android.os.Build.IS_DEBUGGABLE;
Yi Jin2b30f322018-02-20 15:41:47 -08001487 proto.write(MemInfoDumpProto.AppData.UNREACHABLE_MEMORY,
Kweku Adams983829f2017-12-06 14:53:50 -08001488 Debug.getUnreachableMemory(100, showContents));
1489 }
1490 }
1491
1492 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001493 public void dumpGfxInfo(ParcelFileDescriptor pfd, String[] args) {
Chris Craikfc294242016-12-13 18:10:46 -08001494 nDumpGraphicsInfo(pfd.getFileDescriptor());
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001495 WindowManagerGlobal.getInstance().dumpGfxInfo(pfd.getFileDescriptor(), args);
1496 IoUtils.closeQuietly(pfd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 }
1498
Makoto Onuki016dc592018-08-14 12:26:45 -07001499 private File getDatabasesDir(Context context) {
1500 // There's no simple way to get the databases/ path, so do it this way.
1501 return context.getDatabasePath("a").getParentFile();
1502 }
1503
1504 private void dumpDatabaseInfo(ParcelFileDescriptor pfd, String[] args, boolean isSystem) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001505 PrintWriter pw = new FastPrintWriter(
1506 new FileOutputStream(pfd.getFileDescriptor()));
Jeff Brown6754ba22011-12-14 20:20:01 -08001507 PrintWriterPrinter printer = new PrintWriterPrinter(pw);
Makoto Onukiee93ad22018-10-18 16:24:13 -07001508 SQLiteDebug.dump(printer, args, isSystem);
Jeff Brown6754ba22011-12-14 20:20:01 -08001509 pw.flush();
1510 }
1511
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001512 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001513 public void dumpDbInfo(final ParcelFileDescriptor pfd, final String[] args) {
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001514 if (mSystemThread) {
Felipe Leme29de4922016-06-07 16:14:07 -07001515 // Ensure this invocation is asynchronous to prevent writer waiting if buffer cannot
1516 // be consumed. But it must duplicate the file descriptor first, since caller might
1517 // be closing it.
1518 final ParcelFileDescriptor dup;
1519 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001520 dup = pfd.dup();
Felipe Leme29de4922016-06-07 16:14:07 -07001521 } catch (IOException e) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001522 Log.w(TAG, "Could not dup FD " + pfd.getFileDescriptor().getInt$());
Felipe Leme29de4922016-06-07 16:14:07 -07001523 return;
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001524 } finally {
1525 IoUtils.closeQuietly(pfd);
Felipe Leme29de4922016-06-07 16:14:07 -07001526 }
1527
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001528 AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
1529 @Override
1530 public void run() {
Felipe Lemec74972f2016-06-08 09:12:37 -07001531 try {
Makoto Onuki016dc592018-08-14 12:26:45 -07001532 dumpDatabaseInfo(dup, args, true);
Felipe Lemec74972f2016-06-08 09:12:37 -07001533 } finally {
1534 IoUtils.closeQuietly(dup);
1535 }
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001536 }
1537 });
1538 } else {
Makoto Onuki016dc592018-08-14 12:26:45 -07001539 dumpDatabaseInfo(pfd, args, false);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001540 IoUtils.closeQuietly(pfd);
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001541 }
1542 }
1543
1544 @Override
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001545 public void unstableProviderDied(IBinder provider) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001546 sendMessage(H.UNSTABLE_PROVIDER_DIED, provider);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001547 }
1548
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001549 @Override
Adam Skorydfc7fd72013-08-05 19:23:41 -07001550 public void requestAssistContextExtras(IBinder activityToken, IBinder requestToken,
Svet Ganovfd31f852017-04-26 15:54:27 -07001551 int requestType, int sessionId, int flags) {
Adam Skorydfc7fd72013-08-05 19:23:41 -07001552 RequestAssistContextExtras cmd = new RequestAssistContextExtras();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001553 cmd.activityToken = activityToken;
1554 cmd.requestToken = requestToken;
1555 cmd.requestType = requestType;
Amith Yamasani4f128e42016-05-10 11:44:12 -07001556 cmd.sessionId = sessionId;
Svet Ganovfd31f852017-04-26 15:54:27 -07001557 cmd.flags = flags;
Jeff Brown9ef09972013-10-15 20:49:59 -07001558 sendMessage(H.REQUEST_ASSIST_CONTEXT_EXTRAS, cmd);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001559 }
1560
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08001561 public void setCoreSettings(Bundle coreSettings) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001562 sendMessage(H.SET_CORE_SETTINGS, coreSettings);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001563 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001564
1565 public void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) {
1566 UpdateCompatibilityData ucd = new UpdateCompatibilityData();
1567 ucd.pkg = pkg;
1568 ucd.info = info;
Jeff Brown9ef09972013-10-15 20:49:59 -07001569 sendMessage(H.UPDATE_PACKAGE_COMPATIBILITY_INFO, ucd);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001570 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001571
1572 public void scheduleTrimMemory(int level) {
Jorim Jaggib29e3182018-04-30 18:51:56 +02001573 final Runnable r = PooledLambda.obtainRunnable(ActivityThread::handleTrimMemory,
Yohei Yukawae2fa39e2018-09-22 13:13:10 -07001574 ActivityThread.this, level).recycleOnUse();
Jorim Jaggib29e3182018-04-30 18:51:56 +02001575 // Schedule trimming memory after drawing the frame to minimize jank-risk.
1576 Choreographer choreographer = Choreographer.getMainThreadInstance();
1577 if (choreographer != null) {
1578 choreographer.postCallback(Choreographer.CALLBACK_COMMIT, r, null);
1579 } else {
1580 mH.post(r);
1581 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001582 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001583
Craig Mautner5eda9b32013-07-02 11:58:16 -07001584 public void scheduleTranslucentConversionComplete(IBinder token, boolean drawComplete) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001585 sendMessage(H.TRANSLUCENT_CONVERSION_COMPLETE, token, drawComplete ? 1 : 0);
Craig Mautner5eda9b32013-07-02 11:58:16 -07001586 }
Dianne Hackborna413dc02013-07-12 12:02:55 -07001587
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001588 public void scheduleOnNewActivityOptions(IBinder token, Bundle options) {
Craig Mautnereb8abf72014-07-02 15:04:09 -07001589 sendMessage(H.ON_NEW_ACTIVITY_OPTIONS,
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001590 new Pair<IBinder, ActivityOptions>(token, ActivityOptions.fromBundle(options)));
Craig Mautnereb8abf72014-07-02 15:04:09 -07001591 }
1592
Dianne Hackborna413dc02013-07-12 12:02:55 -07001593 public void setProcessState(int state) {
1594 updateProcessState(state, true);
1595 }
1596
Sudheer Shanka84a48952017-03-08 18:19:01 -08001597 /**
1598 * Updates {@link #mNetworkBlockSeq}. This is used by ActivityManagerService to inform
1599 * the main thread that it needs to wait for the network rules to get updated before
1600 * launching an activity.
1601 */
1602 @Override
1603 public void setNetworkBlockSeq(long procStateSeq) {
1604 synchronized (mNetworkPolicyLock) {
1605 mNetworkBlockSeq = procStateSeq;
1606 }
1607 }
1608
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001609 @Override
1610 public void scheduleInstallProvider(ProviderInfo provider) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001611 sendMessage(H.INSTALL_PROVIDER, provider);
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001612 }
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001613
1614 @Override
Neil Fullerb7146fe2016-11-15 16:52:15 +00001615 public final void updateTimePrefs(int timeFormatPreference) {
1616 final Boolean timeFormatPreferenceBool;
1617 // For convenience we are using the Intent extra values.
1618 if (timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_12_HOUR) {
1619 timeFormatPreferenceBool = Boolean.FALSE;
1620 } else if (timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_24_HOUR) {
1621 timeFormatPreferenceBool = Boolean.TRUE;
1622 } else {
1623 // timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_LOCALE_DEFAULT
1624 // (or unknown).
1625 timeFormatPreferenceBool = null;
1626 }
1627 DateFormat.set24HourTimePref(timeFormatPreferenceBool);
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001628 }
Craig Mautneree2e45a2014-06-27 12:10:03 -07001629
1630 @Override
Craig Mautner8746a472014-07-24 15:12:54 -07001631 public void scheduleEnterAnimationComplete(IBinder token) {
1632 sendMessage(H.ENTER_ANIMATION_COMPLETE, token);
1633 }
Jeff Sharkey605eb792014-11-04 13:34:06 -08001634
1635 @Override
1636 public void notifyCleartextNetwork(byte[] firstPacket) {
1637 if (StrictMode.vmCleartextNetworkEnabled()) {
1638 StrictMode.onCleartextNetworkDetected(firstPacket);
1639 }
1640 }
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001641
1642 @Override
1643 public void startBinderTracking() {
1644 sendMessage(H.START_BINDER_TRACKING, null);
1645 }
1646
1647 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001648 public void stopBinderTrackingAndDump(ParcelFileDescriptor pfd) {
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001649 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001650 sendMessage(H.STOP_BINDER_TRACKING_AND_DUMP, pfd.dup());
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001651 } catch (IOException e) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001652 } finally {
1653 IoUtils.closeQuietly(pfd);
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001654 }
1655 }
Wale Ogunwale5f986092015-12-04 15:35:38 -08001656
1657 @Override
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001658 public void scheduleLocalVoiceInteractionStarted(IBinder token,
1659 IVoiceInteractor voiceInteractor) throws RemoteException {
1660 SomeArgs args = SomeArgs.obtain();
1661 args.arg1 = token;
1662 args.arg2 = voiceInteractor;
1663 sendMessage(H.LOCAL_VOICE_INTERACTION_STARTED, args);
1664 }
Chad Brubakerc72875b2016-04-27 16:35:11 -07001665
1666 @Override
1667 public void handleTrustStorageUpdate() {
1668 NetworkSecurityPolicy.getInstance().handleTrustStorageUpdate();
1669 }
Andrii Kulian446e8242017-10-26 15:17:29 -07001670
1671 @Override
1672 public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
1673 ActivityThread.this.scheduleTransaction(transaction);
1674 }
Sunny Goyald40c3452019-03-20 12:46:55 -07001675
1676 @Override
1677 public void requestDirectActions(@NonNull IBinder activityToken,
Svet Ganov3b6be082019-04-28 10:21:01 -07001678 @NonNull IVoiceInteractor interactor, @Nullable RemoteCallback cancellationCallback,
1679 @NonNull RemoteCallback callback) {
1680 final CancellationSignal cancellationSignal = new CancellationSignal();
Sunny Goyald40c3452019-03-20 12:46:55 -07001681 if (cancellationCallback != null) {
Svet Ganov3b6be082019-04-28 10:21:01 -07001682 final ICancellationSignal transport = createSafeCancellationTransport(
1683 cancellationSignal);
Sunny Goyald40c3452019-03-20 12:46:55 -07001684 final Bundle cancellationResult = new Bundle();
1685 cancellationResult.putBinder(VoiceInteractor.KEY_CANCELLATION_SIGNAL,
1686 transport.asBinder());
1687 cancellationCallback.sendResult(cancellationResult);
Sunny Goyald40c3452019-03-20 12:46:55 -07001688 }
Svet Ganov3b6be082019-04-28 10:21:01 -07001689 mH.sendMessage(PooledLambda.obtainMessage(ActivityThread::handleRequestDirectActions,
1690 ActivityThread.this, activityToken, interactor, cancellationSignal, callback));
1691 }
Sunny Goyald40c3452019-03-20 12:46:55 -07001692
Svet Ganov3b6be082019-04-28 10:21:01 -07001693 @Override
1694 public void performDirectAction(@NonNull IBinder activityToken, @NonNull String actionId,
1695 @Nullable Bundle arguments, @Nullable RemoteCallback cancellationCallback,
1696 @NonNull RemoteCallback resultCallback) {
1697 final CancellationSignal cancellationSignal = new CancellationSignal();
1698 if (cancellationCallback != null) {
1699 final ICancellationSignal transport = createSafeCancellationTransport(
1700 cancellationSignal);
1701 final Bundle cancellationResult = new Bundle();
1702 cancellationResult.putBinder(VoiceInteractor.KEY_CANCELLATION_SIGNAL,
1703 transport.asBinder());
1704 cancellationCallback.sendResult(cancellationResult);
1705 }
Sunny Goyald40c3452019-03-20 12:46:55 -07001706 mH.sendMessage(PooledLambda.obtainMessage(ActivityThread::handlePerformDirectAction,
1707 ActivityThread.this, activityToken, actionId, arguments,
1708 cancellationSignal, resultCallback));
1709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 }
1711
Svet Ganov3b6be082019-04-28 10:21:01 -07001712 private @NonNull SafeCancellationTransport createSafeCancellationTransport(
1713 @NonNull CancellationSignal cancellationSignal) {
1714 synchronized (ActivityThread.this) {
1715 if (mRemoteCancellations == null) {
1716 mRemoteCancellations = new ArrayMap<>();
1717 }
1718 final SafeCancellationTransport transport = new SafeCancellationTransport(
1719 this, cancellationSignal);
1720 mRemoteCancellations.put(transport, cancellationSignal);
1721 return transport;
1722 }
1723 }
1724
1725 private @NonNull CancellationSignal removeSafeCancellationTransport(
1726 @NonNull SafeCancellationTransport transport) {
1727 synchronized (ActivityThread.this) {
1728 final CancellationSignal cancellation = mRemoteCancellations.remove(transport);
1729 if (mRemoteCancellations.isEmpty()) {
1730 mRemoteCancellations = null;
1731 }
1732 return cancellation;
1733 }
1734 }
1735
1736 private static final class SafeCancellationTransport extends ICancellationSignal.Stub {
1737 private final @NonNull WeakReference<ActivityThread> mWeakActivityThread;
1738
1739 SafeCancellationTransport(@NonNull ActivityThread activityThread,
1740 @NonNull CancellationSignal cancellation) {
1741 mWeakActivityThread = new WeakReference<>(activityThread);
1742 }
1743
1744 @Override
1745 public void cancel() {
1746 final ActivityThread activityThread = mWeakActivityThread.get();
1747 if (activityThread != null) {
1748 final CancellationSignal cancellation = activityThread
1749 .removeSafeCancellationTransport(this);
1750 if (cancellation != null) {
1751 cancellation.cancel();
1752 }
1753 }
1754 }
1755 }
1756
Andrii Kulian446e8242017-10-26 15:17:29 -07001757 class H extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 public static final int BIND_APPLICATION = 110;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001759 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 public static final int EXIT_APPLICATION = 111;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001761 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 public static final int RECEIVER = 113;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001763 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 public static final int CREATE_SERVICE = 114;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001765 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 public static final int SERVICE_ARGS = 115;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001767 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 public static final int STOP_SERVICE = 116;
Dianne Hackborn09233282014-04-30 11:33:59 -07001769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 public static final int CONFIGURATION_CHANGED = 118;
1771 public static final int CLEAN_UP_CONTEXT = 119;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001772 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 public static final int GC_WHEN_IDLE = 120;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001774 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 public static final int BIND_SERVICE = 121;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001776 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 public static final int UNBIND_SERVICE = 122;
1778 public static final int DUMP_SERVICE = 123;
1779 public static final int LOW_MEMORY = 124;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001780 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001781 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001782 public static final int DESTROY_BACKUP_AGENT = 129;
1783 public static final int SUICIDE = 130;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001784 @UnsupportedAppUsage
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001785 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001786 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001787 @UnsupportedAppUsage
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001788 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -07001789 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001790 public static final int DUMP_ACTIVITY = 136;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001791 public static final int SLEEPING = 137;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001792 public static final int SET_CORE_SETTINGS = 138;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001793 public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001794 @UnsupportedAppUsage
Marco Nelissen18cb2872011-11-15 11:19:53 -08001795 public static final int DUMP_PROVIDER = 141;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001796 public static final int UNSTABLE_PROVIDER_DIED = 142;
Adam Skorydfc7fd72013-08-05 19:23:41 -07001797 public static final int REQUEST_ASSIST_CONTEXT_EXTRAS = 143;
Craig Mautner5eda9b32013-07-02 11:58:16 -07001798 public static final int TRANSLUCENT_CONVERSION_COMPLETE = 144;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001799 @UnsupportedAppUsage
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001800 public static final int INSTALL_PROVIDER = 145;
Craig Mautnereb8abf72014-07-02 15:04:09 -07001801 public static final int ON_NEW_ACTIVITY_OPTIONS = 146;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001802 @UnsupportedAppUsage
Craig Mautner8746a472014-07-24 15:12:54 -07001803 public static final int ENTER_ANIMATION_COMPLETE = 149;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001804 public static final int START_BINDER_TRACKING = 150;
1805 public static final int STOP_BINDER_TRACKING_AND_DUMP = 151;
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001806 public static final int LOCAL_VOICE_INTERACTION_STARTED = 154;
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001807 public static final int ATTACH_AGENT = 155;
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001808 public static final int APPLICATION_INFO_CHANGED = 156;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001809 public static final int RUN_ISOLATED_ENTRY_POINT = 158;
Andrii Kulian446e8242017-10-26 15:17:29 -07001810 public static final int EXECUTE_TRANSACTION = 159;
Andrii Kulian320e3b52018-05-03 16:26:25 -07001811 public static final int RELAUNCH_ACTIVITY = 160;
Tim Murray59f3dc12018-10-22 15:26:08 -07001812 public static final int PURGE_RESOURCES = 161;
Alex Light2d0691c2019-10-03 14:36:57 -07001813 public static final int ATTACH_STARTUP_AGENTS = 162;
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001816 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 switch (code) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 case BIND_APPLICATION: return "BIND_APPLICATION";
1819 case EXIT_APPLICATION: return "EXIT_APPLICATION";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 case RECEIVER: return "RECEIVER";
1821 case CREATE_SERVICE: return "CREATE_SERVICE";
1822 case SERVICE_ARGS: return "SERVICE_ARGS";
1823 case STOP_SERVICE: return "STOP_SERVICE";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1825 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1826 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1827 case BIND_SERVICE: return "BIND_SERVICE";
1828 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1829 case DUMP_SERVICE: return "DUMP_SERVICE";
1830 case LOW_MEMORY: return "LOW_MEMORY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001831 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001832 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1833 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001834 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001835 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001836 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001837 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -07001838 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -07001839 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001840 case SLEEPING: return "SLEEPING";
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001841 case SET_CORE_SETTINGS: return "SET_CORE_SETTINGS";
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001842 case UPDATE_PACKAGE_COMPATIBILITY_INFO: return "UPDATE_PACKAGE_COMPATIBILITY_INFO";
Marco Nelissen18cb2872011-11-15 11:19:53 -08001843 case DUMP_PROVIDER: return "DUMP_PROVIDER";
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001844 case UNSTABLE_PROVIDER_DIED: return "UNSTABLE_PROVIDER_DIED";
Adam Skorydfc7fd72013-08-05 19:23:41 -07001845 case REQUEST_ASSIST_CONTEXT_EXTRAS: return "REQUEST_ASSIST_CONTEXT_EXTRAS";
Craig Mautner5eda9b32013-07-02 11:58:16 -07001846 case TRANSLUCENT_CONVERSION_COMPLETE: return "TRANSLUCENT_CONVERSION_COMPLETE";
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001847 case INSTALL_PROVIDER: return "INSTALL_PROVIDER";
Craig Mautnereb8abf72014-07-02 15:04:09 -07001848 case ON_NEW_ACTIVITY_OPTIONS: return "ON_NEW_ACTIVITY_OPTIONS";
Craig Mautner8746a472014-07-24 15:12:54 -07001849 case ENTER_ANIMATION_COMPLETE: return "ENTER_ANIMATION_COMPLETE";
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001850 case LOCAL_VOICE_INTERACTION_STARTED: return "LOCAL_VOICE_INTERACTION_STARTED";
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001851 case ATTACH_AGENT: return "ATTACH_AGENT";
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001852 case APPLICATION_INFO_CHANGED: return "APPLICATION_INFO_CHANGED";
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001853 case RUN_ISOLATED_ENTRY_POINT: return "RUN_ISOLATED_ENTRY_POINT";
Andrii Kulian446e8242017-10-26 15:17:29 -07001854 case EXECUTE_TRANSACTION: return "EXECUTE_TRANSACTION";
Andrii Kulian320e3b52018-05-03 16:26:25 -07001855 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
Tim Murray59f3dc12018-10-22 15:26:08 -07001856 case PURGE_RESOURCES: return "PURGE_RESOURCES";
Alex Light2d0691c2019-10-03 14:36:57 -07001857 case ATTACH_STARTUP_AGENTS: return "ATTACH_STARTUP_AGENTS";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 }
1859 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001860 return Integer.toString(code);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001861 }
1862 public void handleMessage(Message msg) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001863 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 switch (msg.what) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 case BIND_APPLICATION:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001866 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 AppBindData data = (AppBindData)msg.obj;
1868 handleBindApplication(data);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001869 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 break;
1871 case EXIT_APPLICATION:
1872 if (mInitialApplication != null) {
1873 mInitialApplication.onTerminate();
1874 }
1875 Looper.myLooper().quit();
1876 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 case RECEIVER:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001878 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveComp");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 handleReceiver((ReceiverData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001880 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 break;
1882 case CREATE_SERVICE:
Tim Murrayb6f5a422016-04-07 15:25:22 -07001883 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceCreate: " + String.valueOf(msg.obj)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 handleCreateService((CreateServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001885 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 break;
1887 case BIND_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001888 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 handleBindService((BindServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001890 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 break;
1892 case UNBIND_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001893 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceUnbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 handleUnbindService((BindServiceData)msg.obj);
Tim Murray59f3dc12018-10-22 15:26:08 -07001895 schedulePurgeIdler();
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001896 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 break;
1898 case SERVICE_ARGS:
Tim Murrayb6f5a422016-04-07 15:25:22 -07001899 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceStart: " + String.valueOf(msg.obj)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 handleServiceArgs((ServiceArgsData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001901 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 break;
1903 case STOP_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001904 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 handleStopService((IBinder)msg.obj);
Tim Murray59f3dc12018-10-22 15:26:08 -07001906 schedulePurgeIdler();
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001907 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 case CONFIGURATION_CHANGED:
Andrii Kulian446e8242017-10-26 15:17:29 -07001910 handleConfigurationChanged((Configuration) msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 break;
1912 case CLEAN_UP_CONTEXT:
1913 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1914 cci.context.performFinalCleanup(cci.who, cci.what);
1915 break;
1916 case GC_WHEN_IDLE:
1917 scheduleGcIdler();
1918 break;
1919 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001920 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 break;
1922 case LOW_MEMORY:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001923 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "lowMemory");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 handleLowMemory();
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001925 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001927 case PROFILER_CONTROL:
Jeff Hao1b012d32014-08-20 10:35:34 -07001928 handleProfilerControl(msg.arg1 != 0, (ProfilerInfo)msg.obj, msg.arg2);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001929 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001930 case CREATE_BACKUP_AGENT:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001931 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupCreateAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001932 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001933 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate181fafa2009-05-14 11:12:14 -07001934 break;
1935 case DESTROY_BACKUP_AGENT:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001936 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupDestroyAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001937 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001938 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate181fafa2009-05-14 11:12:14 -07001939 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001940 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001941 Process.killProcess(Process.myPid());
1942 break;
1943 case REMOVE_PROVIDER:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001944 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "providerRemove");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001945 completeRemoveProvider((ProviderRefCount)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001946 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001947 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001948 case DISPATCH_PACKAGE_BROADCAST:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001949 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastPackage");
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001950 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001951 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001952 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001953 case SCHEDULE_CRASH:
1954 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001955 case DUMP_HEAP:
Christopher Ferris8d652f82017-04-11 16:29:18 -07001956 handleDumpHeap((DumpHeapData) msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001957 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001958 case DUMP_ACTIVITY:
1959 handleDumpActivity((DumpComponentInfo)msg.obj);
1960 break;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001961 case DUMP_PROVIDER:
1962 handleDumpProvider((DumpComponentInfo)msg.obj);
1963 break;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001964 case SLEEPING:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001965 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "sleeping");
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001966 handleSleeping((IBinder)msg.obj, msg.arg1 != 0);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001967 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001968 break;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001969 case SET_CORE_SETTINGS:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001970 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setCoreSettings");
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001971 handleSetCoreSettings((Bundle) msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001972 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001973 break;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001974 case UPDATE_PACKAGE_COMPATIBILITY_INFO:
1975 handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001976 break;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001977 case UNSTABLE_PROVIDER_DIED:
1978 handleUnstableProviderDied((IBinder)msg.obj, false);
1979 break;
Adam Skorydfc7fd72013-08-05 19:23:41 -07001980 case REQUEST_ASSIST_CONTEXT_EXTRAS:
1981 handleRequestAssistContextExtras((RequestAssistContextExtras)msg.obj);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001982 break;
Craig Mautner5eda9b32013-07-02 11:58:16 -07001983 case TRANSLUCENT_CONVERSION_COMPLETE:
1984 handleTranslucentConversionComplete((IBinder)msg.obj, msg.arg1 == 1);
1985 break;
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001986 case INSTALL_PROVIDER:
1987 handleInstallProvider((ProviderInfo) msg.obj);
1988 break;
Craig Mautnereb8abf72014-07-02 15:04:09 -07001989 case ON_NEW_ACTIVITY_OPTIONS:
1990 Pair<IBinder, ActivityOptions> pair = (Pair<IBinder, ActivityOptions>) msg.obj;
1991 onNewActivityOptions(pair.first, pair.second);
Dake Gu7ef70b02014-07-08 18:37:12 -07001992 break;
Craig Mautner8746a472014-07-24 15:12:54 -07001993 case ENTER_ANIMATION_COMPLETE:
1994 handleEnterAnimationComplete((IBinder) msg.obj);
1995 break;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001996 case START_BINDER_TRACKING:
1997 handleStartBinderTracking();
1998 break;
1999 case STOP_BINDER_TRACKING_AND_DUMP:
2000 handleStopBinderTrackingAndDump((ParcelFileDescriptor) msg.obj);
2001 break;
Amith Yamasani0af6fa72016-01-17 15:36:19 -08002002 case LOCAL_VOICE_INTERACTION_STARTED:
2003 handleLocalVoiceInteractionStarted((IBinder) ((SomeArgs) msg.obj).arg1,
2004 (IVoiceInteractor) ((SomeArgs) msg.obj).arg2);
Amith Yamasani61019112017-01-10 15:05:00 -08002005 break;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08002006 case ATTACH_AGENT: {
2007 Application app = getApplication();
2008 handleAttachAgent((String) msg.obj, app != null ? app.mLoadedApk : null);
Amith Yamasani0af6fa72016-01-17 15:36:19 -08002009 break;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08002010 }
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01002011 case APPLICATION_INFO_CHANGED:
2012 mUpdatingSystemConfig = true;
2013 try {
2014 handleApplicationInfoChanged((ApplicationInfo) msg.obj);
2015 } finally {
2016 mUpdatingSystemConfig = false;
2017 }
2018 break;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04002019 case RUN_ISOLATED_ENTRY_POINT:
2020 handleRunIsolatedEntryPoint((String) ((SomeArgs) msg.obj).arg1,
2021 (String[]) ((SomeArgs) msg.obj).arg2);
2022 break;
Andrii Kulian446e8242017-10-26 15:17:29 -07002023 case EXECUTE_TRANSACTION:
Andrii Kulian04470682018-01-10 15:32:31 -08002024 final ClientTransaction transaction = (ClientTransaction) msg.obj;
2025 mTransactionExecutor.execute(transaction);
2026 if (isSystem()) {
2027 // Client transactions inside system process are recycled on the client side
2028 // instead of ClientLifecycleManager to avoid being cleared before this
2029 // message is handled.
2030 transaction.recycle();
2031 }
Andrii Kulian914aa7d2018-03-19 21:51:53 -07002032 // TODO(lifecycler): Recycle locally scheduled transactions.
Andrii Kulian446e8242017-10-26 15:17:29 -07002033 break;
Andrii Kulian320e3b52018-05-03 16:26:25 -07002034 case RELAUNCH_ACTIVITY:
2035 handleRelaunchActivityLocally((IBinder) msg.obj);
2036 break;
Tim Murray59f3dc12018-10-22 15:26:08 -07002037 case PURGE_RESOURCES:
2038 schedulePurgeIdler();
2039 break;
Alex Light2d0691c2019-10-03 14:36:57 -07002040 case ATTACH_STARTUP_AGENTS:
2041 handleAttachStartupAgents((String) msg.obj);
2042 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 }
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07002044 Object obj = msg.obj;
2045 if (obj instanceof SomeArgs) {
2046 ((SomeArgs) obj).recycle();
2047 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07002048 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 }
2050 }
2051
Romain Guy65b345f2011-07-27 18:51:50 -07002052 private class Idler implements MessageQueue.IdleHandler {
Craig Mautner48d0d182013-06-11 07:53:06 -07002053 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002055 ActivityClientRecord a = mNewActivities;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002056 boolean stopProfiling = false;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002057 if (mBoundApplication != null && mProfiler.profileFd != null
2058 && mProfiler.autoStopProfiler) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002059 stopProfiling = true;
2060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 if (a != null) {
2062 mNewActivities = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002063 IActivityTaskManager am = ActivityTaskManager.getService();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002064 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002066 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002067 TAG, "Reporting idle of " + a +
2068 " finished=" +
Romain Guy65b345f2011-07-27 18:51:50 -07002069 (a.activity != null && a.activity.mFinished));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 if (a.activity != null && !a.activity.mFinished) {
2071 try {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002072 am.activityIdle(a.token, a.createdConfig, stopProfiling);
Dianne Hackborne88846e2009-09-30 21:34:25 -07002073 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002075 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 }
2077 }
2078 prev = a;
2079 a = a.nextIdle;
2080 prev.nextIdle = null;
2081 } while (a != null);
2082 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002083 if (stopProfiling) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002084 mProfiler.stopProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002085 }
Riddle Hsu50e34002019-04-12 20:42:05 +08002086 applyPendingProcessState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 return false;
2088 }
2089 }
2090
2091 final class GcIdler implements MessageQueue.IdleHandler {
Craig Mautner48d0d182013-06-11 07:53:06 -07002092 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 public final boolean queueIdle() {
2094 doGcIfNeeded();
Makoto Onuki0a9ee1a2019-06-19 08:58:02 -07002095 purgePendingResources();
Tim Murray59f3dc12018-10-22 15:26:08 -07002096 return false;
2097 }
2098 }
2099
2100 final class PurgeIdler implements MessageQueue.IdleHandler {
2101 @Override
2102 public boolean queueIdle() {
Makoto Onuki0a9ee1a2019-06-19 08:58:02 -07002103 purgePendingResources();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 return false;
2105 }
2106 }
2107
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002108 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07002109 public static ActivityThread currentActivityThread() {
Jeff Sharkey66a017b2013-01-17 18:18:22 -08002110 return sCurrentActivityThread;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112
Wale Ogunwale9a6ef1e2015-06-02 13:41:00 -07002113 public static boolean isSystem() {
2114 return (sCurrentActivityThread != null) ? sCurrentActivityThread.mSystemThread : false;
2115 }
2116
Svetoslavfbf0eca2015-05-01 16:52:41 -07002117 public static String currentOpPackageName() {
2118 ActivityThread am = currentActivityThread();
2119 return (am != null && am.getApplication() != null)
2120 ? am.getApplication().getOpPackageName() : null;
2121 }
2122
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002123 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07002124 public static String currentPackageName() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002125 ActivityThread am = currentActivityThread();
2126 return (am != null && am.mBoundApplication != null)
Dianne Hackbornb57a50b2013-04-11 17:29:32 -07002127 ? am.mBoundApplication.appInfo.packageName : null;
2128 }
2129
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002130 @UnsupportedAppUsage
Dianne Hackbornb57a50b2013-04-11 17:29:32 -07002131 public static String currentProcessName() {
2132 ActivityThread am = currentActivityThread();
2133 return (am != null && am.mBoundApplication != null)
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002134 ? am.mBoundApplication.processName : null;
2135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002136
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002137 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07002138 public static Application currentApplication() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002139 ActivityThread am = currentActivityThread();
2140 return am != null ? am.mInitialApplication : null;
2141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002143 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002144 public static IPackageManager getPackageManager() {
2145 if (sPackageManager != null) {
2146 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
2147 return sPackageManager;
2148 }
2149 IBinder b = ServiceManager.getService("package");
2150 //Slog.v("PackageManager", "default service binder = " + b);
2151 sPackageManager = IPackageManager.Stub.asInterface(b);
2152 //Slog.v("PackageManager", "default service = " + sPackageManager);
2153 return sPackageManager;
2154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002155
Romain Guy65b345f2011-07-27 18:51:50 -07002156 private Configuration mMainThreadConfig = new Configuration();
Amith Yamasani4f128e42016-05-10 11:44:12 -07002157
Dianne Hackborn908aecc2012-07-31 16:37:34 -07002158 Configuration applyConfigCompatMainThread(int displayDensity, Configuration config,
2159 CompatibilityInfo compat) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002160 if (config == null) {
2161 return null;
2162 }
Craig Mautner48d0d182013-06-11 07:53:06 -07002163 if (!compat.supportsScreen()) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002164 mMainThreadConfig.setTo(config);
2165 config = mMainThreadConfig;
Dianne Hackborn908aecc2012-07-31 16:37:34 -07002166 compat.applyToConfiguration(displayDensity, config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002167 }
2168 return config;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002171 /**
Todd Kennedy39bfee52016-02-24 10:28:21 -08002172 * Creates the top level resources for the given package. Will return an existing
2173 * Resources if one has already been created.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002174 */
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07002175 Resources getTopLevelResources(String resDir, String[] splitResDirs, String[] overlayDirs,
Adam Lesinski082614c2016-03-04 14:33:47 -08002176 String[] libDirs, int displayId, LoadedApk pkgInfo) {
2177 return mResourcesManager.getResources(null, resDir, splitResDirs, overlayDirs, libDirs,
2178 displayId, null, pkgInfo.getCompatibilityInfo(), pkgInfo.getClassLoader());
Todd Kennedy39bfee52016-02-24 10:28:21 -08002179 }
2180
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002181 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002182 final Handler getHandler() {
2183 return mH;
2184 }
2185
Mathew Inwood8c854f82018-09-14 12:35:36 +01002186 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Todd Kennedy233a0b12018-01-29 20:30:24 +00002187 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
2188 int flags) {
2189 return getPackageInfo(packageName, compatInfo, flags, UserHandle.myUserId());
Amith Yamasani98edc952012-09-25 14:09:27 -07002190 }
2191
Todd Kennedy233a0b12018-01-29 20:30:24 +00002192 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
2193 int flags, int userId) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002194 final boolean differentUser = (UserHandle.myUserId() != userId);
Winson83708c82019-02-19 12:34:17 -08002195 ApplicationInfo ai;
2196 try {
2197 ai = getPackageManager().getApplicationInfo(packageName,
2198 PackageManager.GET_SHARED_LIBRARY_FILES
2199 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2200 (userId < 0) ? UserHandle.myUserId() : userId);
2201 } catch (RemoteException e) {
2202 throw e.rethrowFromSystemServer();
2203 }
2204
Craig Mautner88c05892013-06-28 09:47:45 -07002205 synchronized (mResourcesManager) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002206 WeakReference<LoadedApk> ref;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002207 if (differentUser) {
2208 // Caching not supported across users
2209 ref = null;
2210 } else if ((flags & Context.CONTEXT_INCLUDE_CODE) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211 ref = mPackages.get(packageName);
2212 } else {
2213 ref = mResourcePackages.get(packageName);
2214 }
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002215
Todd Kennedy233a0b12018-01-29 20:30:24 +00002216 LoadedApk packageInfo = ref != null ? ref.get() : null;
Winson71cf3502019-04-09 18:00:08 -07002217 if (ai != null && packageInfo != null) {
2218 if (!isLoadedApkResourceDirsUpToDate(packageInfo, ai)) {
2219 packageInfo.updateApplicationInfo(ai, null);
2220 }
2221
Todd Kennedy233a0b12018-01-29 20:30:24 +00002222 if (packageInfo.isSecurityViolation()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
2224 throw new SecurityException(
2225 "Requesting code from " + packageName
2226 + " to be run in process "
2227 + mBoundApplication.processName
2228 + "/" + mBoundApplication.appInfo.uid);
2229 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00002230 return packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002231 }
2232 }
2233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 if (ai != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002235 return getPackageInfo(ai, compatInfo, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002236 }
2237
2238 return null;
2239 }
2240
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002241 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +00002242 public final LoadedApk getPackageInfo(ApplicationInfo ai, CompatibilityInfo compatInfo,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002243 int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
2245 boolean securityViolation = includeCode && ai.uid != 0
2246 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002247 ? !UserHandle.isSameApp(ai.uid, mBoundApplication.appInfo.uid)
Amith Yamasani742a6712011-05-04 14:49:28 -07002248 : true);
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002249 boolean registerPackage = includeCode && (flags&Context.CONTEXT_REGISTER_PACKAGE) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 if ((flags&(Context.CONTEXT_INCLUDE_CODE
2251 |Context.CONTEXT_IGNORE_SECURITY))
2252 == Context.CONTEXT_INCLUDE_CODE) {
2253 if (securityViolation) {
2254 String msg = "Requesting code from " + ai.packageName
2255 + " (with uid " + ai.uid + ")";
2256 if (mBoundApplication != null) {
2257 msg = msg + " to be run in process "
2258 + mBoundApplication.processName + " (with uid "
2259 + mBoundApplication.appInfo.uid + ")";
2260 }
2261 throw new SecurityException(msg);
2262 }
2263 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00002264 return getPackageInfo(ai, compatInfo, null, securityViolation, includeCode,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002265 registerPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 }
2267
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002268 @Override
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002269 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +00002270 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002271 CompatibilityInfo compatInfo) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002272 return getPackageInfo(ai, compatInfo, null, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273 }
2274
Mathew Inwood8c854f82018-09-14 12:35:36 +01002275 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Todd Kennedy233a0b12018-01-29 20:30:24 +00002276 public final LoadedApk peekPackageInfo(String packageName, boolean includeCode) {
Craig Mautner88c05892013-06-28 09:47:45 -07002277 synchronized (mResourcesManager) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002278 WeakReference<LoadedApk> ref;
2279 if (includeCode) {
2280 ref = mPackages.get(packageName);
2281 } else {
2282 ref = mResourcePackages.get(packageName);
2283 }
2284 return ref != null ? ref.get() : null;
2285 }
2286 }
2287
Todd Kennedy233a0b12018-01-29 20:30:24 +00002288 private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002289 ClassLoader baseLoader, boolean securityViolation, boolean includeCode,
2290 boolean registerPackage) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002291 final boolean differentUser = (UserHandle.myUserId() != UserHandle.getUserId(aInfo.uid));
Craig Mautner88c05892013-06-28 09:47:45 -07002292 synchronized (mResourcesManager) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002293 WeakReference<LoadedApk> ref;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002294 if (differentUser) {
2295 // Caching not supported across users
2296 ref = null;
2297 } else if (includeCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002298 ref = mPackages.get(aInfo.packageName);
2299 } else {
2300 ref = mResourcePackages.get(aInfo.packageName);
2301 }
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002302
Todd Kennedy233a0b12018-01-29 20:30:24 +00002303 LoadedApk packageInfo = ref != null ? ref.get() : null;
Winson83708c82019-02-19 12:34:17 -08002304
Winson71cf3502019-04-09 18:00:08 -07002305 if (packageInfo != null) {
2306 if (!isLoadedApkResourceDirsUpToDate(packageInfo, aInfo)) {
2307 packageInfo.updateApplicationInfo(aInfo, null);
2308 }
Winson83708c82019-02-19 12:34:17 -08002309
Winson83708c82019-02-19 12:34:17 -08002310 return packageInfo;
2311 }
2312
2313 if (localLOGV) {
2314 Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 : "Loading resource-only package ") + aInfo.packageName
2316 + " (in " + (mBoundApplication != null
Winson83708c82019-02-19 12:34:17 -08002317 ? mBoundApplication.processName : null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319 }
Winson83708c82019-02-19 12:34:17 -08002320
2321 packageInfo =
2322 new LoadedApk(this, aInfo, compatInfo, baseLoader,
2323 securityViolation, includeCode
2324 && (aInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0, registerPackage);
2325
2326 if (mSystemThread && "android".equals(aInfo.packageName)) {
2327 packageInfo.installSystemApplicationInfo(aInfo,
2328 getSystemContext().mPackageInfo.getClassLoader());
2329 }
2330
2331 if (differentUser) {
2332 // Caching not supported across users
2333 } else if (includeCode) {
2334 mPackages.put(aInfo.packageName,
2335 new WeakReference<LoadedApk>(packageInfo));
2336 } else {
2337 mResourcePackages.put(aInfo.packageName,
2338 new WeakReference<LoadedApk>(packageInfo));
2339 }
2340
Todd Kennedy233a0b12018-01-29 20:30:24 +00002341 return packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 }
2343 }
2344
Winson71cf3502019-04-09 18:00:08 -07002345 private static boolean isLoadedApkResourceDirsUpToDate(LoadedApk loadedApk,
2346 ApplicationInfo appInfo) {
Winson83708c82019-02-19 12:34:17 -08002347 Resources packageResources = loadedApk.mResources;
2348 String[] overlayDirs = ArrayUtils.defeatNullable(loadedApk.getOverlayDirs());
2349 String[] resourceDirs = ArrayUtils.defeatNullable(appInfo.resourceDirs);
2350
2351 return (packageResources == null || packageResources.getAssets().isUpToDate())
2352 && overlayDirs.length == resourceDirs.length
2353 && ArrayUtils.containsAll(overlayDirs, resourceDirs);
2354 }
2355
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002356 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357 ActivityThread() {
Craig Mautner88c05892013-06-28 09:47:45 -07002358 mResourcesManager = ResourcesManager.getInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 }
2360
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002361 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002362 public ApplicationThread getApplicationThread()
2363 {
2364 return mAppThread;
2365 }
2366
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002367 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 public Instrumentation getInstrumentation()
2369 {
2370 return mInstrumentation;
2371 }
2372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 public boolean isProfiling() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002374 return mProfiler != null && mProfiler.profileFile != null
2375 && mProfiler.profileFd == null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 }
2377
2378 public String getProfileFilePath() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002379 return mProfiler.profileFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380 }
2381
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002382 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002383 public Looper getLooper() {
2384 return mLooper;
2385 }
2386
Jeff Sharkey8439ac02017-12-12 17:26:23 -07002387 public Executor getExecutor() {
2388 return mExecutor;
2389 }
2390
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002391 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 public Application getApplication() {
2393 return mInitialApplication;
2394 }
Bob Leee5408332009-09-04 18:31:17 -07002395
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002396 @UnsupportedAppUsage
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07002397 public String getProcessName() {
2398 return mBoundApplication.processName;
2399 }
Bob Leee5408332009-09-04 18:31:17 -07002400
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002401 @UnsupportedAppUsage
Dianne Hackborn21556372010-02-04 16:34:40 -08002402 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 synchronized (this) {
2404 if (mSystemContext == null) {
Jeff Browndefd4a62014-03-10 21:24:37 -07002405 mSystemContext = ContextImpl.createSystemContext(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406 }
Jeff Browndefd4a62014-03-10 21:24:37 -07002407 return mSystemContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 }
2410
Adam Lesinskia82b6262017-03-21 16:56:17 -07002411 public ContextImpl getSystemUiContext() {
2412 synchronized (this) {
2413 if (mSystemUiContext == null) {
Adam Lesinski6f1a9172017-04-10 16:35:19 -07002414 mSystemUiContext = ContextImpl.createSystemUiContext(getSystemContext());
Adam Lesinskia82b6262017-03-21 16:56:17 -07002415 }
2416 return mSystemUiContext;
2417 }
2418 }
2419
lumark0b05f9e2018-11-26 15:09:06 +08002420 /**
2421 * Create the context instance base on system resources & display information which used for UI.
2422 * @param displayId The ID of the display where the UI is shown.
2423 * @see ContextImpl#createSystemUiContext(ContextImpl, int)
2424 */
2425 public ContextImpl createSystemUiContext(int displayId) {
2426 return ContextImpl.createSystemUiContext(getSystemUiContext(), displayId);
2427 }
2428
Narayan Kamath29564cd2014-08-07 10:57:40 +01002429 public void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
Mike Cleron432b7132009-09-24 15:28:29 -07002430 synchronized (this) {
Narayan Kamath29564cd2014-08-07 10:57:40 +01002431 getSystemContext().installSystemApplicationInfo(info, classLoader);
Adam Lesinskia82b6262017-03-21 16:56:17 -07002432 getSystemUiContext().installSystemApplicationInfo(info, classLoader);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002433
2434 // give ourselves a default profiler
2435 mProfiler = new Profiler();
Mike Cleron432b7132009-09-24 15:28:29 -07002436 }
2437 }
2438
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002439 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440 void scheduleGcIdler() {
2441 if (!mGcIdlerScheduled) {
2442 mGcIdlerScheduled = true;
2443 Looper.myQueue().addIdleHandler(mGcIdler);
2444 }
2445 mH.removeMessages(H.GC_WHEN_IDLE);
2446 }
2447
2448 void unscheduleGcIdler() {
2449 if (mGcIdlerScheduled) {
2450 mGcIdlerScheduled = false;
2451 Looper.myQueue().removeIdleHandler(mGcIdler);
2452 }
2453 mH.removeMessages(H.GC_WHEN_IDLE);
2454 }
2455
Tim Murray59f3dc12018-10-22 15:26:08 -07002456 void schedulePurgeIdler() {
2457 if (!mPurgeIdlerScheduled) {
2458 mPurgeIdlerScheduled = true;
2459 Looper.myQueue().addIdleHandler(mPurgeIdler);
2460 }
2461 mH.removeMessages(H.PURGE_RESOURCES);
2462 }
2463
2464 void unschedulePurgeIdler() {
2465 if (mPurgeIdlerScheduled) {
2466 mPurgeIdlerScheduled = false;
2467 Looper.myQueue().removeIdleHandler(mPurgeIdler);
2468 }
2469 mH.removeMessages(H.PURGE_RESOURCES);
2470 }
2471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472 void doGcIfNeeded() {
Makoto Onuki0a9ee1a2019-06-19 08:58:02 -07002473 doGcIfNeeded("bg");
2474 }
2475
2476 void doGcIfNeeded(String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 mGcIdlerScheduled = false;
2478 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002479 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 // + "m now=" + now);
2481 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002482 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
Makoto Onuki0a9ee1a2019-06-19 08:58:02 -07002483 BinderInternal.forceGc(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 }
2485 }
2486
Dianne Hackborne77187d2013-10-25 16:32:41 -07002487 private static final String HEAP_FULL_COLUMN
2488 = "%13s %8s %8s %8s %8s %8s %8s %8s %8s %8s %8s";
2489 private static final String HEAP_COLUMN
2490 = "%13s %8s %8s %8s %8s %8s %8s %8s";
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002491 private static final String ONE_COUNT_COLUMN = "%21s %8d";
2492 private static final String TWO_COUNT_COLUMNS = "%21s %8d %21s %8d";
2493 private static final String ONE_COUNT_COLUMN_HEADER = "%21s %8s";
Dianne Hackborne77187d2013-10-25 16:32:41 -07002494
2495 // Formatting for checkin service - update version if row format changes
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002496 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 4;
Dianne Hackborne77187d2013-10-25 16:32:41 -07002497
2498 static void printRow(PrintWriter pw, String format, Object...objs) {
2499 pw.println(String.format(format, objs));
2500 }
2501
2502 public static void dumpMemInfoTable(PrintWriter pw, Debug.MemoryInfo memInfo, boolean checkin,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002503 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
2504 int pid, String processName,
Dianne Hackborne77187d2013-10-25 16:32:41 -07002505 long nativeMax, long nativeAllocated, long nativeFree,
2506 long dalvikMax, long dalvikAllocated, long dalvikFree) {
2507
2508 // For checkin, we print one long comma-separated list of values
2509 if (checkin) {
2510 // NOTE: if you change anything significant below, also consider changing
2511 // ACTIVITY_THREAD_CHECKIN_VERSION.
2512
2513 // Header
2514 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
2515 pw.print(pid); pw.print(',');
2516 pw.print(processName); pw.print(',');
2517
2518 // Heap info - max
2519 pw.print(nativeMax); pw.print(',');
2520 pw.print(dalvikMax); pw.print(',');
2521 pw.print("N/A,");
2522 pw.print(nativeMax + dalvikMax); pw.print(',');
2523
2524 // Heap info - allocated
2525 pw.print(nativeAllocated); pw.print(',');
2526 pw.print(dalvikAllocated); pw.print(',');
2527 pw.print("N/A,");
2528 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
2529
2530 // Heap info - free
2531 pw.print(nativeFree); pw.print(',');
2532 pw.print(dalvikFree); pw.print(',');
2533 pw.print("N/A,");
2534 pw.print(nativeFree + dalvikFree); pw.print(',');
2535
2536 // Heap info - proportional set size
2537 pw.print(memInfo.nativePss); pw.print(',');
2538 pw.print(memInfo.dalvikPss); pw.print(',');
2539 pw.print(memInfo.otherPss); pw.print(',');
2540 pw.print(memInfo.getTotalPss()); pw.print(',');
2541
2542 // Heap info - swappable set size
2543 pw.print(memInfo.nativeSwappablePss); pw.print(',');
2544 pw.print(memInfo.dalvikSwappablePss); pw.print(',');
2545 pw.print(memInfo.otherSwappablePss); pw.print(',');
2546 pw.print(memInfo.getTotalSwappablePss()); pw.print(',');
2547
2548 // Heap info - shared dirty
2549 pw.print(memInfo.nativeSharedDirty); pw.print(',');
2550 pw.print(memInfo.dalvikSharedDirty); pw.print(',');
2551 pw.print(memInfo.otherSharedDirty); pw.print(',');
2552 pw.print(memInfo.getTotalSharedDirty()); pw.print(',');
2553
2554 // Heap info - shared clean
2555 pw.print(memInfo.nativeSharedClean); pw.print(',');
2556 pw.print(memInfo.dalvikSharedClean); pw.print(',');
2557 pw.print(memInfo.otherSharedClean); pw.print(',');
2558 pw.print(memInfo.getTotalSharedClean()); pw.print(',');
2559
2560 // Heap info - private Dirty
2561 pw.print(memInfo.nativePrivateDirty); pw.print(',');
2562 pw.print(memInfo.dalvikPrivateDirty); pw.print(',');
2563 pw.print(memInfo.otherPrivateDirty); pw.print(',');
2564 pw.print(memInfo.getTotalPrivateDirty()); pw.print(',');
2565
2566 // Heap info - private Clean
2567 pw.print(memInfo.nativePrivateClean); pw.print(',');
2568 pw.print(memInfo.dalvikPrivateClean); pw.print(',');
2569 pw.print(memInfo.otherPrivateClean); pw.print(',');
2570 pw.print(memInfo.getTotalPrivateClean()); pw.print(',');
2571
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002572 // Heap info - swapped out
2573 pw.print(memInfo.nativeSwappedOut); pw.print(',');
2574 pw.print(memInfo.dalvikSwappedOut); pw.print(',');
2575 pw.print(memInfo.otherSwappedOut); pw.print(',');
2576 pw.print(memInfo.getTotalSwappedOut()); pw.print(',');
2577
2578 // Heap info - swapped out pss
2579 if (memInfo.hasSwappedOutPss) {
2580 pw.print(memInfo.nativeSwappedOutPss); pw.print(',');
2581 pw.print(memInfo.dalvikSwappedOutPss); pw.print(',');
2582 pw.print(memInfo.otherSwappedOutPss); pw.print(',');
2583 pw.print(memInfo.getTotalSwappedOutPss()); pw.print(',');
2584 } else {
2585 pw.print("N/A,");
2586 pw.print("N/A,");
2587 pw.print("N/A,");
2588 pw.print("N/A,");
2589 }
2590
Dianne Hackborne77187d2013-10-25 16:32:41 -07002591 // Heap info - other areas
2592 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
2593 pw.print(Debug.MemoryInfo.getOtherLabel(i)); pw.print(',');
2594 pw.print(memInfo.getOtherPss(i)); pw.print(',');
2595 pw.print(memInfo.getOtherSwappablePss(i)); pw.print(',');
2596 pw.print(memInfo.getOtherSharedDirty(i)); pw.print(',');
2597 pw.print(memInfo.getOtherSharedClean(i)); pw.print(',');
2598 pw.print(memInfo.getOtherPrivateDirty(i)); pw.print(',');
2599 pw.print(memInfo.getOtherPrivateClean(i)); pw.print(',');
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002600 pw.print(memInfo.getOtherSwappedOut(i)); pw.print(',');
2601 if (memInfo.hasSwappedOutPss) {
2602 pw.print(memInfo.getOtherSwappedOutPss(i)); pw.print(',');
2603 } else {
2604 pw.print("N/A,");
2605 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002606 }
2607 return;
2608 }
2609
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002610 if (!dumpSummaryOnly) {
2611 if (dumpFullInfo) {
2612 printRow(pw, HEAP_FULL_COLUMN, "", "Pss", "Pss", "Shared", "Private",
Martijn Coenene0764852016-01-07 17:04:22 -08002613 "Shared", "Private", memInfo.hasSwappedOutPss ? "SwapPss" : "Swap",
2614 "Heap", "Heap", "Heap");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002615 printRow(pw, HEAP_FULL_COLUMN, "", "Total", "Clean", "Dirty", "Dirty",
Martijn Coenene0764852016-01-07 17:04:22 -08002616 "Clean", "Clean", "Dirty",
2617 "Size", "Alloc", "Free");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002618 printRow(pw, HEAP_FULL_COLUMN, "", "------", "------", "------", "------",
2619 "------", "------", "------", "------", "------", "------");
2620 printRow(pw, HEAP_FULL_COLUMN, "Native Heap", memInfo.nativePss,
2621 memInfo.nativeSwappablePss, memInfo.nativeSharedDirty,
2622 memInfo.nativePrivateDirty, memInfo.nativeSharedClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002623 memInfo.nativePrivateClean, memInfo.hasSwappedOutPss ?
Richard Uhler91702eb32017-06-23 16:54:25 +01002624 memInfo.nativeSwappedOutPss : memInfo.nativeSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002625 nativeMax, nativeAllocated, nativeFree);
2626 printRow(pw, HEAP_FULL_COLUMN, "Dalvik Heap", memInfo.dalvikPss,
2627 memInfo.dalvikSwappablePss, memInfo.dalvikSharedDirty,
2628 memInfo.dalvikPrivateDirty, memInfo.dalvikSharedClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002629 memInfo.dalvikPrivateClean, memInfo.hasSwappedOutPss ?
Richard Uhler91702eb32017-06-23 16:54:25 +01002630 memInfo.dalvikSwappedOutPss : memInfo.dalvikSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002631 dalvikMax, dalvikAllocated, dalvikFree);
2632 } else {
2633 printRow(pw, HEAP_COLUMN, "", "Pss", "Private",
Martijn Coenene0764852016-01-07 17:04:22 -08002634 "Private", memInfo.hasSwappedOutPss ? "SwapPss" : "Swap",
2635 "Heap", "Heap", "Heap");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002636 printRow(pw, HEAP_COLUMN, "", "Total", "Dirty",
2637 "Clean", "Dirty", "Size", "Alloc", "Free");
2638 printRow(pw, HEAP_COLUMN, "", "------", "------", "------",
2639 "------", "------", "------", "------", "------");
2640 printRow(pw, HEAP_COLUMN, "Native Heap", memInfo.nativePss,
2641 memInfo.nativePrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002642 memInfo.nativePrivateClean,
2643 memInfo.hasSwappedOutPss ? memInfo.nativeSwappedOutPss :
2644 memInfo.nativeSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002645 nativeMax, nativeAllocated, nativeFree);
2646 printRow(pw, HEAP_COLUMN, "Dalvik Heap", memInfo.dalvikPss,
2647 memInfo.dalvikPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002648 memInfo.dalvikPrivateClean,
2649 memInfo.hasSwappedOutPss ? memInfo.dalvikSwappedOutPss :
2650 memInfo.dalvikSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002651 dalvikMax, dalvikAllocated, dalvikFree);
Dianne Hackborne77187d2013-10-25 16:32:41 -07002652 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002653
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002654 int otherPss = memInfo.otherPss;
2655 int otherSwappablePss = memInfo.otherSwappablePss;
2656 int otherSharedDirty = memInfo.otherSharedDirty;
2657 int otherPrivateDirty = memInfo.otherPrivateDirty;
2658 int otherSharedClean = memInfo.otherSharedClean;
2659 int otherPrivateClean = memInfo.otherPrivateClean;
2660 int otherSwappedOut = memInfo.otherSwappedOut;
Martijn Coenene0764852016-01-07 17:04:22 -08002661 int otherSwappedOutPss = memInfo.otherSwappedOutPss;
Dianne Hackborne77187d2013-10-25 16:32:41 -07002662
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002663 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
Dianne Hackborne77187d2013-10-25 16:32:41 -07002664 final int myPss = memInfo.getOtherPss(i);
2665 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2666 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2667 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2668 final int mySharedClean = memInfo.getOtherSharedClean(i);
2669 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2670 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
Martijn Coenene0764852016-01-07 17:04:22 -08002671 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Dianne Hackborne77187d2013-10-25 16:32:41 -07002672 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
Martijn Coenene0764852016-01-07 17:04:22 -08002673 || mySharedClean != 0 || myPrivateClean != 0
2674 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Dianne Hackborne77187d2013-10-25 16:32:41 -07002675 if (dumpFullInfo) {
2676 printRow(pw, HEAP_FULL_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2677 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002678 mySharedClean, myPrivateClean,
2679 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2680 "", "", "");
Dianne Hackborne77187d2013-10-25 16:32:41 -07002681 } else {
2682 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2683 myPss, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002684 myPrivateClean,
2685 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2686 "", "", "");
Dianne Hackborne77187d2013-10-25 16:32:41 -07002687 }
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002688 otherPss -= myPss;
2689 otherSwappablePss -= mySwappablePss;
2690 otherSharedDirty -= mySharedDirty;
2691 otherPrivateDirty -= myPrivateDirty;
2692 otherSharedClean -= mySharedClean;
2693 otherPrivateClean -= myPrivateClean;
2694 otherSwappedOut -= mySwappedOut;
Martijn Coenene0764852016-01-07 17:04:22 -08002695 otherSwappedOutPss -= mySwappedOutPss;
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002696 }
2697 }
2698
2699 if (dumpFullInfo) {
2700 printRow(pw, HEAP_FULL_COLUMN, "Unknown", otherPss, otherSwappablePss,
2701 otherSharedDirty, otherPrivateDirty, otherSharedClean, otherPrivateClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002702 memInfo.hasSwappedOutPss ? otherSwappedOutPss : otherSwappedOut,
2703 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002704 printRow(pw, HEAP_FULL_COLUMN, "TOTAL", memInfo.getTotalPss(),
2705 memInfo.getTotalSwappablePss(),
2706 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
2707 memInfo.getTotalSharedClean(), memInfo.getTotalPrivateClean(),
Thierry Strudel9b511602016-02-25 17:46:38 -08002708 memInfo.hasSwappedOutPss ? memInfo.getTotalSwappedOutPss() :
2709 memInfo.getTotalSwappedOut(),
Martijn Coenene0764852016-01-07 17:04:22 -08002710 nativeMax+dalvikMax, nativeAllocated+dalvikAllocated,
2711 nativeFree+dalvikFree);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002712 } else {
2713 printRow(pw, HEAP_COLUMN, "Unknown", otherPss,
Martijn Coenene0764852016-01-07 17:04:22 -08002714 otherPrivateDirty, otherPrivateClean,
2715 memInfo.hasSwappedOutPss ? otherSwappedOutPss : otherSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002716 "", "", "");
2717 printRow(pw, HEAP_COLUMN, "TOTAL", memInfo.getTotalPss(),
2718 memInfo.getTotalPrivateDirty(),
2719 memInfo.getTotalPrivateClean(),
Martijn Coenene0764852016-01-07 17:04:22 -08002720 memInfo.hasSwappedOutPss ? memInfo.getTotalSwappedOutPss() :
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002721 memInfo.getTotalSwappedOut(),
2722 nativeMax+dalvikMax,
2723 nativeAllocated+dalvikAllocated, nativeFree+dalvikFree);
2724 }
2725
2726 if (dumpDalvik) {
2727 pw.println(" ");
2728 pw.println(" Dalvik Details");
2729
2730 for (int i=Debug.MemoryInfo.NUM_OTHER_STATS;
2731 i<Debug.MemoryInfo.NUM_OTHER_STATS + Debug.MemoryInfo.NUM_DVK_STATS; i++) {
2732 final int myPss = memInfo.getOtherPss(i);
2733 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2734 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2735 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2736 final int mySharedClean = memInfo.getOtherSharedClean(i);
2737 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2738 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
Martijn Coenene0764852016-01-07 17:04:22 -08002739 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002740 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
Martijn Coenene0764852016-01-07 17:04:22 -08002741 || mySharedClean != 0 || myPrivateClean != 0
2742 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002743 if (dumpFullInfo) {
2744 printRow(pw, HEAP_FULL_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2745 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002746 mySharedClean, myPrivateClean,
2747 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2748 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002749 } else {
2750 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2751 myPss, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002752 myPrivateClean,
2753 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2754 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002755 }
2756 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002757 }
2758 }
2759 }
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002760
2761 pw.println(" ");
2762 pw.println(" App Summary");
2763 printRow(pw, ONE_COUNT_COLUMN_HEADER, "", "Pss(KB)");
2764 printRow(pw, ONE_COUNT_COLUMN_HEADER, "", "------");
2765 printRow(pw, ONE_COUNT_COLUMN,
2766 "Java Heap:", memInfo.getSummaryJavaHeap());
2767 printRow(pw, ONE_COUNT_COLUMN,
2768 "Native Heap:", memInfo.getSummaryNativeHeap());
2769 printRow(pw, ONE_COUNT_COLUMN,
2770 "Code:", memInfo.getSummaryCode());
2771 printRow(pw, ONE_COUNT_COLUMN,
2772 "Stack:", memInfo.getSummaryStack());
2773 printRow(pw, ONE_COUNT_COLUMN,
2774 "Graphics:", memInfo.getSummaryGraphics());
2775 printRow(pw, ONE_COUNT_COLUMN,
2776 "Private Other:", memInfo.getSummaryPrivateOther());
2777 printRow(pw, ONE_COUNT_COLUMN,
2778 "System:", memInfo.getSummarySystem());
2779 pw.println(" ");
Martijn Coenene0764852016-01-07 17:04:22 -08002780 if (memInfo.hasSwappedOutPss) {
2781 printRow(pw, TWO_COUNT_COLUMNS,
2782 "TOTAL:", memInfo.getSummaryTotalPss(),
2783 "TOTAL SWAP PSS:", memInfo.getSummaryTotalSwapPss());
2784 } else {
2785 printRow(pw, TWO_COUNT_COLUMNS,
2786 "TOTAL:", memInfo.getSummaryTotalPss(),
2787 "TOTAL SWAP (KB):", memInfo.getSummaryTotalSwap());
2788 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002789 }
2790
Kweku Adams598e9a22017-11-02 17:12:20 -07002791 /**
2792 * Dump heap info to proto.
2793 *
2794 * @param hasSwappedOutPss determines whether to use dirtySwap or dirtySwapPss
2795 */
Kweku Adams983829f2017-12-06 14:53:50 -08002796 private static void dumpMemoryInfo(ProtoOutputStream proto, long fieldId, String name,
Kweku Adams598e9a22017-11-02 17:12:20 -07002797 int pss, int cleanPss, int sharedDirty, int privateDirty,
2798 int sharedClean, int privateClean,
2799 boolean hasSwappedOutPss, int dirtySwap, int dirtySwapPss) {
2800 final long token = proto.start(fieldId);
2801
Yi Jin2b30f322018-02-20 15:41:47 -08002802 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.NAME, name);
2803 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.TOTAL_PSS_KB, pss);
2804 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.CLEAN_PSS_KB, cleanPss);
2805 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.SHARED_DIRTY_KB, sharedDirty);
2806 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.PRIVATE_DIRTY_KB, privateDirty);
2807 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.SHARED_CLEAN_KB, sharedClean);
2808 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.PRIVATE_CLEAN_KB, privateClean);
Kweku Adams598e9a22017-11-02 17:12:20 -07002809 if (hasSwappedOutPss) {
Yi Jin2b30f322018-02-20 15:41:47 -08002810 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.DIRTY_SWAP_PSS_KB, dirtySwapPss);
Kweku Adams598e9a22017-11-02 17:12:20 -07002811 } else {
Yi Jin2b30f322018-02-20 15:41:47 -08002812 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.DIRTY_SWAP_KB, dirtySwap);
Kweku Adams598e9a22017-11-02 17:12:20 -07002813 }
2814
2815 proto.end(token);
2816 }
2817
2818 /**
2819 * Dump mem info data to proto.
2820 */
2821 public static void dumpMemInfoTable(ProtoOutputStream proto, Debug.MemoryInfo memInfo,
2822 boolean dumpDalvik, boolean dumpSummaryOnly,
2823 long nativeMax, long nativeAllocated, long nativeFree,
2824 long dalvikMax, long dalvikAllocated, long dalvikFree) {
2825
2826 if (!dumpSummaryOnly) {
Yi Jin2b30f322018-02-20 15:41:47 -08002827 final long nhToken = proto.start(MemInfoDumpProto.ProcessMemory.NATIVE_HEAP);
2828 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "Native Heap",
Kweku Adams598e9a22017-11-02 17:12:20 -07002829 memInfo.nativePss, memInfo.nativeSwappablePss, memInfo.nativeSharedDirty,
2830 memInfo.nativePrivateDirty, memInfo.nativeSharedClean,
2831 memInfo.nativePrivateClean, memInfo.hasSwappedOutPss,
2832 memInfo.nativeSwappedOut, memInfo.nativeSwappedOutPss);
Yi Jin2b30f322018-02-20 15:41:47 -08002833 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB, nativeMax);
2834 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB, nativeAllocated);
2835 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB, nativeFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002836 proto.end(nhToken);
2837
Yi Jin2b30f322018-02-20 15:41:47 -08002838 final long dvToken = proto.start(MemInfoDumpProto.ProcessMemory.DALVIK_HEAP);
2839 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "Dalvik Heap",
Kweku Adams598e9a22017-11-02 17:12:20 -07002840 memInfo.dalvikPss, memInfo.dalvikSwappablePss, memInfo.dalvikSharedDirty,
2841 memInfo.dalvikPrivateDirty, memInfo.dalvikSharedClean,
2842 memInfo.dalvikPrivateClean, memInfo.hasSwappedOutPss,
2843 memInfo.dalvikSwappedOut, memInfo.dalvikSwappedOutPss);
Yi Jin2b30f322018-02-20 15:41:47 -08002844 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB, dalvikMax);
2845 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB, dalvikAllocated);
2846 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB, dalvikFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002847 proto.end(dvToken);
2848
2849 int otherPss = memInfo.otherPss;
2850 int otherSwappablePss = memInfo.otherSwappablePss;
2851 int otherSharedDirty = memInfo.otherSharedDirty;
2852 int otherPrivateDirty = memInfo.otherPrivateDirty;
2853 int otherSharedClean = memInfo.otherSharedClean;
2854 int otherPrivateClean = memInfo.otherPrivateClean;
2855 int otherSwappedOut = memInfo.otherSwappedOut;
2856 int otherSwappedOutPss = memInfo.otherSwappedOutPss;
2857
2858 for (int i = 0; i < Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
2859 final int myPss = memInfo.getOtherPss(i);
2860 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2861 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2862 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2863 final int mySharedClean = memInfo.getOtherSharedClean(i);
2864 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2865 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
2866 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
2867 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
2868 || mySharedClean != 0 || myPrivateClean != 0
2869 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Yi Jin2b30f322018-02-20 15:41:47 -08002870 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.OTHER_HEAPS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002871 Debug.MemoryInfo.getOtherLabel(i),
2872 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
2873 mySharedClean, myPrivateClean,
2874 memInfo.hasSwappedOutPss, mySwappedOut, mySwappedOutPss);
2875
2876 otherPss -= myPss;
2877 otherSwappablePss -= mySwappablePss;
2878 otherSharedDirty -= mySharedDirty;
2879 otherPrivateDirty -= myPrivateDirty;
2880 otherSharedClean -= mySharedClean;
2881 otherPrivateClean -= myPrivateClean;
2882 otherSwappedOut -= mySwappedOut;
2883 otherSwappedOutPss -= mySwappedOutPss;
2884 }
2885 }
2886
Yi Jin2b30f322018-02-20 15:41:47 -08002887 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.UNKNOWN_HEAP, "Unknown",
Kweku Adams598e9a22017-11-02 17:12:20 -07002888 otherPss, otherSwappablePss,
2889 otherSharedDirty, otherPrivateDirty, otherSharedClean, otherPrivateClean,
2890 memInfo.hasSwappedOutPss, otherSwappedOut, otherSwappedOutPss);
Yi Jin2b30f322018-02-20 15:41:47 -08002891 final long tToken = proto.start(MemInfoDumpProto.ProcessMemory.TOTAL_HEAP);
2892 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "TOTAL",
Kweku Adams598e9a22017-11-02 17:12:20 -07002893 memInfo.getTotalPss(), memInfo.getTotalSwappablePss(),
2894 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
2895 memInfo.getTotalSharedClean(), memInfo.getTotalPrivateClean(),
2896 memInfo.hasSwappedOutPss, memInfo.getTotalSwappedOut(),
2897 memInfo.getTotalSwappedOutPss());
Yi Jin2b30f322018-02-20 15:41:47 -08002898 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB,
2899 nativeMax + dalvikMax);
2900 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002901 nativeAllocated + dalvikAllocated);
Yi Jin2b30f322018-02-20 15:41:47 -08002902 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB,
2903 nativeFree + dalvikFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002904 proto.end(tToken);
2905
2906 if (dumpDalvik) {
2907 for (int i = Debug.MemoryInfo.NUM_OTHER_STATS;
2908 i < Debug.MemoryInfo.NUM_OTHER_STATS + Debug.MemoryInfo.NUM_DVK_STATS;
2909 i++) {
2910 final int myPss = memInfo.getOtherPss(i);
2911 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2912 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2913 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2914 final int mySharedClean = memInfo.getOtherSharedClean(i);
2915 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2916 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
2917 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
2918 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
2919 || mySharedClean != 0 || myPrivateClean != 0
2920 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Yi Jin2b30f322018-02-20 15:41:47 -08002921 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.DALVIK_DETAILS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002922 Debug.MemoryInfo.getOtherLabel(i),
2923 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
2924 mySharedClean, myPrivateClean,
2925 memInfo.hasSwappedOutPss, mySwappedOut, mySwappedOutPss);
2926 }
2927 }
2928 }
2929 }
2930
Yi Jin2b30f322018-02-20 15:41:47 -08002931 final long asToken = proto.start(MemInfoDumpProto.ProcessMemory.APP_SUMMARY);
2932 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.JAVA_HEAP_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002933 memInfo.getSummaryJavaHeap());
Yi Jin2b30f322018-02-20 15:41:47 -08002934 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.NATIVE_HEAP_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002935 memInfo.getSummaryNativeHeap());
Yi Jin2b30f322018-02-20 15:41:47 -08002936 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.CODE_PSS_KB,
2937 memInfo.getSummaryCode());
2938 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.STACK_PSS_KB,
2939 memInfo.getSummaryStack());
2940 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.GRAPHICS_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002941 memInfo.getSummaryGraphics());
Yi Jin2b30f322018-02-20 15:41:47 -08002942 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.PRIVATE_OTHER_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002943 memInfo.getSummaryPrivateOther());
Yi Jin2b30f322018-02-20 15:41:47 -08002944 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.SYSTEM_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002945 memInfo.getSummarySystem());
2946 if (memInfo.hasSwappedOutPss) {
Yi Jin2b30f322018-02-20 15:41:47 -08002947 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.TOTAL_SWAP_PSS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002948 memInfo.getSummaryTotalSwapPss());
2949 } else {
Yi Jin2b30f322018-02-20 15:41:47 -08002950 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.TOTAL_SWAP_PSS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002951 memInfo.getSummaryTotalSwap());
2952 }
2953 proto.end(asToken);
2954 }
2955
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002956 @UnsupportedAppUsage
Jeff Hamilton52d32032011-01-08 15:31:26 -06002957 public void registerOnActivityPausedListener(Activity activity,
2958 OnActivityPausedListener listener) {
2959 synchronized (mOnPauseListeners) {
2960 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
2961 if (list == null) {
2962 list = new ArrayList<OnActivityPausedListener>();
2963 mOnPauseListeners.put(activity, list);
2964 }
2965 list.add(listener);
2966 }
2967 }
2968
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002969 @UnsupportedAppUsage
Jeff Hamiltonce3224c2011-01-17 11:05:03 -08002970 public void unregisterOnActivityPausedListener(Activity activity,
2971 OnActivityPausedListener listener) {
2972 synchronized (mOnPauseListeners) {
2973 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
2974 if (list != null) {
2975 list.remove(listener);
2976 }
2977 }
2978 }
2979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 public final ActivityInfo resolveActivityInfo(Intent intent) {
2981 ActivityInfo aInfo = intent.resolveActivityInfo(
2982 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
2983 if (aInfo == null) {
2984 // Throw an exception.
2985 Instrumentation.checkStartActivityResult(
Dianne Hackborna4972e92012-03-14 10:38:05 -07002986 ActivityManager.START_CLASS_NOT_FOUND, intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002987 }
2988 return aInfo;
2989 }
Bob Leee5408332009-09-04 18:31:17 -07002990
Mathew Inwood8c854f82018-09-14 12:35:36 +01002991 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002993 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Sunny Goyald40c3452019-03-20 12:46:55 -07002994 Activity.NonConfigurationInstances lastNonConfigurationInstances, IBinder assistToken) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002995 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002996 r.token = token;
Sunny Goyald40c3452019-03-20 12:46:55 -07002997 r.assistToken = assistToken;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002998 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002999 r.intent = intent;
3000 r.state = state;
3001 r.parent = parent;
3002 r.embeddedID = id;
3003 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003004 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003005 if (localLOGV) {
3006 ComponentName compname = intent.getComponent();
3007 String name;
3008 if (compname != null) {
3009 name = compname.toShortString();
3010 } else {
3011 name = "(Intent " + intent + ").getComponent() returned null";
3012 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003013 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003014 + ", comp=" + name
3015 + ", token=" + token);
3016 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003017 // TODO(lifecycler): Can't switch to use #handleLaunchActivity() because it will try to
3018 // call #reportSizeConfigurations(), but the server might not know anything about the
3019 // activity if it was launched from LocalAcvitivyManager.
Andrii Kulian770c4032018-05-02 18:40:59 -07003020 return performLaunchActivity(r, null /* customIntent */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 }
3022
Mathew Inwood61e8ae62018-08-14 14:17:44 +01003023 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003024 public final Activity getActivity(IBinder token) {
Andrii Kuliand56ed0c2018-06-14 12:22:18 -07003025 final ActivityClientRecord activityRecord = mActivities.get(token);
3026 return activityRecord != null ? activityRecord.activity : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003027 }
3028
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003029 @Override
3030 public ActivityClientRecord getActivityClient(IBinder token) {
3031 return mActivities.get(token);
3032 }
3033
Riddle Hsu50e34002019-04-12 20:42:05 +08003034 @Override
3035 public void updatePendingConfiguration(Configuration config) {
3036 synchronized (mResourcesManager) {
3037 if (mPendingConfiguration == null || mPendingConfiguration.isOtherSeqNewer(config)) {
3038 mPendingConfiguration = config;
3039 }
3040 }
3041 }
3042
3043 @Override
3044 public void updateProcessState(int processState, boolean fromIpc) {
3045 synchronized (mAppThread) {
3046 if (mLastProcessState == processState) {
3047 return;
3048 }
3049 mLastProcessState = processState;
3050 // Defer the top state for VM to avoid aggressive JIT compilation affecting activity
3051 // launch time.
3052 if (processState == ActivityManager.PROCESS_STATE_TOP
3053 && mNumLaunchingActivities.get() > 0) {
3054 mPendingProcessState = processState;
3055 mH.postDelayed(this::applyPendingProcessState, PENDING_TOP_PROCESS_STATE_TIMEOUT);
3056 } else {
3057 mPendingProcessState = PROCESS_STATE_UNKNOWN;
3058 updateVmProcessState(processState);
3059 }
3060 if (localLOGV) {
3061 Slog.i(TAG, "******************* PROCESS STATE CHANGED TO: " + processState
3062 + (fromIpc ? " (from ipc" : ""));
3063 }
3064 }
3065 }
3066
3067 /** Update VM state based on ActivityManager.PROCESS_STATE_* constants. */
3068 private void updateVmProcessState(int processState) {
3069 // TODO: Tune this since things like gmail sync are important background but not jank
3070 // perceptible.
3071 final int state = processState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
3072 ? VM_PROCESS_STATE_JANK_PERCEPTIBLE
3073 : VM_PROCESS_STATE_JANK_IMPERCEPTIBLE;
3074 VMRuntime.getRuntime().updateProcessState(state);
3075 }
3076
3077 private void applyPendingProcessState() {
3078 synchronized (mAppThread) {
3079 if (mPendingProcessState == PROCESS_STATE_UNKNOWN) {
3080 return;
3081 }
3082 final int pendingState = mPendingProcessState;
3083 mPendingProcessState = PROCESS_STATE_UNKNOWN;
3084 // Only apply the pending state if the last state doesn't change.
3085 if (pendingState == mLastProcessState) {
3086 updateVmProcessState(pendingState);
3087 }
3088 }
3089 }
3090
3091 @Override
3092 public void countLaunchingActivities(int num) {
3093 mNumLaunchingActivities.getAndAdd(num);
3094 }
3095
Mathew Inwood61e8ae62018-08-14 14:17:44 +01003096 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 public final void sendActivityResult(
3098 IBinder token, String id, int requestCode,
3099 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003100 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07003101 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3103 list.add(new ResultInfo(id, requestCode, resultCode, data));
Andrii Kulian9c5ea9c2017-12-07 09:31:01 -08003104 final ClientTransaction clientTransaction = ClientTransaction.obtain(mAppThread, token);
3105 clientTransaction.addCallback(ActivityResultItem.obtain(list));
Andrii Kulian446e8242017-10-26 15:17:29 -07003106 try {
3107 mAppThread.scheduleTransaction(clientTransaction);
3108 } catch (RemoteException e) {
3109 // Local scheduling
3110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003111 }
3112
Andrii Kulian914aa7d2018-03-19 21:51:53 -07003113 @Override
3114 TransactionExecutor getTransactionExecutor() {
3115 return mTransactionExecutor;
3116 }
3117
Andrii Kulian446e8242017-10-26 15:17:29 -07003118 void sendMessage(int what, Object obj) {
Jeff Brown9ef09972013-10-15 20:49:59 -07003119 sendMessage(what, obj, 0, 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003120 }
3121
Jeff Brown9ef09972013-10-15 20:49:59 -07003122 private void sendMessage(int what, Object obj, int arg1) {
3123 sendMessage(what, obj, arg1, 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003124 }
3125
Jeff Brown9ef09972013-10-15 20:49:59 -07003126 private void sendMessage(int what, Object obj, int arg1, int arg2) {
3127 sendMessage(what, obj, arg1, arg2, false);
3128 }
3129
3130 private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
Kweku Adams4af1b502019-05-23 16:23:48 -07003131 if (DEBUG_MESSAGES) {
3132 Slog.v(TAG,
3133 "SCHEDULE " + what + " " + mH.codeToString(what) + ": " + arg1 + " / " + obj);
3134 }
Jeff Brown9ef09972013-10-15 20:49:59 -07003135 Message msg = Message.obtain();
3136 msg.what = what;
3137 msg.obj = obj;
3138 msg.arg1 = arg1;
3139 msg.arg2 = arg2;
3140 if (async) {
3141 msg.setAsynchronous(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 }
Jeff Brown9ef09972013-10-15 20:49:59 -07003143 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003144 }
3145
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07003146 private void sendMessage(int what, Object obj, int arg1, int arg2, int seq) {
3147 if (DEBUG_MESSAGES) Slog.v(
3148 TAG, "SCHEDULE " + mH.codeToString(what) + " arg1=" + arg1 + " arg2=" + arg2 +
3149 "seq= " + seq);
3150 Message msg = Message.obtain();
3151 msg.what = what;
3152 SomeArgs args = SomeArgs.obtain();
3153 args.arg1 = obj;
3154 args.argi1 = arg1;
3155 args.argi2 = arg2;
3156 args.argi3 = seq;
3157 msg.obj = args;
3158 mH.sendMessage(msg);
3159 }
3160
Dianne Hackborn21556372010-02-04 16:34:40 -08003161 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003162 String what) {
3163 ContextCleanupInfo cci = new ContextCleanupInfo();
3164 cci.context = context;
3165 cci.who = who;
3166 cci.what = what;
Jeff Brown9ef09972013-10-15 20:49:59 -07003167 sendMessage(H.CLEAN_UP_CONTEXT, cci);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003168 }
3169
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003170 /** Core implementation of activity launch. */
Andrii Kulian770c4032018-05-02 18:40:59 -07003171 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003172 ActivityInfo aInfo = r.activityInfo;
Todd Kennedy233a0b12018-01-29 20:30:24 +00003173 if (r.packageInfo == null) {
3174 r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003175 Context.CONTEXT_INCLUDE_CODE);
3176 }
Bob Leee5408332009-09-04 18:31:17 -07003177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 ComponentName component = r.intent.getComponent();
3179 if (component == null) {
3180 component = r.intent.resolveActivity(
3181 mInitialApplication.getPackageManager());
3182 r.intent.setComponent(component);
3183 }
3184
3185 if (r.activityInfo.targetActivity != null) {
3186 component = new ComponentName(r.activityInfo.packageName,
3187 r.activityInfo.targetActivity);
3188 }
3189
Adam Lesinski4e862812016-11-21 16:02:24 -08003190 ContextImpl appContext = createBaseContextForActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191 Activity activity = null;
3192 try {
Adam Lesinski4e862812016-11-21 16:02:24 -08003193 java.lang.ClassLoader cl = appContext.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04003194 activity = mInstrumentation.newActivity(
3195 cl, component.getClassName(), r.intent);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003196 StrictMode.incrementExpectedActivityCount(activity.getClass());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197 r.intent.setExtrasClassLoader(cl);
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003198 r.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 if (r.state != null) {
3200 r.state.setClassLoader(cl);
3201 }
3202 } catch (Exception e) {
3203 if (!mInstrumentation.onException(activity, e)) {
3204 throw new RuntimeException(
3205 "Unable to instantiate activity " + component
3206 + ": " + e.toString(), e);
3207 }
3208 }
3209
3210 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00003211 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07003212
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003213 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
3214 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003215 TAG, r + ": app=" + app
3216 + ", appName=" + app.getPackageName()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003217 + ", pkg=" + r.packageInfo.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003218 + ", comp=" + r.intent.getComponent().toShortString()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003219 + ", dir=" + r.packageInfo.getAppDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220
3221 if (activity != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003223 Configuration config = new Configuration(mCompatConfiguration);
Andrii Kuliand0ad9382016-04-18 20:54:20 -07003224 if (r.overrideConfig != null) {
3225 config.updateFrom(r.overrideConfig);
3226 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003227 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003228 + r.activityInfo.name + " with config " + config);
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003229 Window window = null;
3230 if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
3231 window = r.mPendingRemoveWindow;
3232 r.mPendingRemoveWindow = null;
3233 r.mPendingRemoveWindowManager = null;
3234 }
Adam Lesinski4e862812016-11-21 16:02:24 -08003235 appContext.setOuterContext(activity);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003236 activity.attach(appContext, this, getInstrumentation(), r.token,
3237 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Craig Mautner233ceee2014-05-09 17:05:11 -07003238 r.embeddedID, r.lastNonConfigurationInstances, config,
Sunny Goyald40c3452019-03-20 12:46:55 -07003239 r.referrer, r.voiceInteractor, window, r.configCallback,
3240 r.assistToken);
Bob Leee5408332009-09-04 18:31:17 -07003241
Andrii Kulian770c4032018-05-02 18:40:59 -07003242 if (customIntent != null) {
3243 activity.mIntent = customIntent;
3244 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003245 r.lastNonConfigurationInstances = null;
Sudheer Shanka84a48952017-03-08 18:19:01 -08003246 checkAndBlockForNetworkAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247 activity.mStartedActivity = false;
3248 int theme = r.activityInfo.getThemeResource();
3249 if (theme != 0) {
3250 activity.setTheme(theme);
3251 }
3252
3253 activity.mCalled = false;
Craig Mautnera0026042014-04-23 11:45:37 -07003254 if (r.isPersistable()) {
3255 mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
3256 } else {
3257 mInstrumentation.callActivityOnCreate(activity, r.state);
3258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 if (!activity.mCalled) {
3260 throw new SuperNotCalledException(
3261 "Activity " + r.intent.getComponent().toShortString() +
3262 " did not call through to super.onCreate()");
3263 }
3264 r.activity = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003266 r.setState(ON_CREATE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267
Garfield Tan0443b372019-01-04 15:00:13 -08003268 // updatePendingActivityConfiguration() reads from mActivities to update
3269 // ActivityClientRecord which runs in a different thread. Protect modifications to
3270 // mActivities to avoid race.
3271 synchronized (mResourcesManager) {
3272 mActivities.put(r.token, r);
3273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274
3275 } catch (SuperNotCalledException e) {
3276 throw e;
3277
3278 } catch (Exception e) {
3279 if (!mInstrumentation.onException(activity, e)) {
3280 throw new RuntimeException(
3281 "Unable to start activity " + component
3282 + ": " + e.toString(), e);
3283 }
3284 }
3285
3286 return activity;
3287 }
3288
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003289 @Override
3290 public void handleStartActivity(ActivityClientRecord r,
3291 PendingTransactionActions pendingActions) {
3292 final Activity activity = r.activity;
3293 if (r.activity == null) {
3294 // TODO(lifecycler): What do we do in this case?
3295 return;
3296 }
3297 if (!r.stopped) {
3298 throw new IllegalStateException("Can't start activity that is not stopped.");
3299 }
Andrii Kulian0f3356c2019-03-18 21:34:40 +00003300 if (r.activity.mFinished) {
3301 // TODO(lifecycler): How can this happen?
3302 return;
3303 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003304
3305 // Start
Andrii Kuliand25680c2018-02-21 15:16:58 -08003306 activity.performStart("handleStartActivity");
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003307 r.setState(ON_START);
3308
3309 if (pendingActions == null) {
3310 // No more work to do.
3311 return;
3312 }
3313
3314 // Restore instance state
3315 if (pendingActions.shouldRestoreInstanceState()) {
3316 if (r.isPersistable()) {
3317 if (r.state != null || r.persistentState != null) {
3318 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
3319 r.persistentState);
3320 }
3321 } else if (r.state != null) {
3322 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
3323 }
3324 }
3325
3326 // Call postOnCreate()
3327 if (pendingActions.shouldCallOnPostCreate()) {
3328 activity.mCalled = false;
3329 if (r.isPersistable()) {
3330 mInstrumentation.callActivityOnPostCreate(activity, r.state,
3331 r.persistentState);
3332 } else {
3333 mInstrumentation.callActivityOnPostCreate(activity, r.state);
3334 }
3335 if (!activity.mCalled) {
3336 throw new SuperNotCalledException(
3337 "Activity " + r.intent.getComponent().toShortString()
3338 + " did not call through to super.onPostCreate()");
3339 }
3340 }
3341 }
3342
Sudheer Shanka84a48952017-03-08 18:19:01 -08003343 /**
3344 * Checks if {@link #mNetworkBlockSeq} is {@link #INVALID_PROC_STATE_SEQ} and if so, returns
3345 * immediately. Otherwise, makes a blocking call to ActivityManagerService to wait for the
3346 * network rules to get updated.
3347 */
3348 private void checkAndBlockForNetworkAccess() {
3349 synchronized (mNetworkPolicyLock) {
3350 if (mNetworkBlockSeq != INVALID_PROC_STATE_SEQ) {
3351 try {
3352 ActivityManager.getService().waitForNetworkStateUpdate(mNetworkBlockSeq);
3353 mNetworkBlockSeq = INVALID_PROC_STATE_SEQ;
3354 } catch (RemoteException ignored) {}
3355 }
3356 }
3357 }
3358
Adam Lesinski4e862812016-11-21 16:02:24 -08003359 private ContextImpl createBaseContextForActivity(ActivityClientRecord r) {
3360 final int displayId;
Craig Mautnere0a38842013-12-16 16:14:02 -08003361 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003362 displayId = ActivityTaskManager.getService().getActivityDisplayId(r.token);
Craig Mautnere0a38842013-12-16 16:14:02 -08003363 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003364 throw e.rethrowFromSystemServer();
Craig Mautnere0a38842013-12-16 16:14:02 -08003365 }
Jeff Brownefd43bd2012-09-21 17:02:35 -07003366
Wale Ogunwale7c726682015-02-06 17:34:28 -08003367 ContextImpl appContext = ContextImpl.createActivityContext(
Todd Kennedy233a0b12018-01-29 20:30:24 +00003368 this, r.packageInfo, r.activityInfo, r.token, displayId, r.overrideConfig);
Wale Ogunwale7c726682015-02-06 17:34:28 -08003369
3370 final DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance();
Jeff Brownefd43bd2012-09-21 17:02:35 -07003371 // For debugging purposes, if the activity's package name contains the value of
3372 // the "debug.use-second-display" system property as a substring, then show
3373 // its content on a secondary display if there is one.
Jeff Brownefd43bd2012-09-21 17:02:35 -07003374 String pkgName = SystemProperties.get("debug.second-display.pkg");
3375 if (pkgName != null && !pkgName.isEmpty()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003376 && r.packageInfo.mPackageName.contains(pkgName)) {
Wale Ogunwale7c726682015-02-06 17:34:28 -08003377 for (int id : dm.getDisplayIds()) {
3378 if (id != Display.DEFAULT_DISPLAY) {
Wale Ogunwale26698512015-06-05 16:55:33 -07003379 Display display =
Bryce Lee609bf652017-02-09 16:50:13 -08003380 dm.getCompatibleDisplay(id, appContext.getResources());
Adam Lesinski4e862812016-11-21 16:02:24 -08003381 appContext = (ContextImpl) appContext.createDisplayContext(display);
Jeff Brownefd43bd2012-09-21 17:02:35 -07003382 break;
3383 }
3384 }
3385 }
Adam Lesinski4e862812016-11-21 16:02:24 -08003386 return appContext;
Jeff Brownefd43bd2012-09-21 17:02:35 -07003387 }
3388
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003389 /**
3390 * Extended implementation of activity launch. Used when server requests a launch or relaunch.
3391 */
Andrii Kulian446e8242017-10-26 15:17:29 -07003392 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003393 public Activity handleLaunchActivity(ActivityClientRecord r,
Andrii Kulian770c4032018-05-02 18:40:59 -07003394 PendingTransactionActions pendingActions, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 // If we are getting ready to gc after going to the background, well
3396 // we are back active so skip it.
3397 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003398 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003399
Jeff Hao1b012d32014-08-20 10:35:34 -07003400 if (r.profilerInfo != null) {
3401 mProfiler.setProfiler(r.profilerInfo);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003402 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003403 }
3404
Dianne Hackborn58f42a52011-10-10 13:46:34 -07003405 // Make sure we are running with the most recent config.
3406 handleConfigurationChanged(null, null);
3407
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003408 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003409 TAG, "Handling launch of " + r);
Adam Powellcfbe9be2013-11-06 14:58:58 -08003410
Chet Haase0d1c27a2014-11-03 18:35:16 +00003411 // Initialize before creating the activity
Stan Iliev898123b2019-02-14 14:57:44 -05003412 if (!ThreadedRenderer.sRendererDisabled
3413 && (r.activityInfo.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
3414 HardwareRenderer.preload();
Jesse Hallc37984f2017-05-23 16:55:08 -07003415 }
Chet Haase0d1c27a2014-11-03 18:35:16 +00003416 WindowManagerGlobal.initialize();
3417
Yiwei Zhange54faf52019-05-08 18:43:11 -07003418 // Hint the GraphicsEnvironment that an activity is launching on the process.
3419 GraphicsEnvironment.hintActivityLaunch();
3420
Andrii Kulian770c4032018-05-02 18:40:59 -07003421 final Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422
3423 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003424 r.createdConfig = new Configuration(mConfiguration);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003425 reportSizeConfigurations(r);
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003426 if (!r.activity.mFinished && pendingActions != null) {
3427 pendingActions.setOldState(r.state);
3428 pendingActions.setRestoreInstanceState(true);
3429 pendingActions.setCallOnPostCreate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 }
3431 } else {
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07003432 // 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 -08003433 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003434 ActivityTaskManager.getService()
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003435 .finishActivity(r.token, Activity.RESULT_CANCELED, null,
3436 Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003438 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003439 }
3440 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003441
3442 return a;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 }
3444
Filip Gruszczynski23493322015-07-29 17:02:59 -07003445 private void reportSizeConfigurations(ActivityClientRecord r) {
Riddle Hsu66b74a82018-07-26 00:20:12 +08003446 if (mActivitiesToBeDestroyed.containsKey(r.token)) {
3447 // Size configurations of a destroyed activity is meaningless.
3448 return;
3449 }
Filip Gruszczynski23493322015-07-29 17:02:59 -07003450 Configuration[] configurations = r.activity.getResources().getSizeConfigurations();
3451 if (configurations == null) {
3452 return;
3453 }
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003454 SparseIntArray horizontal = new SparseIntArray();
3455 SparseIntArray vertical = new SparseIntArray();
3456 SparseIntArray smallest = new SparseIntArray();
Filip Gruszczynski23493322015-07-29 17:02:59 -07003457 for (int i = configurations.length - 1; i >= 0; i--) {
3458 Configuration config = configurations[i];
3459 if (config.screenHeightDp != Configuration.SCREEN_HEIGHT_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003460 vertical.put(config.screenHeightDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003461 }
3462 if (config.screenWidthDp != Configuration.SCREEN_WIDTH_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003463 horizontal.put(config.screenWidthDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003464 }
3465 if (config.smallestScreenWidthDp != Configuration.SMALLEST_SCREEN_WIDTH_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003466 smallest.put(config.smallestScreenWidthDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003467 }
3468 }
Filip Gruszczynski23493322015-07-29 17:02:59 -07003469 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003470 ActivityTaskManager.getService().reportSizeConfigurations(r.token,
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003471 horizontal.copyKeys(), vertical.copyKeys(), smallest.copyKeys());
Filip Gruszczynski23493322015-07-29 17:02:59 -07003472 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003473 throw ex.rethrowFromSystemServer();
Filip Gruszczynski23493322015-07-29 17:02:59 -07003474 }
Filip Gruszczynski23493322015-07-29 17:02:59 -07003475 }
3476
Dianne Hackborn85d558c2014-11-04 10:31:54 -08003477 private void deliverNewIntents(ActivityClientRecord r, List<ReferrerIntent> intents) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 final int N = intents.size();
3479 for (int i=0; i<N; i++) {
Dianne Hackborna01a0fa2014-12-02 10:33:14 -08003480 ReferrerIntent intent = intents.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481 intent.setExtrasClassLoader(r.activity.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003482 intent.prepareToEnterProcess();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003483 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
3485 }
3486 }
3487
Louis Chang92d16522019-02-27 12:56:18 +08003488 @Override
3489 public void handleNewIntent(IBinder token, List<ReferrerIntent> intents) {
Wale Ogunwale826c7062016-09-13 08:25:54 -07003490 final ActivityClientRecord r = mActivities.get(token);
3491 if (r == null) {
3492 return;
3493 }
3494
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07003495 checkAndBlockForNetworkAccess();
Wale Ogunwale826c7062016-09-13 08:25:54 -07003496 deliverNewIntents(r, intents);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497 }
3498
Adam Skorydfc7fd72013-08-05 19:23:41 -07003499 public void handleRequestAssistContextExtras(RequestAssistContextExtras cmd) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003500 // Filling for autofill has a few differences:
Felipe Leme1ca634a2016-11-28 17:21:21 -08003501 // - it does not need an AssistContent
3502 // - it does not call onProvideAssistData()
3503 // - it needs an IAutoFillCallback
Felipe Leme640f30a2017-03-06 15:44:06 -08003504 boolean forAutofill = cmd.requestType == ActivityManager.ASSIST_CONTEXT_AUTOFILL;
Felipe Leme1ca634a2016-11-28 17:21:21 -08003505
Felipe Leme85d1c2d2017-04-21 08:56:04 -07003506 // TODO: decide if lastSessionId logic applies to autofill sessions
Amith Yamasani4f128e42016-05-10 11:44:12 -07003507 if (mLastSessionId != cmd.sessionId) {
3508 // Clear the existing structures
3509 mLastSessionId = cmd.sessionId;
3510 for (int i = mLastAssistStructures.size() - 1; i >= 0; i--) {
3511 AssistStructure structure = mLastAssistStructures.get(i).get();
3512 if (structure != null) {
3513 structure.clearSendChannel();
3514 }
3515 mLastAssistStructures.remove(i);
Dianne Hackborn782d4982015-07-08 17:36:37 -07003516 }
3517 }
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003518
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003519 Bundle data = new Bundle();
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003520 AssistStructure structure = null;
Felipe Leme640f30a2017-03-06 15:44:06 -08003521 AssistContent content = forAutofill ? null : new AssistContent();
Amith Yamasani858f98d2017-02-22 12:59:53 -08003522 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003523 ActivityClientRecord r = mActivities.get(cmd.activityToken);
Dianne Hackborna3acdb32015-06-08 17:07:40 -07003524 Uri referrer = null;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003525 if (r != null) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003526 if (!forAutofill) {
Felipe Leme1ca634a2016-11-28 17:21:21 -08003527 r.activity.getApplication().dispatchOnProvideAssistData(r.activity, data);
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003528 r.activity.onProvideAssistData(data);
Felipe Leme6d553872016-12-08 17:13:25 -08003529 referrer = r.activity.onProvideReferrer();
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003530 }
Felipe Leme640f30a2017-03-06 15:44:06 -08003531 if (cmd.requestType == ActivityManager.ASSIST_CONTEXT_FULL || forAutofill) {
Svet Ganovfd31f852017-04-26 15:54:27 -07003532 structure = new AssistStructure(r.activity, forAutofill, cmd.flags);
Adam Skory4aaed142015-04-22 11:29:31 -06003533 Intent activityIntent = r.activity.getIntent();
Felipe Leme6d553872016-12-08 17:13:25 -08003534 boolean notSecure = r.window == null ||
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003535 (r.window.getAttributes().flags
Felipe Leme6d553872016-12-08 17:13:25 -08003536 & WindowManager.LayoutParams.FLAG_SECURE) == 0;
3537 if (activityIntent != null && notSecure) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003538 if (!forAutofill) {
Felipe Leme1ca634a2016-11-28 17:21:21 -08003539 Intent intent = new Intent(activityIntent);
3540 intent.setFlags(intent.getFlags() & ~(Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3541 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION));
3542 intent.removeUnsafeExtras();
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003543 content.setDefaultIntent(intent);
3544 }
Adam Skory4aaed142015-04-22 11:29:31 -06003545 } else {
Felipe Leme640f30a2017-03-06 15:44:06 -08003546 if (!forAutofill) {
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003547 content.setDefaultIntent(new Intent());
3548 }
Adam Skory4aaed142015-04-22 11:29:31 -06003549 }
Felipe Leme640f30a2017-03-06 15:44:06 -08003550 if (!forAutofill) {
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003551 r.activity.onProvideAssistContent(content);
3552 }
Dianne Hackborna83ce1d2015-03-11 15:16:13 -07003553 }
Sunny Goyald40c3452019-03-20 12:46:55 -07003554
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003555 }
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003556 if (structure == null) {
3557 structure = new AssistStructure();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003558 }
Felipe Leme0200d9e2017-01-24 15:10:26 -08003559
Felipe Leme85d1c2d2017-04-21 08:56:04 -07003560 // TODO: decide if lastSessionId logic applies to autofill sessions
Amith Yamasani858f98d2017-02-22 12:59:53 -08003561
3562 structure.setAcquisitionStartTime(startTime);
3563 structure.setAcquisitionEndTime(SystemClock.uptimeMillis());
3564
Amith Yamasani4f128e42016-05-10 11:44:12 -07003565 mLastAssistStructures.add(new WeakReference<>(structure));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003566 IActivityTaskManager mgr = ActivityTaskManager.getService();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003567 try {
Dianne Hackborna3acdb32015-06-08 17:07:40 -07003568 mgr.reportAssistContextExtras(cmd.requestToken, data, structure, content, referrer);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003569 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003570 throw e.rethrowFromSystemServer();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003571 }
3572 }
Craig Mautner5eda9b32013-07-02 11:58:16 -07003573
Sunny Goyald40c3452019-03-20 12:46:55 -07003574 /** Fetches the user actions for the corresponding activity */
3575 private void handleRequestDirectActions(@NonNull IBinder activityToken,
Svet Ganov3b6be082019-04-28 10:21:01 -07003576 @NonNull IVoiceInteractor interactor, @NonNull CancellationSignal cancellationSignal,
3577 @NonNull RemoteCallback callback) {
Sunny Goyald40c3452019-03-20 12:46:55 -07003578 final ActivityClientRecord r = mActivities.get(activityToken);
Svet Ganov3b6be082019-04-28 10:21:01 -07003579 if (r == null) {
Felipe Lemeada51842019-05-14 15:19:52 -07003580 Log.w(TAG, "requestDirectActions(): no activity for " + activityToken);
Svet Ganov3b6be082019-04-28 10:21:01 -07003581 callback.sendResult(null);
3582 return;
3583 }
3584 final int lifecycleState = r.getLifecycleState();
3585 if (lifecycleState < ON_START || lifecycleState >= ON_STOP) {
Felipe Lemeada51842019-05-14 15:19:52 -07003586 Log.w(TAG, "requestDirectActions(" + r + "): wrong lifecycle: " + lifecycleState);
Svet Ganov3b6be082019-04-28 10:21:01 -07003587 callback.sendResult(null);
3588 return;
3589 }
3590 if (r.activity.mVoiceInteractor == null
3591 || r.activity.mVoiceInteractor.mInteractor.asBinder()
3592 != interactor.asBinder()) {
3593 if (r.activity.mVoiceInteractor != null) {
3594 r.activity.mVoiceInteractor.destroy();
Sunny Goyald40c3452019-03-20 12:46:55 -07003595 }
Svet Ganov3b6be082019-04-28 10:21:01 -07003596 r.activity.mVoiceInteractor = new VoiceInteractor(interactor, r.activity,
3597 r.activity, Looper.myLooper());
3598 }
3599 r.activity.onGetDirectActions(cancellationSignal, (actions) -> {
Sunny Goyald40c3452019-03-20 12:46:55 -07003600 Preconditions.checkNotNull(actions);
3601 Preconditions.checkCollectionElementsNotNull(actions, "actions");
Svet Ganov3b6be082019-04-28 10:21:01 -07003602 if (!actions.isEmpty()) {
Sunny Goyald40c3452019-03-20 12:46:55 -07003603 final int actionCount = actions.size();
3604 for (int i = 0; i < actionCount; i++) {
3605 final DirectAction action = actions.get(i);
3606 action.setSource(r.activity.getTaskId(), r.activity.getAssistToken());
3607 }
3608 final Bundle result = new Bundle();
3609 result.putParcelable(DirectAction.KEY_ACTIONS_LIST,
3610 new ParceledListSlice<>(actions));
3611 callback.sendResult(result);
Svet Ganov3b6be082019-04-28 10:21:01 -07003612 } else {
3613 callback.sendResult(null);
Sunny Goyald40c3452019-03-20 12:46:55 -07003614 }
Svet Ganov3b6be082019-04-28 10:21:01 -07003615 });
Sunny Goyald40c3452019-03-20 12:46:55 -07003616 }
3617
3618 /** Performs an actions in the corresponding activity */
3619 private void handlePerformDirectAction(@NonNull IBinder activityToken,
3620 @NonNull String actionId, @Nullable Bundle arguments,
3621 @NonNull CancellationSignal cancellationSignal,
3622 @NonNull RemoteCallback resultCallback) {
3623 final ActivityClientRecord r = mActivities.get(activityToken);
3624 if (r != null) {
3625 final int lifecycleState = r.getLifecycleState();
3626 if (lifecycleState < ON_START || lifecycleState >= ON_STOP) {
3627 resultCallback.sendResult(null);
3628 return;
3629 }
3630 final Bundle nonNullArguments = (arguments != null) ? arguments : Bundle.EMPTY;
Sunny Goyald40c3452019-03-20 12:46:55 -07003631 r.activity.onPerformDirectAction(actionId, nonNullArguments, cancellationSignal,
Svet Ganov3b6be082019-04-28 10:21:01 -07003632 resultCallback::sendResult);
3633 } else {
3634 resultCallback.sendResult(null);
Sunny Goyald40c3452019-03-20 12:46:55 -07003635 }
Sunny Goyald40c3452019-03-20 12:46:55 -07003636 }
3637
Craig Mautner5eda9b32013-07-02 11:58:16 -07003638 public void handleTranslucentConversionComplete(IBinder token, boolean drawComplete) {
3639 ActivityClientRecord r = mActivities.get(token);
3640 if (r != null) {
3641 r.activity.onTranslucentConversionComplete(drawComplete);
3642 }
3643 }
3644
Craig Mautnereb8abf72014-07-02 15:04:09 -07003645 public void onNewActivityOptions(IBinder token, ActivityOptions options) {
3646 ActivityClientRecord r = mActivities.get(token);
3647 if (r != null) {
3648 r.activity.onNewActivityOptions(options);
3649 }
3650 }
3651
Jeff Sharkeydd97f422013-10-08 17:01:30 -07003652 public void handleInstallProvider(ProviderInfo info) {
Jeff Sharkeybb2e2ca2014-10-23 11:42:31 -07003653 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3654 try {
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -06003655 installContentProviders(mInitialApplication, Arrays.asList(info));
Jeff Sharkeybb2e2ca2014-10-23 11:42:31 -07003656 } finally {
3657 StrictMode.setThreadPolicy(oldPolicy);
3658 }
Jeff Sharkeydd97f422013-10-08 17:01:30 -07003659 }
3660
Craig Mautner8746a472014-07-24 15:12:54 -07003661 private void handleEnterAnimationComplete(IBinder token) {
3662 ActivityClientRecord r = mActivities.get(token);
3663 if (r != null) {
Filip Gruszczynski6eafa902014-11-14 14:24:37 -08003664 r.activity.dispatchEnterAnimationComplete();
Craig Mautner8746a472014-07-24 15:12:54 -07003665 }
3666 }
3667
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04003668 private void handleStartBinderTracking() {
3669 Binder.enableTracing();
3670 }
3671
3672 private void handleStopBinderTrackingAndDump(ParcelFileDescriptor fd) {
3673 try {
3674 Binder.disableTracing();
3675 Binder.getTransactionTracker().writeTracesToFile(fd);
3676 } finally {
3677 IoUtils.closeQuietly(fd);
3678 Binder.getTransactionTracker().clearTraces();
3679 }
3680 }
3681
Andrii Kulian446e8242017-10-26 15:17:29 -07003682 @Override
3683 public void handleMultiWindowModeChanged(IBinder token, boolean isInMultiWindowMode,
Winson Chung5af42fc2017-03-24 17:11:33 -07003684 Configuration overrideConfig) {
Wale Ogunwale5f986092015-12-04 15:35:38 -08003685 final ActivityClientRecord r = mActivities.get(token);
3686 if (r != null) {
Winson Chung5af42fc2017-03-24 17:11:33 -07003687 final Configuration newConfig = new Configuration(mConfiguration);
3688 if (overrideConfig != null) {
3689 newConfig.updateFrom(overrideConfig);
3690 }
3691 r.activity.dispatchMultiWindowModeChanged(isInMultiWindowMode, newConfig);
Wale Ogunwale5f986092015-12-04 15:35:38 -08003692 }
3693 }
3694
Andrii Kulian446e8242017-10-26 15:17:29 -07003695 @Override
3696 public void handlePictureInPictureModeChanged(IBinder token, boolean isInPipMode,
Winson Chung5af42fc2017-03-24 17:11:33 -07003697 Configuration overrideConfig) {
Wale Ogunwale5f986092015-12-04 15:35:38 -08003698 final ActivityClientRecord r = mActivities.get(token);
3699 if (r != null) {
Winson Chung5af42fc2017-03-24 17:11:33 -07003700 final Configuration newConfig = new Configuration(mConfiguration);
3701 if (overrideConfig != null) {
3702 newConfig.updateFrom(overrideConfig);
3703 }
3704 r.activity.dispatchPictureInPictureModeChanged(isInPipMode, newConfig);
Wale Ogunwale5f986092015-12-04 15:35:38 -08003705 }
3706 }
3707
Amith Yamasani0af6fa72016-01-17 15:36:19 -08003708 private void handleLocalVoiceInteractionStarted(IBinder token, IVoiceInteractor interactor) {
3709 final ActivityClientRecord r = mActivities.get(token);
3710 if (r != null) {
3711 r.voiceInteractor = interactor;
3712 r.activity.setVoiceInteractor(interactor);
3713 if (interactor == null) {
3714 r.activity.onLocalVoiceInteractionStopped();
3715 } else {
3716 r.activity.onLocalVoiceInteractionStarted();
3717 }
3718 }
3719 }
3720
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003721 private static boolean attemptAttachAgent(String agent, ClassLoader classLoader) {
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003722 try {
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003723 VMDebug.attachAgent(agent, classLoader);
3724 return true;
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003725 } catch (IOException e) {
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003726 Slog.e(TAG, "Attaching agent with " + classLoader + " failed: " + agent);
3727 return false;
3728 }
3729 }
3730
3731 static void handleAttachAgent(String agent, LoadedApk loadedApk) {
3732 ClassLoader classLoader = loadedApk != null ? loadedApk.getClassLoader() : null;
3733 if (attemptAttachAgent(agent, classLoader)) {
3734 return;
3735 }
3736 if (classLoader != null) {
3737 attemptAttachAgent(agent, null);
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003738 }
3739 }
3740
Alex Light2d0691c2019-10-03 14:36:57 -07003741 static void handleAttachStartupAgents(String dataDir) {
3742 try {
3743 Path code_cache = ContextImpl.getCodeCacheDirBeforeBind(new File(dataDir)).toPath();
3744 if (!Files.exists(code_cache)) {
3745 return;
3746 }
3747 Path startup_path = code_cache.resolve("startup_agents");
3748 if (Files.exists(startup_path)) {
3749 for (Path p : Files.newDirectoryStream(startup_path)) {
3750 handleAttachAgent(
3751 p.toAbsolutePath().toString()
3752 + "="
3753 + dataDir,
3754 null);
3755 }
3756 }
3757 } catch (Exception e) {
3758 // Ignored.
3759 }
3760 }
3761
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003762 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
3763
3764 /**
3765 * Return the Intent that's currently being handled by a
3766 * BroadcastReceiver on this thread, or null if none.
3767 * @hide
3768 */
3769 public static Intent getIntentBeingBroadcast() {
3770 return sCurrentBroadcastIntent.get();
3771 }
3772
Mathew Inwood31755f92018-12-20 13:53:36 +00003773 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Romain Guy65b345f2011-07-27 18:51:50 -07003774 private void handleReceiver(ReceiverData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003775 // If we are getting ready to gc after going to the background, well
3776 // we are back active so skip it.
3777 unscheduleGcIdler();
3778
3779 String component = data.intent.getComponent().getClassName();
3780
Todd Kennedy233a0b12018-01-29 20:30:24 +00003781 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003782 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003783
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003784 IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003785
Adam Lesinski4e862812016-11-21 16:02:24 -08003786 Application app;
Romain Guy65b345f2011-07-27 18:51:50 -07003787 BroadcastReceiver receiver;
Adam Lesinski4e862812016-11-21 16:02:24 -08003788 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003789 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00003790 app = packageInfo.makeApplication(false, mInstrumentation);
Adam Lesinski4e862812016-11-21 16:02:24 -08003791 context = (ContextImpl) app.getBaseContext();
3792 if (data.info.splitName != null) {
3793 context = (ContextImpl) context.createContextForSplit(data.info.splitName);
3794 }
3795 java.lang.ClassLoader cl = context.getClassLoader();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003796 data.intent.setExtrasClassLoader(cl);
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003797 data.intent.prepareToEnterProcess();
Dianne Hackborne829fef2010-10-26 17:44:01 -07003798 data.setExtrasClassLoader(cl);
Todd Kennedy233a0b12018-01-29 20:30:24 +00003799 receiver = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05003800 .instantiateReceiver(cl, data.info.name, data.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07003802 if (DEBUG_BROADCAST) Slog.i(TAG,
3803 "Finishing failed broadcast to " + data.intent.getComponent());
3804 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 throw new RuntimeException(
3806 "Unable to instantiate receiver " + component
3807 + ": " + e.toString(), e);
3808 }
3809
3810 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003811 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003812 TAG, "Performing receive of " + data.intent
3813 + ": app=" + app
3814 + ", appName=" + app.getPackageName()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003815 + ", pkg=" + packageInfo.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003816 + ", comp=" + data.intent.getComponent().toShortString()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003817 + ", dir=" + packageInfo.getAppDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003818
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003819 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07003820 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003821 receiver.onReceive(context.getReceiverRestrictedContext(),
3822 data.intent);
3823 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07003824 if (DEBUG_BROADCAST) Slog.i(TAG,
3825 "Finishing failed broadcast to " + data.intent.getComponent());
3826 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827 if (!mInstrumentation.onException(receiver, e)) {
3828 throw new RuntimeException(
3829 "Unable to start receiver " + component
3830 + ": " + e.toString(), e);
3831 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003832 } finally {
3833 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 }
3835
Dianne Hackborne829fef2010-10-26 17:44:01 -07003836 if (receiver.getPendingResult() != null) {
3837 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003838 }
3839 }
3840
Christopher Tate181fafa2009-05-14 11:12:14 -07003841 // Instantiate a BackupAgent and tell it that it's alive
Romain Guy65b345f2011-07-27 18:51:50 -07003842 private void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003843 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07003844
Christopher Tate346acb12012-10-15 19:20:25 -07003845 // Sanity check the requested target package's uid against ours
3846 try {
3847 PackageInfo requestedPackage = getPackageManager().getPackageInfo(
3848 data.appInfo.packageName, 0, UserHandle.myUserId());
3849 if (requestedPackage.applicationInfo.uid != Process.myUid()) {
3850 Slog.w(TAG, "Asked to instantiate non-matching package "
3851 + data.appInfo.packageName);
3852 return;
3853 }
3854 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003855 throw e.rethrowFromSystemServer();
Christopher Tate346acb12012-10-15 19:20:25 -07003856 }
3857
Christopher Tate181fafa2009-05-14 11:12:14 -07003858 // no longer idle; we have backup work to do
3859 unscheduleGcIdler();
3860
3861 // instantiate the BackupAgent class named in the manifest
Todd Kennedy233a0b12018-01-29 20:30:24 +00003862 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
3863 String packageName = packageInfo.mPackageName;
Christopher Tate346acb12012-10-15 19:20:25 -07003864 if (packageName == null) {
3865 Slog.d(TAG, "Asked to create backup agent for nonexistent package");
3866 return;
3867 }
3868
Christopher Tate181fafa2009-05-14 11:12:14 -07003869 String classname = data.appInfo.backupAgentName;
Christopher Tate79ec80d2011-06-24 14:58:49 -07003870 // full backup operation but no app-supplied agent? use the default implementation
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003871 if (classname == null && (data.backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL
3872 || data.backupMode == ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL)) {
Christopher Tate4a627c72011-04-01 14:43:32 -07003873 classname = "android.app.backup.FullBackupAgent";
Christopher Tate181fafa2009-05-14 11:12:14 -07003874 }
Christopher Tate4a627c72011-04-01 14:43:32 -07003875
Christopher Tate181fafa2009-05-14 11:12:14 -07003876 try {
Christopher Tated1475e02009-07-09 15:36:17 -07003877 IBinder binder = null;
Annie Mengd5827872019-01-30 20:28:57 +00003878 ArrayMap<String, BackupAgent> backupAgents = getBackupAgentsForUser(data.userId);
3879 BackupAgent agent = backupAgents.get(packageName);
Christopher Tate2e40d112014-07-15 12:37:38 -07003880 if (agent != null) {
3881 // reusing the existing instance
3882 if (DEBUG_BACKUP) {
3883 Slog.v(TAG, "Reusing existing agent instance");
Christopher Tated1475e02009-07-09 15:36:17 -07003884 }
Christopher Tate2e40d112014-07-15 12:37:38 -07003885 binder = agent.onBind();
3886 } else {
3887 try {
3888 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing agent class " + classname);
3889
Todd Kennedy233a0b12018-01-29 20:30:24 +00003890 java.lang.ClassLoader cl = packageInfo.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04003891 agent = (BackupAgent) cl.loadClass(classname).newInstance();
Christopher Tate2e40d112014-07-15 12:37:38 -07003892
3893 // set up the agent's context
Todd Kennedy233a0b12018-01-29 20:30:24 +00003894 ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
Christopher Tate2e40d112014-07-15 12:37:38 -07003895 context.setOuterContext(agent);
3896 agent.attach(context);
3897
Ruslan Tkhakokhov063180f2019-01-28 20:29:46 +00003898 agent.onCreate(UserHandle.of(data.userId));
Christopher Tate2e40d112014-07-15 12:37:38 -07003899 binder = agent.onBind();
Annie Mengd5827872019-01-30 20:28:57 +00003900 backupAgents.put(packageName, agent);
Christopher Tate2e40d112014-07-15 12:37:38 -07003901 } catch (Exception e) {
3902 // If this is during restore, fail silently; otherwise go
3903 // ahead and let the user see the crash.
3904 Slog.e(TAG, "Agent threw during creation: " + e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003905 if (data.backupMode != ApplicationThreadConstants.BACKUP_MODE_RESTORE
3906 && data.backupMode !=
3907 ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL) {
Christopher Tate2e40d112014-07-15 12:37:38 -07003908 throw e;
3909 }
3910 // falling through with 'binder' still null
3911 }
Christopher Tated1475e02009-07-09 15:36:17 -07003912 }
Christopher Tate181fafa2009-05-14 11:12:14 -07003913
3914 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07003915 try {
Annie Mengd5827872019-01-30 20:28:57 +00003916 ActivityManager.getService().backupAgentCreated(packageName, binder, data.userId);
Christopher Tate181fafa2009-05-14 11:12:14 -07003917 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003918 throw e.rethrowFromSystemServer();
Christopher Tate181fafa2009-05-14 11:12:14 -07003919 }
Christopher Tate181fafa2009-05-14 11:12:14 -07003920 } catch (Exception e) {
3921 throw new RuntimeException("Unable to create BackupAgent "
Christopher Tate4a627c72011-04-01 14:43:32 -07003922 + classname + ": " + e.toString(), e);
Christopher Tate181fafa2009-05-14 11:12:14 -07003923 }
3924 }
3925
3926 // Tear down a BackupAgent
Romain Guy65b345f2011-07-27 18:51:50 -07003927 private void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003928 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07003929
Todd Kennedy233a0b12018-01-29 20:30:24 +00003930 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
3931 String packageName = packageInfo.mPackageName;
Annie Mengd5827872019-01-30 20:28:57 +00003932 ArrayMap<String, BackupAgent> backupAgents = getBackupAgentsForUser(data.userId);
3933 BackupAgent agent = backupAgents.get(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07003934 if (agent != null) {
3935 try {
3936 agent.onDestroy();
3937 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003938 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07003939 e.printStackTrace();
3940 }
Annie Mengd5827872019-01-30 20:28:57 +00003941 backupAgents.remove(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07003942 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003943 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07003944 }
3945 }
3946
Annie Mengd5827872019-01-30 20:28:57 +00003947 private ArrayMap<String, BackupAgent> getBackupAgentsForUser(int userId) {
3948 ArrayMap<String, BackupAgent> backupAgents = mBackupAgentsByUser.get(userId);
3949 if (backupAgents == null) {
3950 backupAgents = new ArrayMap<>();
3951 mBackupAgentsByUser.put(userId, backupAgents);
3952 }
3953 return backupAgents;
3954 }
3955
Mathew Inwood61e8ae62018-08-14 14:17:44 +01003956 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07003957 private void handleCreateService(CreateServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 // If we are getting ready to gc after going to the background, well
3959 // we are back active so skip it.
3960 unscheduleGcIdler();
3961
Todd Kennedy233a0b12018-01-29 20:30:24 +00003962 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003963 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964 Service service = null;
3965 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00003966 java.lang.ClassLoader cl = packageInfo.getClassLoader();
3967 service = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05003968 .instantiateService(cl, data.info.name, data.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969 } catch (Exception e) {
3970 if (!mInstrumentation.onException(service, e)) {
3971 throw new RuntimeException(
3972 "Unable to instantiate service " + data.info.name
3973 + ": " + e.toString(), e);
3974 }
3975 }
3976
3977 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003978 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003979
Todd Kennedy233a0b12018-01-29 20:30:24 +00003980 ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
Jeff Browndefd4a62014-03-10 21:24:37 -07003981 context.setOuterContext(service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982
Todd Kennedy233a0b12018-01-29 20:30:24 +00003983 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984 service.attach(context, this, data.info.name, data.token, app,
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003985 ActivityManager.getService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986 service.onCreate();
3987 mServices.put(data.token, service);
3988 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003989 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003990 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003991 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003992 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993 }
3994 } catch (Exception e) {
3995 if (!mInstrumentation.onException(service, e)) {
3996 throw new RuntimeException(
3997 "Unable to create service " + data.info.name
3998 + ": " + e.toString(), e);
3999 }
4000 }
4001 }
4002
Romain Guy65b345f2011-07-27 18:51:50 -07004003 private void handleBindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 Service s = mServices.get(data.token);
Amith Yamasani742a6712011-05-04 14:49:28 -07004005 if (DEBUG_SERVICE)
4006 Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007 if (s != null) {
4008 try {
4009 data.intent.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01004010 data.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 try {
4012 if (!data.rebind) {
4013 IBinder binder = s.onBind(data.intent);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004014 ActivityManager.getService().publishService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004015 data.token, data.intent, binder);
4016 } else {
4017 s.onRebind(data.intent);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004018 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08004019 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 }
4021 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004022 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004023 }
4024 } catch (Exception e) {
4025 if (!mInstrumentation.onException(s, e)) {
4026 throw new RuntimeException(
4027 "Unable to bind to service " + s
4028 + " with " + data.intent + ": " + e.toString(), e);
4029 }
4030 }
4031 }
4032 }
4033
Romain Guy65b345f2011-07-27 18:51:50 -07004034 private void handleUnbindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 Service s = mServices.get(data.token);
4036 if (s != null) {
4037 try {
4038 data.intent.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01004039 data.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040 boolean doRebind = s.onUnbind(data.intent);
4041 try {
4042 if (doRebind) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004043 ActivityManager.getService().unbindFinished(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004044 data.token, data.intent, doRebind);
4045 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004046 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08004047 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 }
4049 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004050 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 }
4052 } catch (Exception e) {
4053 if (!mInstrumentation.onException(s, e)) {
4054 throw new RuntimeException(
4055 "Unable to unbind to service " + s
4056 + " with " + data.intent + ": " + e.toString(), e);
4057 }
4058 }
4059 }
4060 }
4061
Dianne Hackborn625ac272010-09-17 18:29:22 -07004062 private void handleDumpService(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08004063 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
4064 try {
4065 Service s = mServices.get(info.token);
4066 if (s != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07004067 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
4068 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08004069 s.dump(info.fd.getFileDescriptor(), pw, info.args);
4070 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08004072 } finally {
4073 IoUtils.closeQuietly(info.fd);
4074 StrictMode.setThreadPolicy(oldPolicy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004075 }
4076 }
4077
Dianne Hackborn625ac272010-09-17 18:29:22 -07004078 private void handleDumpActivity(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08004079 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
4080 try {
4081 ActivityClientRecord r = mActivities.get(info.token);
4082 if (r != null && r.activity != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07004083 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
4084 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08004085 r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
4086 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07004087 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08004088 } finally {
4089 IoUtils.closeQuietly(info.fd);
4090 StrictMode.setThreadPolicy(oldPolicy);
Dianne Hackborn625ac272010-09-17 18:29:22 -07004091 }
4092 }
4093
Marco Nelissen18cb2872011-11-15 11:19:53 -08004094 private void handleDumpProvider(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08004095 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
4096 try {
4097 ProviderClientRecord r = mLocalProviders.get(info.token);
4098 if (r != null && r.mLocalProvider != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07004099 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
4100 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08004101 r.mLocalProvider.dump(info.fd.getFileDescriptor(), pw, info.args);
4102 pw.flush();
Marco Nelissen18cb2872011-11-15 11:19:53 -08004103 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08004104 } finally {
4105 IoUtils.closeQuietly(info.fd);
4106 StrictMode.setThreadPolicy(oldPolicy);
Marco Nelissen18cb2872011-11-15 11:19:53 -08004107 }
4108 }
4109
Romain Guy65b345f2011-07-27 18:51:50 -07004110 private void handleServiceArgs(ServiceArgsData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004111 Service s = mServices.get(data.token);
4112 if (s != null) {
4113 try {
4114 if (data.args != null) {
4115 data.args.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01004116 data.args.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004117 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004118 int res;
4119 if (!data.taskRemoved) {
4120 res = s.onStartCommand(data.args, data.flags, data.startId);
4121 } else {
4122 s.onTaskRemoved(data.args);
4123 res = Service.START_TASK_REMOVED_COMPLETE;
4124 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07004125
4126 QueuedWork.waitToFinish();
4127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004128 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004129 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08004130 data.token, SERVICE_DONE_EXECUTING_START, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004131 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004132 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004133 }
4134 } catch (Exception e) {
4135 if (!mInstrumentation.onException(s, e)) {
4136 throw new RuntimeException(
4137 "Unable to start service " + s
4138 + " with " + data.args + ": " + e.toString(), e);
4139 }
4140 }
4141 }
4142 }
4143
Romain Guy65b345f2011-07-27 18:51:50 -07004144 private void handleStopService(IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 Service s = mServices.remove(token);
4146 if (s != null) {
4147 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004148 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004149 s.onDestroy();
Amith Yamasani75928252017-05-22 15:10:47 -07004150 s.detachAndCleanUp();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004151 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08004152 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004153 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08004154 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07004156
4157 QueuedWork.waitToFinish();
4158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004160 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08004161 token, SERVICE_DONE_EXECUTING_STOP, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004162 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004163 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 }
4165 } catch (Exception e) {
4166 if (!mInstrumentation.onException(s, e)) {
4167 throw new RuntimeException(
4168 "Unable to stop service " + s
4169 + ": " + e.toString(), e);
4170 }
Craig Mautner66c4a822015-01-16 12:48:16 -08004171 Slog.i(TAG, "handleStopService: exception for " + token, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004172 }
Craig Mautner9776ad42015-01-15 14:38:39 -08004173 } else {
4174 Slog.i(TAG, "handleStopService: token=" + token + " not found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004175 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004176 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004177 }
4178
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004179 /**
4180 * Resume the activity.
4181 * @param token Target activity token.
4182 * @param finalStateRequest Flag indicating if this is part of final state resolution for a
4183 * transaction.
4184 * @param reason Reason for performing the action.
4185 *
4186 * @return The {@link ActivityClientRecord} that was resumed, {@code null} otherwise.
4187 */
4188 @VisibleForTesting
4189 public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
Andrii Kuliandfbf9712018-03-08 15:42:24 -08004190 String reason) {
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004191 final ActivityClientRecord r = mActivities.get(token);
4192 if (localLOGV) {
4193 Slog.v(TAG, "Performing resume of " + r + " finished=" + r.activity.mFinished);
4194 }
Andrii Kulian0f3356c2019-03-18 21:34:40 +00004195 if (r == null || r.activity.mFinished) {
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004196 return null;
4197 }
4198 if (r.getLifecycleState() == ON_RESUME) {
4199 if (!finalStateRequest) {
4200 final RuntimeException e = new IllegalStateException(
4201 "Trying to resume activity which is already resumed");
4202 Slog.e(TAG, e.getMessage(), e);
4203 Slog.e(TAG, r.getStateString());
4204 // TODO(lifecycler): A double resume request is possible when an activity
4205 // receives two consequent transactions with relaunch requests and "resumed"
4206 // final state requests and the second relaunch is omitted. We still try to
4207 // handle two resume requests for the final state. For cases other than this
4208 // one, we don't expect it to happen.
Andrii Kulian9956d892018-02-14 13:48:56 -08004209 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004210 return null;
4211 }
4212 if (finalStateRequest) {
4213 r.hideForNow = false;
4214 r.activity.mStartedActivity = false;
4215 }
4216 try {
4217 r.activity.onStateNotSaved();
4218 r.activity.mFragments.noteStateNotSaved();
4219 checkAndBlockForNetworkAccess();
4220 if (r.pendingIntents != null) {
4221 deliverNewIntents(r, r.pendingIntents);
4222 r.pendingIntents = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004223 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004224 if (r.pendingResults != null) {
Andrii Kuliane55b0092018-04-19 15:29:22 -07004225 deliverResults(r, r.pendingResults, reason);
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004226 r.pendingResults = null;
4227 }
4228 r.activity.performResume(r.startsNotResumed, reason);
Bob Leee5408332009-09-04 18:31:17 -07004229
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004230 r.state = null;
4231 r.persistentState = null;
4232 r.setState(ON_RESUME);
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004233
Andrii Kulian86024012019-04-18 19:41:23 -07004234 reportTopResumedActivityChanged(r, r.isTopResumedActivity, "topWhenResuming");
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004235 } catch (Exception e) {
4236 if (!mInstrumentation.onException(r.activity, e)) {
4237 throw new RuntimeException("Unable to resume activity "
4238 + r.intent.getComponent().toShortString() + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004239 }
4240 }
4241 return r;
4242 }
4243
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004244 static final void cleanUpPendingRemoveWindows(ActivityClientRecord r, boolean force) {
4245 if (r.mPreserveWindow && !force) {
4246 return;
4247 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004248 if (r.mPendingRemoveWindow != null) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004249 r.mPendingRemoveWindowManager.removeViewImmediate(
4250 r.mPendingRemoveWindow.getDecorView());
4251 IBinder wtoken = r.mPendingRemoveWindow.getDecorView().getWindowToken();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004252 if (wtoken != null) {
Jeff Brown98365d72012-08-19 20:30:52 -07004253 WindowManagerGlobal.getInstance().closeAll(wtoken,
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004254 r.activity.getClass().getName(), "Activity");
4255 }
4256 }
4257 r.mPendingRemoveWindow = null;
4258 r.mPendingRemoveWindowManager = null;
4259 }
4260
Andrii Kulian446e8242017-10-26 15:17:29 -07004261 @Override
Andrii Kuliandfbf9712018-03-08 15:42:24 -08004262 public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004263 String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004264 // If we are getting ready to gc after going to the background, well
4265 // we are back active so skip it.
4266 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004267 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004268
Adam Powellcfbe9be2013-11-06 14:58:58 -08004269 // TODO Push resumeArgs into the activity for consideration
Andrii Kuliandfbf9712018-03-08 15:42:24 -08004270 final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004271 if (r == null) {
4272 // We didn't actually resume the activity, so skipping any follow-up actions.
4273 return;
4274 }
Riddle Hsu66b74a82018-07-26 00:20:12 +08004275 if (mActivitiesToBeDestroyed.containsKey(token)) {
4276 // Although the activity is resumed, it is going to be destroyed. So the following
4277 // UI operations are unnecessary and also prevents exception because its token may
4278 // be gone that window manager cannot recognize it. All necessary cleanup actions
4279 // performed below will be done while handling destruction.
4280 return;
4281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004282
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004283 final Activity a = r.activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004284
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004285 if (localLOGV) {
4286 Slog.v(TAG, "Resume " + r + " started activity: " + a.mStartedActivity
4287 + ", hideForNow: " + r.hideForNow + ", finished: " + a.mFinished);
4288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004290 final int forwardBit = isForward
4291 ? WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07004292
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004293 // If the window hasn't yet been added to the window manager,
4294 // and this guy didn't finish itself or start another activity,
4295 // then go ahead and add the window.
4296 boolean willBeVisible = !a.mStartedActivity;
4297 if (!willBeVisible) {
4298 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004299 willBeVisible = ActivityTaskManager.getService().willActivityBeVisible(
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004300 a.getActivityToken());
4301 } catch (RemoteException e) {
4302 throw e.rethrowFromSystemServer();
4303 }
4304 }
4305 if (r.window == null && !a.mFinished && willBeVisible) {
4306 r.window = r.activity.getWindow();
4307 View decor = r.window.getDecorView();
4308 decor.setVisibility(View.INVISIBLE);
4309 ViewManager wm = a.getWindowManager();
4310 WindowManager.LayoutParams l = r.window.getAttributes();
4311 a.mDecor = decor;
4312 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
4313 l.softInputMode |= forwardBit;
4314 if (r.mPreserveWindow) {
4315 a.mWindowAdded = true;
4316 r.mPreserveWindow = false;
4317 // Normally the ViewRoot sets up callbacks with the Activity
4318 // in addView->ViewRootImpl#setView. If we are instead reusing
4319 // the decor view we have to notify the view root that the
4320 // callbacks may have changed.
4321 ViewRootImpl impl = decor.getViewRootImpl();
4322 if (impl != null) {
4323 impl.notifyChildRebuilt();
Dianne Hackborn061d58a2010-03-12 15:07:06 -08004324 }
4325 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004326 if (a.mVisibleFromClient) {
4327 if (!a.mWindowAdded) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004328 a.mWindowAdded = true;
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004329 wm.addView(decor, l);
4330 } else {
4331 // The activity will get a callback for this {@link LayoutParams} change
4332 // earlier. However, at that time the decor will not be set (this is set
4333 // in this method), so no action will be taken. This call ensures the
4334 // callback occurs with the decor set.
4335 a.onWindowAttributesChanged(l);
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004336 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004337 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004338
4339 // If the window has already been added, but during resume
4340 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08004341 // window visible.
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004342 } else if (!willBeVisible) {
4343 if (localLOGV) Slog.v(TAG, "Launch " + r + " mStartedActivity set");
4344 r.hideForNow = true;
4345 }
4346
4347 // Get rid of anything left hanging around.
4348 cleanUpPendingRemoveWindows(r, false /* force */);
4349
4350 // The window is now visible if it has been added, we are not
4351 // simply finishing, and we are not starting another activity.
4352 if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) {
4353 if (r.newConfig != null) {
4354 performConfigurationChangedForActivity(r, r.newConfig);
4355 if (DEBUG_CONFIGURATION) {
4356 Slog.v(TAG, "Resuming activity " + r.activityInfo.name + " with newConfig "
4357 + r.activity.mCurrentConfig);
4358 }
4359 r.newConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004360 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004361 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward=" + isForward);
4362 WindowManager.LayoutParams l = r.window.getAttributes();
4363 if ((l.softInputMode
4364 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
4365 != forwardBit) {
4366 l.softInputMode = (l.softInputMode
4367 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
4368 | forwardBit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004369 if (r.activity.mVisibleFromClient) {
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004370 ViewManager wm = a.getWindowManager();
4371 View decor = r.window.getDecorView();
4372 wm.updateViewLayout(decor, l);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004373 }
4374 }
4375
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004376 r.activity.mVisibleFromServer = true;
4377 mNumVisibleActivities++;
4378 if (r.activity.mVisibleFromClient) {
4379 r.activity.makeVisible();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004380 }
4381 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004382
4383 r.nextIdle = mNewActivities;
4384 mNewActivities = r;
4385 if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);
4386 Looper.myQueue().addIdleHandler(new Idler());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004387 }
4388
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004389
4390 @Override
4391 public void handleTopResumedActivityChanged(IBinder token, boolean onTop, String reason) {
4392 ActivityClientRecord r = mActivities.get(token);
4393 if (r == null || r.activity == null) {
4394 Slog.w(TAG, "Not found target activity to report position change for token: " + token);
4395 return;
4396 }
4397
4398 if (DEBUG_ORDER) {
4399 Slog.d(TAG, "Received position change to top: " + onTop + " for activity: " + r);
4400 }
4401
4402 if (r.isTopResumedActivity == onTop) {
4403 throw new IllegalStateException("Activity top position already set to onTop=" + onTop);
4404 }
4405
4406 r.isTopResumedActivity = onTop;
4407
4408 if (r.getLifecycleState() == ON_RESUME) {
Andrii Kulian86024012019-04-18 19:41:23 -07004409 reportTopResumedActivityChanged(r, onTop, "topStateChangedWhenResumed");
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004410 } else {
4411 if (DEBUG_ORDER) {
4412 Slog.d(TAG, "Won't deliver top position change in state=" + r.getLifecycleState());
4413 }
4414 }
4415 }
4416
4417 /**
4418 * Call {@link Activity#onTopResumedActivityChanged(boolean)} if its top resumed state changed
4419 * since the last report.
4420 */
Andrii Kulian86024012019-04-18 19:41:23 -07004421 private void reportTopResumedActivityChanged(ActivityClientRecord r, boolean onTop,
4422 String reason) {
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004423 if (r.lastReportedTopResumedState != onTop) {
4424 r.lastReportedTopResumedState = onTop;
Andrii Kulian86024012019-04-18 19:41:23 -07004425 r.activity.performTopResumedActivityChanged(onTop, reason);
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004426 }
4427 }
4428
Andrii Kulian446e8242017-10-26 15:17:29 -07004429 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004430 public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
Andrii Kuliana6176e32018-02-27 11:51:18 -08004431 int configChanges, PendingTransactionActions pendingActions, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004432 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004433 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004434 if (userLeaving) {
4435 performUserLeavingActivity(r);
4436 }
Bob Leee5408332009-09-04 18:31:17 -07004437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004438 r.activity.mConfigChangeFlags |= configChanges;
Andrii Kuliand25680c2018-02-21 15:16:58 -08004439 performPauseActivity(r, finished, reason, pendingActions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004440
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07004441 // Make sure any pending writes are now committed.
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004442 if (r.isPreHoneycomb()) {
4443 QueuedWork.waitToFinish();
4444 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004445 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004446 }
4447 }
4448
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004449 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004450 mInstrumentation.callActivityOnUserLeaving(r.activity);
4451 }
4452
Andrii Kulian8ae79572018-01-26 15:36:06 -08004453 final Bundle performPauseActivity(IBinder token, boolean finished, String reason,
4454 PendingTransactionActions pendingActions) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004455 ActivityClientRecord r = mActivities.get(token);
Andrii Kulian8ae79572018-01-26 15:36:06 -08004456 return r != null ? performPauseActivity(r, finished, reason, pendingActions) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004457 }
4458
Andrii Kulian8ae79572018-01-26 15:36:06 -08004459 /**
4460 * Pause the activity.
4461 * @return Saved instance state for pre-Honeycomb apps if it was saved, {@code null} otherwise.
4462 */
4463 private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
4464 PendingTransactionActions pendingActions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004465 if (r.paused) {
Andrii Kulian0f3356c2019-03-18 21:34:40 +00004466 if (r.activity.mFinished) {
4467 // If we are finishing, we won't call onResume() in certain cases.
4468 // So here we likewise don't want to call onPause() if the activity
4469 // isn't resumed.
4470 return null;
4471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004472 RuntimeException e = new RuntimeException(
4473 "Performing pause of activity that is not resumed: "
4474 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004475 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004477 if (finished) {
4478 r.activity.mFinished = true;
4479 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004480
Andrii Kulian8ae79572018-01-26 15:36:06 -08004481 // Pre-Honeycomb apps always save their state before pausing
4482 final boolean shouldSaveState = !r.activity.mFinished && r.isPreHoneycomb();
4483 if (shouldSaveState) {
4484 callActivityOnSaveInstanceState(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485 }
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004486
4487 performPauseActivityIfNeeded(r, reason);
Jeff Hamilton52d32032011-01-08 15:31:26 -06004488
4489 // Notify any outstanding on paused listeners
4490 ArrayList<OnActivityPausedListener> listeners;
4491 synchronized (mOnPauseListeners) {
4492 listeners = mOnPauseListeners.remove(r.activity);
4493 }
4494 int size = (listeners != null ? listeners.size() : 0);
4495 for (int i = 0; i < size; i++) {
4496 listeners.get(i).onPaused(r.activity);
4497 }
4498
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004499 final Bundle oldState = pendingActions != null ? pendingActions.getOldState() : null;
4500 if (oldState != null) {
4501 // We need to keep around the original state, in case we need to be created again.
4502 // But we only do this for pre-Honeycomb apps, which always save their state when
4503 // pausing, so we can not have them save their state when restarting from a paused
4504 // state. For HC and later, we want to (and can) let the state be saved as the
4505 // normal part of stopping the activity.
4506 if (r.isPreHoneycomb()) {
4507 r.state = oldState;
4508 }
4509 }
4510
Andrii Kulian8ae79572018-01-26 15:36:06 -08004511 return shouldSaveState ? r.state : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004512 }
4513
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004514 private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
4515 if (r.paused) {
4516 // You are already paused silly...
4517 return;
4518 }
4519
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004520 // Always reporting top resumed position loss when pausing an activity. If necessary, it
4521 // will be restored in performResumeActivity().
Andrii Kulian86024012019-04-18 19:41:23 -07004522 reportTopResumedActivityChanged(r, false /* onTop */, "pausing");
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004523
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004524 try {
4525 r.activity.mCalled = false;
4526 mInstrumentation.callActivityOnPause(r.activity);
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004527 if (!r.activity.mCalled) {
4528 throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
4529 + " did not call through to super.onPause()");
4530 }
4531 } catch (SuperNotCalledException e) {
4532 throw e;
4533 } catch (Exception e) {
4534 if (!mInstrumentation.onException(r.activity, e)) {
4535 throw new RuntimeException("Unable to pause activity "
4536 + safeToComponentShortString(r.intent) + ": " + e.toString(), e);
4537 }
4538 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004539 r.setState(ON_PAUSE);
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004540 }
4541
Andrii Kulian829829c2018-03-19 18:19:05 -07004542 /** Called from {@link LocalActivityManager}. */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01004543 @UnsupportedAppUsage
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08004544 final void performStopActivity(IBinder token, boolean saveState, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004545 ActivityClientRecord r = mActivities.get(token);
Andrii Kulian829829c2018-03-19 18:19:05 -07004546 performStopActivityInner(r, null /* stopInfo */, false /* keepShown */, saveState,
4547 false /* finalStateRequest */, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004548 }
4549
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004550 private static final class ProviderRefCount {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07004551 public final ContentProviderHolder holder;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004552 public final ProviderClientRecord client;
4553 public int stableCount;
4554 public int unstableCount;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004555
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004556 // When this is set, the stable and unstable ref counts are 0 and
4557 // we have a pending operation scheduled to remove the ref count
4558 // from the activity manager. On the activity manager we are still
4559 // holding an unstable ref, though it is not reflected in the counts
4560 // here.
4561 public boolean removePending;
4562
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07004563 ProviderRefCount(ContentProviderHolder inHolder,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004564 ProviderClientRecord inClient, int sCount, int uCount) {
4565 holder = inHolder;
4566 client = inClient;
4567 stableCount = sCount;
4568 unstableCount = uCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004569 }
4570 }
4571
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004572 /**
4573 * Core implementation of stopping an activity. Note this is a little
4574 * tricky because the server's meaning of stop is slightly different
4575 * than our client -- for the server, stop means to save state and give
4576 * it the result when it is done, but the window may still be visible.
4577 * For the client, we want to call onStop()/onStart() to indicate when
Wale Ogunwaleb5066fe2016-09-21 07:33:43 -07004578 * the activity's UI visibility changes.
Andrii Kulian829829c2018-03-19 18:19:05 -07004579 * @param r Target activity client record.
4580 * @param info Action that will report activity stop to server.
4581 * @param keepShown Flag indicating whether the activity is still shown.
4582 * @param saveState Flag indicating whether the activity state should be saved.
4583 * @param finalStateRequest Flag indicating if this call is handling final lifecycle state
4584 * request for a transaction.
4585 * @param reason Reason for performing this operation.
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004586 */
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004587 private void performStopActivityInner(ActivityClientRecord r, StopInfo info, boolean keepShown,
Andrii Kulian829829c2018-03-19 18:19:05 -07004588 boolean saveState, boolean finalStateRequest, String reason) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004589 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004590 if (r != null) {
Andrii Kulian0f3356c2019-03-18 21:34:40 +00004591 if (!keepShown && r.stopped) {
4592 if (r.activity.mFinished) {
4593 // If we are finishing, we won't call onResume() in certain
4594 // cases. So here we likewise don't want to call onStop()
4595 // if the activity isn't resumed.
4596 return;
4597 }
4598 if (!finalStateRequest) {
4599 final RuntimeException e = new RuntimeException(
4600 "Performing stop of activity that is already stopped: "
4601 + r.intent.getComponent().toShortString());
4602 Slog.e(TAG, e.getMessage(), e);
4603 Slog.e(TAG, r.getStateString());
4604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004605 }
4606
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004607 // One must first be paused before stopped...
4608 performPauseActivityIfNeeded(r, reason);
4609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004610 if (info != null) {
4611 try {
4612 // First create a thumbnail for the activity...
Dianne Hackborn0500b3c2011-11-01 15:28:43 -07004613 // For now, don't create the thumbnail here; we are
4614 // doing that by doing a screen snapshot.
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004615 info.setDescription(r.activity.onCreateDescription());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004616 } catch (Exception e) {
4617 if (!mInstrumentation.onException(r.activity, e)) {
4618 throw new RuntimeException(
4619 "Unable to save state of activity "
4620 + r.intent.getComponent().toShortString()
4621 + ": " + e.toString(), e);
4622 }
4623 }
4624 }
4625
4626 if (!keepShown) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004627 callActivityOnStop(r, saveState, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004629 }
4630 }
4631
Andrii Kulian8ae79572018-01-26 15:36:06 -08004632 /**
4633 * Calls {@link Activity#onStop()} and {@link Activity#onSaveInstanceState(Bundle)}, and updates
4634 * the client record's state.
4635 * All calls to stop an activity must be done through this method to make sure that
4636 * {@link Activity#onSaveInstanceState(Bundle)} is also executed in the same call.
4637 */
4638 private void callActivityOnStop(ActivityClientRecord r, boolean saveState, String reason) {
Andrii Kulian391161f2018-01-29 10:50:02 -08004639 // Before P onSaveInstanceState was called before onStop, starting with P it's
4640 // called after. Before Honeycomb state was always saved before onPause.
Andrii Kulian8ae79572018-01-26 15:36:06 -08004641 final boolean shouldSaveState = saveState && !r.activity.mFinished && r.state == null
4642 && !r.isPreHoneycomb();
Andrii Kulian391161f2018-01-29 10:50:02 -08004643 final boolean isPreP = r.isPreP();
4644 if (shouldSaveState && isPreP) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004645 callActivityOnSaveInstanceState(r);
4646 }
4647
4648 try {
Garfield Tanc1681e62018-05-29 11:05:05 -07004649 r.activity.performStop(r.mPreserveWindow, reason);
Andrii Kulian8ae79572018-01-26 15:36:06 -08004650 } catch (SuperNotCalledException e) {
4651 throw e;
4652 } catch (Exception e) {
4653 if (!mInstrumentation.onException(r.activity, e)) {
4654 throw new RuntimeException(
4655 "Unable to stop activity "
4656 + r.intent.getComponent().toShortString()
4657 + ": " + e.toString(), e);
4658 }
4659 }
4660 r.setState(ON_STOP);
Andrii Kulian391161f2018-01-29 10:50:02 -08004661
4662 if (shouldSaveState && !isPreP) {
4663 callActivityOnSaveInstanceState(r);
4664 }
Andrii Kulian8ae79572018-01-26 15:36:06 -08004665 }
4666
Romain Guy65b345f2011-07-27 18:51:50 -07004667 private void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004668 View v = r.activity.mDecor;
4669 if (v != null) {
4670 if (show) {
4671 if (!r.activity.mVisibleFromServer) {
4672 r.activity.mVisibleFromServer = true;
4673 mNumVisibleActivities++;
4674 if (r.activity.mVisibleFromClient) {
4675 r.activity.makeVisible();
4676 }
4677 }
4678 if (r.newConfig != null) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004679 performConfigurationChangedForActivity(r, r.newConfig);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004680 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Adam Lesinski082614c2016-03-04 14:33:47 -08004681 + r.activityInfo.name + " with new config "
4682 + r.activity.mCurrentConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004683 r.newConfig = null;
4684 }
4685 } else {
4686 if (r.activity.mVisibleFromServer) {
4687 r.activity.mVisibleFromServer = false;
4688 mNumVisibleActivities--;
4689 v.setVisibility(View.INVISIBLE);
4690 }
4691 }
4692 }
4693 }
4694
Andrii Kulian446e8242017-10-26 15:17:29 -07004695 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004696 public void handleStopActivity(IBinder token, boolean show, int configChanges,
Andrii Kulian829829c2018-03-19 18:19:05 -07004697 PendingTransactionActions pendingActions, boolean finalStateRequest, String reason) {
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004698 final ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004699 r.activity.mConfigChangeFlags |= configChanges;
4700
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004701 final StopInfo stopInfo = new StopInfo();
Andrii Kulian829829c2018-03-19 18:19:05 -07004702 performStopActivityInner(r, stopInfo, show, true /* saveState */, finalStateRequest,
4703 reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004704
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004705 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004706 TAG, "Finishing stop of " + r + ": show=" + show
4707 + " win=" + r.window);
4708
4709 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07004710
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004711 // Make sure any pending writes are now committed.
4712 if (!r.isPreHoneycomb()) {
4713 QueuedWork.waitToFinish();
4714 }
4715
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004716 stopInfo.setActivity(r);
4717 stopInfo.setState(r.state);
4718 stopInfo.setPersistentState(r.persistentState);
4719 pendingActions.setStopInfo(stopInfo);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004720 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004721 }
4722
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004723 /**
4724 * Schedule the call to tell the activity manager we have stopped. We don't do this
4725 * immediately, because we want to have a chance for any other pending work (in particular
4726 * memory trim requests) to complete before you tell the activity manager to proceed and allow
4727 * us to go fully into the background.
4728 */
4729 @Override
4730 public void reportStop(PendingTransactionActions pendingActions) {
4731 mH.post(pendingActions.getStopInfo());
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07004732 }
4733
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004734 @Override
4735 public void performRestartActivity(IBinder token, boolean start) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004736 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004737 if (r.stopped) {
Andrii Kuliand25680c2018-02-21 15:16:58 -08004738 r.activity.performRestart(start, "performRestartActivity");
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004739 if (start) {
4740 r.setState(ON_START);
4741 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004742 }
4743 }
4744
Andrii Kulian446e8242017-10-26 15:17:29 -07004745 @Override
4746 public void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004747 ActivityClientRecord r = mActivities.get(token);
Tim Murraye1e6c662015-04-07 13:24:14 -07004748
Dianne Hackbornbfddc0f2010-12-14 11:28:01 -08004749 if (r == null) {
4750 Log.w(TAG, "handleWindowVisibility: no activity for token " + token);
4751 return;
4752 }
Tim Murraye1e6c662015-04-07 13:24:14 -07004753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004754 if (!show && !r.stopped) {
Andrii Kulian829829c2018-03-19 18:19:05 -07004755 performStopActivityInner(r, null /* stopInfo */, show, false /* saveState */,
4756 false /* finalStateRequest */, "handleWindowVisibility");
Andrii Kulian49dc7982019-03-21 19:01:57 -07004757 } else if (show && r.getLifecycleState() == ON_STOP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004758 // If we are getting ready to gc after going to the background, well
4759 // we are back active so skip it.
4760 unscheduleGcIdler();
4761
Andrii Kuliand25680c2018-02-21 15:16:58 -08004762 r.activity.performRestart(true /* start */, "handleWindowVisibility");
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004763 r.setState(ON_START);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004764 }
4765 if (r.activity.mDecor != null) {
Joe Onorato43a17652011-04-06 19:22:23 -07004766 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004767 TAG, "Handle window " + r + " visibility: " + show);
4768 updateVisibility(r, show);
4769 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004770 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004771 }
4772
Wale Ogunwaleb5066fe2016-09-21 07:33:43 -07004773 // TODO: This method should be changed to use {@link #performStopActivityInner} to perform to
4774 // stop operation on the activity to reduce code duplication and the chance of fixing a bug in
4775 // one place and missing the other.
Romain Guy65b345f2011-07-27 18:51:50 -07004776 private void handleSleeping(IBinder token, boolean sleeping) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004777 ActivityClientRecord r = mActivities.get(token);
4778
4779 if (r == null) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08004780 Log.w(TAG, "handleSleeping: no activity for token " + token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004781 return;
4782 }
4783
4784 if (sleeping) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08004785 if (!r.stopped && !r.isPreHoneycomb()) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004786 callActivityOnStop(r, true /* saveState */, "sleeping");
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004787 }
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004788
4789 // Make sure any pending writes are now committed.
4790 if (!r.isPreHoneycomb()) {
4791 QueuedWork.waitToFinish();
4792 }
4793
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004794 // Tell activity manager we slept.
4795 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004796 ActivityTaskManager.getService().activitySlept(r.token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004797 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004798 throw ex.rethrowFromSystemServer();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004799 }
4800 } else {
4801 if (r.stopped && r.activity.mVisibleFromServer) {
Andrii Kuliand25680c2018-02-21 15:16:58 -08004802 r.activity.performRestart(true /* start */, "handleSleeping");
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004803 r.setState(ON_START);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004804 }
4805 }
4806 }
4807
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004808 private void handleSetCoreSettings(Bundle coreSettings) {
Craig Mautner88c05892013-06-28 09:47:45 -07004809 synchronized (mResourcesManager) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08004810 mCoreSettings = coreSettings;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004811 }
Jon Miranda836c0a82014-08-11 12:32:26 -07004812 onCoreSettingsChange();
4813 }
4814
4815 private void onCoreSettingsChange() {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08004816 if (updateDebugViewAttributeState()) {
Jon Miranda836c0a82014-08-11 12:32:26 -07004817 // request all activities to relaunch for the changes to take place
Adrian Roos03dd48c2019-03-19 17:17:37 -04004818 relaunchAllActivities(false /* preserveWindows */);
Fyodor Kupolovcb93d6f2017-05-04 17:27:16 -07004819 }
4820 }
4821
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08004822 private boolean updateDebugViewAttributeState() {
4823 boolean previousState = View.sDebugViewAttributes;
4824
4825 View.sDebugViewAttributesApplicationPackage = mCoreSettings.getString(
4826 Settings.Global.DEBUG_VIEW_ATTRIBUTES_APPLICATION_PACKAGE, "");
4827 String currentPackage = (mBoundApplication != null && mBoundApplication.appInfo != null)
4828 ? mBoundApplication.appInfo.packageName : "";
4829 View.sDebugViewAttributes =
4830 mCoreSettings.getInt(Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0
4831 || View.sDebugViewAttributesApplicationPackage.equals(currentPackage);
4832 return previousState != View.sDebugViewAttributes;
4833 }
4834
Adrian Roos03dd48c2019-03-19 17:17:37 -04004835 private void relaunchAllActivities(boolean preserveWindows) {
Fyodor Kupolovcb93d6f2017-05-04 17:27:16 -07004836 for (Map.Entry<IBinder, ActivityClientRecord> entry : mActivities.entrySet()) {
Adrian Roos03dd48c2019-03-19 17:17:37 -04004837 final ActivityClientRecord r = entry.getValue();
4838 if (!r.activity.mFinished) {
4839 if (preserveWindows && r.window != null) {
4840 r.mPreserveWindow = true;
4841 }
Andrii Kulian320e3b52018-05-03 16:26:25 -07004842 scheduleRelaunchActivity(entry.getKey());
Jon Miranda836c0a82014-08-11 12:32:26 -07004843 }
4844 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004845 }
4846
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004847 private void handleUpdatePackageCompatibilityInfo(UpdateCompatibilityData data) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00004848 LoadedApk apk = peekPackageInfo(data.pkg, false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004849 if (apk != null) {
Craig Mautner48d0d182013-06-11 07:53:06 -07004850 apk.setCompatibilityInfo(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004851 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00004852 apk = peekPackageInfo(data.pkg, true);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004853 if (apk != null) {
Craig Mautner48d0d182013-06-11 07:53:06 -07004854 apk.setCompatibilityInfo(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004855 }
4856 handleConfigurationChanged(mConfiguration, data.info);
Jeff Brown98365d72012-08-19 20:30:52 -07004857 WindowManagerGlobal.getInstance().reportNewConfiguration(mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004858 }
4859
Andrii Kuliane55b0092018-04-19 15:29:22 -07004860 private void deliverResults(ActivityClientRecord r, List<ResultInfo> results, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004861 final int N = results.size();
4862 for (int i=0; i<N; i++) {
4863 ResultInfo ri = results.get(i);
4864 try {
4865 if (ri.mData != null) {
4866 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01004867 ri.mData.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004868 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004869 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07004870 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004871 r.activity.dispatchActivityResult(ri.mResultWho,
Andrii Kuliane55b0092018-04-19 15:29:22 -07004872 ri.mRequestCode, ri.mResultCode, ri.mData, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004873 } catch (Exception e) {
4874 if (!mInstrumentation.onException(r.activity, e)) {
4875 throw new RuntimeException(
4876 "Failure delivering result " + ri + " to activity "
4877 + r.intent.getComponent().toShortString()
4878 + ": " + e.toString(), e);
4879 }
4880 }
4881 }
4882 }
4883
Andrii Kulian446e8242017-10-26 15:17:29 -07004884 @Override
Andrii Kuliane55b0092018-04-19 15:29:22 -07004885 public void handleSendResult(IBinder token, List<ResultInfo> results, String reason) {
Andrii Kulian446e8242017-10-26 15:17:29 -07004886 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004887 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004888 if (r != null) {
4889 final boolean resumed = !r.paused;
4890 if (!r.activity.mFinished && r.activity.mDecor != null
4891 && r.hideForNow && resumed) {
4892 // We had hidden the activity because it started another
4893 // one... we have gotten a result back and we are not
4894 // paused, so make sure our window is visible.
4895 updateVisibility(r, true);
4896 }
4897 if (resumed) {
4898 try {
4899 // Now we are idle.
4900 r.activity.mCalled = false;
4901 mInstrumentation.callActivityOnPause(r.activity);
4902 if (!r.activity.mCalled) {
4903 throw new SuperNotCalledException(
4904 "Activity " + r.intent.getComponent().toShortString()
4905 + " did not call through to super.onPause()");
4906 }
4907 } catch (SuperNotCalledException e) {
4908 throw e;
4909 } catch (Exception e) {
4910 if (!mInstrumentation.onException(r.activity, e)) {
4911 throw new RuntimeException(
4912 "Unable to pause activity "
4913 + r.intent.getComponent().toShortString()
4914 + ": " + e.toString(), e);
4915 }
4916 }
4917 }
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07004918 checkAndBlockForNetworkAccess();
Andrii Kuliane55b0092018-04-19 15:29:22 -07004919 deliverResults(r, results, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004920 if (resumed) {
Andrii Kuliane55b0092018-04-19 15:29:22 -07004921 r.activity.performResume(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004922 }
4923 }
4924 }
4925
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004926 /** Core implementation of activity destroy call. */
4927 ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
Bryce Leea33c13d2018-02-08 14:37:06 -08004928 int configChanges, boolean getNonConfigInstance, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004929 ActivityClientRecord r = mActivities.get(token);
Craig Mautner88c05892013-06-28 09:47:45 -07004930 Class<? extends Activity> activityClass = null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004931 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004932 if (r != null) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08004933 activityClass = r.activity.getClass();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004934 r.activity.mConfigChangeFlags |= configChanges;
4935 if (finishing) {
4936 r.activity.mFinished = true;
4937 }
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004938
4939 performPauseActivityIfNeeded(r, "destroy");
4940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004941 if (!r.stopped) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004942 callActivityOnStop(r, false /* saveState */, "destroy");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004943 }
4944 if (getNonConfigInstance) {
4945 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004946 r.lastNonConfigurationInstances
4947 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004948 } catch (Exception e) {
4949 if (!mInstrumentation.onException(r.activity, e)) {
4950 throw new RuntimeException(
4951 "Unable to retain activity "
4952 + r.intent.getComponent().toShortString()
4953 + ": " + e.toString(), e);
4954 }
4955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004956 }
4957 try {
4958 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004959 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004960 if (!r.activity.mCalled) {
4961 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004962 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004963 " did not call through to super.onDestroy()");
4964 }
4965 if (r.window != null) {
4966 r.window.closeAllPanels();
4967 }
4968 } catch (SuperNotCalledException e) {
4969 throw e;
4970 } catch (Exception e) {
4971 if (!mInstrumentation.onException(r.activity, e)) {
4972 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004973 "Unable to destroy activity " + safeToComponentShortString(r.intent)
4974 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004975 }
4976 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004977 r.setState(ON_DESTROY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004978 }
Tim Murray59f3dc12018-10-22 15:26:08 -07004979 schedulePurgeIdler();
Garfield Tan0443b372019-01-04 15:00:13 -08004980 // updatePendingActivityConfiguration() reads from mActivities to update
4981 // ActivityClientRecord which runs in a different thread. Protect modifications to
4982 // mActivities to avoid race.
4983 synchronized (mResourcesManager) {
4984 mActivities.remove(token);
4985 }
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08004986 StrictMode.decrementExpectedActivityCount(activityClass);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004987 return r;
4988 }
4989
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004990 private static String safeToComponentShortString(Intent intent) {
4991 ComponentName component = intent.getComponent();
4992 return component == null ? "[Unknown]" : component.toShortString();
4993 }
4994
Andrii Kulian446e8242017-10-26 15:17:29 -07004995 @Override
Riddle Hsud3062cb2018-06-30 02:06:42 +08004996 public Map<IBinder, ClientTransactionItem> getActivitiesToBeDestroyed() {
4997 return mActivitiesToBeDestroyed;
4998 }
4999
5000 @Override
Andrii Kulian446e8242017-10-26 15:17:29 -07005001 public void handleDestroyActivity(IBinder token, boolean finishing, int configChanges,
Bryce Leea33c13d2018-02-08 14:37:06 -08005002 boolean getNonConfigInstance, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005003 ActivityClientRecord r = performDestroyActivity(token, finishing,
Bryce Leea33c13d2018-02-08 14:37:06 -08005004 configChanges, getNonConfigInstance, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005005 if (r != null) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07005006 cleanUpPendingRemoveWindows(r, finishing);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005007 WindowManager wm = r.activity.getWindowManager();
5008 View v = r.activity.mDecor;
5009 if (v != null) {
5010 if (r.activity.mVisibleFromServer) {
5011 mNumVisibleActivities--;
5012 }
5013 IBinder wtoken = v.getWindowToken();
5014 if (r.activity.mWindowAdded) {
Robert Carr77bdfb52016-05-02 18:18:31 -07005015 if (r.mPreserveWindow) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005016 // Hold off on removing this until the new activity's
5017 // window is being added.
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07005018 r.mPendingRemoveWindow = r.window;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005019 r.mPendingRemoveWindowManager = wm;
Andrii Kulianeac0ea52016-05-11 15:50:24 -07005020 // We can only keep the part of the view hierarchy that we control,
5021 // everything else must be removed, because it might not be able to
5022 // behave properly when activity is relaunching.
5023 r.window.clearContentView();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005024 } else {
5025 wm.removeViewImmediate(v);
5026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005027 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005028 if (wtoken != null && r.mPendingRemoveWindow == null) {
Jeff Brown98365d72012-08-19 20:30:52 -07005029 WindowManagerGlobal.getInstance().closeAll(wtoken,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005030 r.activity.getClass().getName(), "Activity");
Andrii Kulianeac0ea52016-05-11 15:50:24 -07005031 } else if (r.mPendingRemoveWindow != null) {
5032 // We're preserving only one window, others should be closed so app views
5033 // will be detached before the final tear down. It should be done now because
5034 // some components (e.g. WebView) rely on detach callbacks to perform receiver
5035 // unregister and other cleanup.
5036 WindowManagerGlobal.getInstance().closeAllExceptView(token, v,
5037 r.activity.getClass().getName(), "Activity");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005038 }
5039 r.activity.mDecor = null;
5040 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005041 if (r.mPendingRemoveWindow == null) {
5042 // If we are delaying the removal of the activity window, then
5043 // we can't clean up all windows here. Note that we can't do
5044 // so later either, which means any windows that aren't closed
5045 // by the app will leak. Well we try to warning them a lot
5046 // about leaking windows, because that is a bug, so if they are
5047 // using this recreate facility then they get to live with leaks.
Jeff Brown98365d72012-08-19 20:30:52 -07005048 WindowManagerGlobal.getInstance().closeAll(token,
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005049 r.activity.getClass().getName(), "Activity");
5050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005051
5052 // Mocked out contexts won't be participating in the normal
5053 // process lifecycle, but if we're running with a proper
5054 // ApplicationContext we need to have it tear down things
5055 // cleanly.
5056 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08005057 if (c instanceof ContextImpl) {
5058 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005059 r.activity.getClass().getName(), "Activity");
5060 }
5061 }
5062 if (finishing) {
5063 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07005064 ActivityTaskManager.getService().activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005065 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005066 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005067 }
5068 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07005069 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005070 }
5071
Andrii Kulianb372da62018-01-18 10:46:24 -08005072 @Override
5073 public ActivityClientRecord prepareRelaunchActivity(IBinder token,
Dianne Hackborn85d558c2014-11-04 10:31:54 -08005074 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
Andrii Kulianb372da62018-01-18 10:46:24 -08005075 int configChanges, MergedConfiguration config, boolean preserveWindow) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005076 ActivityClientRecord target = null;
Andrii Kulianb372da62018-01-18 10:46:24 -08005077 boolean scheduleRelaunch = false;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005078
Craig Mautner88c05892013-06-28 09:47:45 -07005079 synchronized (mResourcesManager) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005080 for (int i=0; i<mRelaunchingActivities.size(); i++) {
5081 ActivityClientRecord r = mRelaunchingActivities.get(i);
Filip Gruszczynskic3b61792016-01-22 16:43:48 -08005082 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: " + this + ", trying: " + r);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005083 if (r.token == token) {
5084 target = r;
5085 if (pendingResults != null) {
5086 if (r.pendingResults != null) {
5087 r.pendingResults.addAll(pendingResults);
5088 } else {
5089 r.pendingResults = pendingResults;
5090 }
5091 }
5092 if (pendingNewIntents != null) {
5093 if (r.pendingIntents != null) {
5094 r.pendingIntents.addAll(pendingNewIntents);
5095 } else {
5096 r.pendingIntents = pendingNewIntents;
5097 }
5098 }
5099 break;
5100 }
5101 }
5102
5103 if (target == null) {
Andrii Kulianb372da62018-01-18 10:46:24 -08005104 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: target is null");
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005105 target = new ActivityClientRecord();
5106 target.token = token;
5107 target.pendingResults = pendingResults;
5108 target.pendingIntents = pendingNewIntents;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07005109 target.mPreserveWindow = preserveWindow;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005110 mRelaunchingActivities.add(target);
Andrii Kulianb372da62018-01-18 10:46:24 -08005111 scheduleRelaunch = true;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005112 }
Andrii Kulianb372da62018-01-18 10:46:24 -08005113 target.createdConfig = config.getGlobalConfiguration();
5114 target.overrideConfig = config.getOverrideConfiguration();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005115 target.pendingConfigChanges |= configChanges;
5116 }
Andrii Kulianb372da62018-01-18 10:46:24 -08005117
5118 return scheduleRelaunch ? target : null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005119 }
5120
Andrii Kulianb372da62018-01-18 10:46:24 -08005121 @Override
5122 public void handleRelaunchActivity(ActivityClientRecord tmp,
5123 PendingTransactionActions pendingActions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005124 // If we are getting ready to gc after going to the background, well
5125 // we are back active so skip it.
5126 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07005127 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005128
5129 Configuration changedConfig = null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005130 int configChanges = 0;
Bob Leee5408332009-09-04 18:31:17 -07005131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005132 // First: make sure we have the most recent configuration and most
5133 // recent version of the activity, or skip it if some previous call
5134 // had taken a more recent version.
Craig Mautner88c05892013-06-28 09:47:45 -07005135 synchronized (mResourcesManager) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005136 int N = mRelaunchingActivities.size();
5137 IBinder token = tmp.token;
5138 tmp = null;
5139 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005140 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005141 if (r.token == token) {
5142 tmp = r;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005143 configChanges |= tmp.pendingConfigChanges;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005144 mRelaunchingActivities.remove(i);
5145 i--;
5146 N--;
5147 }
5148 }
Bob Leee5408332009-09-04 18:31:17 -07005149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005150 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005151 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005152 return;
5153 }
Bob Leee5408332009-09-04 18:31:17 -07005154
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005155 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
5156 + tmp.token + " with configChanges=0x"
5157 + Integer.toHexString(configChanges));
5158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005159 if (mPendingConfiguration != null) {
5160 changedConfig = mPendingConfiguration;
5161 mPendingConfiguration = null;
5162 }
5163 }
Bob Leee5408332009-09-04 18:31:17 -07005164
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08005165 if (tmp.createdConfig != null) {
5166 // If the activity manager is passing us its current config,
5167 // assume that is really what we want regardless of what we
5168 // may have pending.
5169 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005170 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
5171 && mConfiguration.diff(tmp.createdConfig) != 0)) {
5172 if (changedConfig == null
5173 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
5174 changedConfig = tmp.createdConfig;
5175 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08005176 }
5177 }
Tim Murraye1e6c662015-04-07 13:24:14 -07005178
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005179 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07005180 + tmp.token + ": changedConfig=" + changedConfig);
Tim Murraye1e6c662015-04-07 13:24:14 -07005181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005182 // If there was a pending configuration change, execute it first.
5183 if (changedConfig != null) {
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005184 mCurDefaultDisplayDpi = changedConfig.densityDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -07005185 updateDefaultDensity();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04005186 handleConfigurationChanged(changedConfig, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005187 }
Bob Leee5408332009-09-04 18:31:17 -07005188
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005189 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005190 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005191 if (r == null) {
5192 return;
5193 }
Bob Leee5408332009-09-04 18:31:17 -07005194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005195 r.activity.mConfigChangeFlags |= configChanges;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07005196 r.mPreserveWindow = tmp.mPreserveWindow;
Bob Leee5408332009-09-04 18:31:17 -07005197
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08005198 r.activity.mChangingConfigurations = true;
5199
Robert Carr23fa16b2016-01-13 13:19:58 -08005200 // If we are preserving the main window across relaunches we would also like to preserve
5201 // the children. However the client side view system does not support preserving
5202 // the child views so we notify the window manager to expect these windows to
5203 // be replaced and defer requests to destroy or hide them. This way we can achieve
5204 // visual continuity. It's important that we do this here prior to pause and destroy
5205 // as that is when we may hide or remove the child views.
Robert Carr77bdfb52016-05-02 18:18:31 -07005206 //
5207 // There is another scenario, if we have decided locally to relaunch the app from a
5208 // call to recreate, then none of the windows will be prepared for replacement or
5209 // preserved by the server, so we want to notify it that we are preparing to replace
5210 // everything
Robert Carr23fa16b2016-01-13 13:19:58 -08005211 try {
Andrii Kulianb372da62018-01-18 10:46:24 -08005212 if (r.mPreserveWindow) {
Robert Carr77bdfb52016-05-02 18:18:31 -07005213 WindowManagerGlobal.getWindowSession().prepareToReplaceWindows(
Andrii Kulianb372da62018-01-18 10:46:24 -08005214 r.token, true /* childrenOnly */);
Robert Carr23fa16b2016-01-13 13:19:58 -08005215 }
5216 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005217 throw e.rethrowFromSystemServer();
Robert Carr23fa16b2016-01-13 13:19:58 -08005218 }
5219
Wale Ogunwale5527a502018-02-20 18:18:21 -08005220 handleRelaunchActivityInner(r, configChanges, tmp.pendingResults, tmp.pendingIntents,
5221 pendingActions, tmp.startsNotResumed, tmp.overrideConfig, "handleRelaunchActivity");
5222
5223 if (pendingActions != null) {
5224 // Only report a successful relaunch to WindowManager.
5225 pendingActions.setReportRelaunchToWindowManager(true);
Dianne Hackborne2b04802010-12-09 09:24:55 -08005226 }
Wale Ogunwale5527a502018-02-20 18:18:21 -08005227 }
5228
Andrii Kulian320e3b52018-05-03 16:26:25 -07005229 /**
5230 * Post a message to relaunch the activity. We do this instead of launching it immediately,
5231 * because this will destroy the activity from which it was called and interfere with the
5232 * lifecycle changes it was going through before. We need to make sure that we have finished
5233 * handling current transaction item before relaunching the activity.
5234 */
5235 void scheduleRelaunchActivity(IBinder token) {
Amin Shaikh96e60d72019-04-24 13:47:57 -04005236 mH.removeMessages(H.RELAUNCH_ACTIVITY, token);
Andrii Kulian320e3b52018-05-03 16:26:25 -07005237 sendMessage(H.RELAUNCH_ACTIVITY, token);
5238 }
Bob Leee5408332009-09-04 18:31:17 -07005239
Andrii Kulian320e3b52018-05-03 16:26:25 -07005240 /** Performs the activity relaunch locally vs. requesting from system-server. */
5241 private void handleRelaunchActivityLocally(IBinder token) {
Wale Ogunwale5527a502018-02-20 18:18:21 -08005242 final ActivityClientRecord r = mActivities.get(token);
5243 if (r == null) {
Andrii Kulian320e3b52018-05-03 16:26:25 -07005244 Log.w(TAG, "Activity to relaunch no longer exists");
Wale Ogunwale5527a502018-02-20 18:18:21 -08005245 return;
5246 }
5247
5248 final int prevState = r.getLifecycleState();
5249
Andrii Kulian320e3b52018-05-03 16:26:25 -07005250 if (prevState < ON_RESUME || prevState > ON_STOP) {
5251 Log.w(TAG, "Activity state must be in [ON_RESUME..ON_STOP] in order to be relaunched,"
5252 + "current state is " + prevState);
Wale Ogunwale5527a502018-02-20 18:18:21 -08005253 return;
5254 }
5255
Wale Ogunwale5527a502018-02-20 18:18:21 -08005256
Andrii Kulian914aa7d2018-03-19 21:51:53 -07005257 // Initialize a relaunch request.
5258 final MergedConfiguration mergedConfiguration = new MergedConfiguration(
5259 r.createdConfig != null ? r.createdConfig : mConfiguration,
5260 r.overrideConfig);
5261 final ActivityRelaunchItem activityRelaunchItem = ActivityRelaunchItem.obtain(
5262 null /* pendingResults */, null /* pendingIntents */, 0 /* configChanges */,
5263 mergedConfiguration, r.mPreserveWindow);
5264 // Make sure to match the existing lifecycle state in the end of the transaction.
5265 final ActivityLifecycleItem lifecycleRequest =
5266 TransactionExecutorHelper.getLifecycleRequestForCurrentState(r);
5267 // Schedule the transaction.
5268 final ClientTransaction transaction = ClientTransaction.obtain(this.mAppThread, r.token);
5269 transaction.addCallback(activityRelaunchItem);
5270 transaction.setLifecycleStateRequest(lifecycleRequest);
5271 executeTransaction(transaction);
Wale Ogunwale5527a502018-02-20 18:18:21 -08005272 }
5273
5274 private void handleRelaunchActivityInner(ActivityClientRecord r, int configChanges,
5275 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingIntents,
5276 PendingTransactionActions pendingActions, boolean startsNotResumed,
5277 Configuration overrideConfig, String reason) {
Andrii Kulian770c4032018-05-02 18:40:59 -07005278 // Preserve last used intent, it may be set from Activity#setIntent().
5279 final Intent customIntent = r.activity.mIntent;
Wale Ogunwale5527a502018-02-20 18:18:21 -08005280 // Need to ensure state is saved.
5281 if (!r.paused) {
5282 performPauseActivity(r, false, reason, null /* pendingActions */);
5283 }
5284 if (!r.stopped) {
5285 callActivityOnStop(r, true /* saveState */, reason);
5286 }
5287
5288 handleDestroyActivity(r.token, false, configChanges, true, reason);
Bob Leee5408332009-09-04 18:31:17 -07005289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005290 r.activity = null;
5291 r.window = null;
5292 r.hideForNow = false;
5293 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07005294 // Merge any pending results and pending intents; don't just replace them
Wale Ogunwale5527a502018-02-20 18:18:21 -08005295 if (pendingResults != null) {
The Android Open Source Project10592532009-03-18 17:39:46 -07005296 if (r.pendingResults == null) {
Wale Ogunwale5527a502018-02-20 18:18:21 -08005297 r.pendingResults = pendingResults;
The Android Open Source Project10592532009-03-18 17:39:46 -07005298 } else {
Wale Ogunwale5527a502018-02-20 18:18:21 -08005299 r.pendingResults.addAll(pendingResults);
The Android Open Source Project10592532009-03-18 17:39:46 -07005300 }
5301 }
Wale Ogunwale5527a502018-02-20 18:18:21 -08005302 if (pendingIntents != null) {
The Android Open Source Project10592532009-03-18 17:39:46 -07005303 if (r.pendingIntents == null) {
Wale Ogunwale5527a502018-02-20 18:18:21 -08005304 r.pendingIntents = pendingIntents;
The Android Open Source Project10592532009-03-18 17:39:46 -07005305 } else {
Wale Ogunwale5527a502018-02-20 18:18:21 -08005306 r.pendingIntents.addAll(pendingIntents);
The Android Open Source Project10592532009-03-18 17:39:46 -07005307 }
5308 }
Wale Ogunwale5527a502018-02-20 18:18:21 -08005309 r.startsNotResumed = startsNotResumed;
5310 r.overrideConfig = overrideConfig;
Bob Leee5408332009-09-04 18:31:17 -07005311
Andrii Kulian770c4032018-05-02 18:40:59 -07005312 handleLaunchActivity(r, pendingActions, customIntent);
Andrii Kulianb372da62018-01-18 10:46:24 -08005313 }
Jorim Jaggife89d122015-12-22 16:28:44 +01005314
Andrii Kulianb372da62018-01-18 10:46:24 -08005315 @Override
5316 public void reportRelaunch(IBinder token, PendingTransactionActions pendingActions) {
5317 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07005318 ActivityTaskManager.getService().activityRelaunched(token);
Andrii Kulianb372da62018-01-18 10:46:24 -08005319 final ActivityClientRecord r = mActivities.get(token);
5320 if (pendingActions.shouldReportRelaunchToWindowManager() && r != null
5321 && r.window != null) {
5322 r.window.reportActivityRelaunched();
Jorim Jaggife89d122015-12-22 16:28:44 +01005323 }
Andrii Kulianb372da62018-01-18 10:46:24 -08005324 } catch (RemoteException e) {
5325 throw e.rethrowFromSystemServer();
Jorim Jaggife89d122015-12-22 16:28:44 +01005326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005327 }
5328
Andrii Kulian8ae79572018-01-26 15:36:06 -08005329 private void callActivityOnSaveInstanceState(ActivityClientRecord r) {
Craig Mautnera0026042014-04-23 11:45:37 -07005330 r.state = new Bundle();
5331 r.state.setAllowFds(false);
5332 if (r.isPersistable()) {
5333 r.persistentState = new PersistableBundle();
5334 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state,
5335 r.persistentState);
5336 } else {
5337 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
5338 }
5339 }
5340
Dianne Hackborn73c14162012-09-19 15:45:06 -07005341 ArrayList<ComponentCallbacks2> collectComponentCallbacks(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005342 boolean allActivities, Configuration newConfig) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005343 ArrayList<ComponentCallbacks2> callbacks
5344 = new ArrayList<ComponentCallbacks2>();
Bob Leee5408332009-09-04 18:31:17 -07005345
Craig Mautner88c05892013-06-28 09:47:45 -07005346 synchronized (mResourcesManager) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005347 final int NAPP = mAllApplications.size();
5348 for (int i=0; i<NAPP; i++) {
Dianne Hackborn73c14162012-09-19 15:45:06 -07005349 callbacks.add(mAllApplications.get(i));
5350 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005351 final int NACT = mActivities.size();
5352 for (int i=0; i<NACT; i++) {
5353 ActivityClientRecord ar = mActivities.valueAt(i);
5354 Activity a = ar.activity;
5355 if (a != null) {
5356 Configuration thisConfig = applyConfigCompatMainThread(
5357 mCurDefaultDisplayDpi, newConfig,
Todd Kennedy233a0b12018-01-29 20:30:24 +00005358 ar.packageInfo.getCompatibilityInfo());
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005359 if (!ar.activity.mFinished && (allActivities || !ar.paused)) {
5360 // If the activity is currently resumed, its configuration
5361 // needs to change right now.
5362 callbacks.add(a);
5363 } else if (thisConfig != null) {
5364 // Otherwise, we will tell it about the change
5365 // the next time it is resumed or shown. Note that
5366 // the activity manager may, before then, decide the
5367 // activity needs to be destroyed to handle its new
5368 // configuration.
5369 if (DEBUG_CONFIGURATION) {
5370 Slog.v(TAG, "Setting activity "
5371 + ar.activityInfo.name + " newConfig=" + thisConfig);
Romain Guya998dff2012-03-23 18:58:36 -07005372 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005373 ar.newConfig = thisConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005374 }
5375 }
5376 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005377 final int NSVC = mServices.size();
5378 for (int i=0; i<NSVC; i++) {
5379 callbacks.add(mServices.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005380 }
5381 }
5382 synchronized (mProviderMap) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005383 final int NPRV = mLocalProviders.size();
5384 for (int i=0; i<NPRV; i++) {
5385 callbacks.add(mLocalProviders.valueAt(i).mLocalProvider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005386 }
5387 }
Bob Leee5408332009-09-04 18:31:17 -07005388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005389 return callbacks;
5390 }
Bob Leee5408332009-09-04 18:31:17 -07005391
Adam Lesinski082614c2016-03-04 14:33:47 -08005392 /**
5393 * Updates the configuration for an Activity. The ActivityClientRecord's
5394 * {@link ActivityClientRecord#overrideConfig} is used to compute the final Configuration for
5395 * that Activity. {@link ActivityClientRecord#tmpConfig} is used as a temporary for delivering
5396 * the updated Configuration.
5397 * @param r ActivityClientRecord representing the Activity.
5398 * @param newBaseConfig The new configuration to use. This may be augmented with
5399 * {@link ActivityClientRecord#overrideConfig}.
Adam Lesinski082614c2016-03-04 14:33:47 -08005400 */
5401 private void performConfigurationChangedForActivity(ActivityClientRecord r,
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005402 Configuration newBaseConfig) {
5403 performConfigurationChangedForActivity(r, newBaseConfig,
Yohei Yukawa5281b6b2018-10-15 07:38:25 +08005404 r.activity.getDisplayId(), false /* movedToDifferentDisplay */);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005405 }
5406
5407 /**
5408 * Updates the configuration for an Activity. The ActivityClientRecord's
5409 * {@link ActivityClientRecord#overrideConfig} is used to compute the final Configuration for
5410 * that Activity. {@link ActivityClientRecord#tmpConfig} is used as a temporary for delivering
5411 * the updated Configuration.
5412 * @param r ActivityClientRecord representing the Activity.
5413 * @param newBaseConfig The new configuration to use. This may be augmented with
5414 * {@link ActivityClientRecord#overrideConfig}.
5415 * @param displayId The id of the display where the Activity currently resides.
5416 * @param movedToDifferentDisplay Indicates if the activity was moved to different display.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005417 * @return {@link Configuration} instance sent to client, null if not sent.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005418 */
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005419 private Configuration performConfigurationChangedForActivity(ActivityClientRecord r,
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005420 Configuration newBaseConfig, int displayId, boolean movedToDifferentDisplay) {
Adam Lesinski082614c2016-03-04 14:33:47 -08005421 r.tmpConfig.setTo(newBaseConfig);
5422 if (r.overrideConfig != null) {
5423 r.tmpConfig.updateFrom(r.overrideConfig);
5424 }
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005425 final Configuration reportedConfig = performActivityConfigurationChanged(r.activity,
5426 r.tmpConfig, r.overrideConfig, displayId, movedToDifferentDisplay);
Adam Lesinski082614c2016-03-04 14:33:47 -08005427 freeTextLayoutCachesIfNeeded(r.activity.mCurrentConfig.diff(r.tmpConfig));
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005428 return reportedConfig;
Adam Lesinski082614c2016-03-04 14:33:47 -08005429 }
5430
5431 /**
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -07005432 * Creates a new Configuration only if override would modify base. Otherwise returns base.
5433 * @param base The base configuration.
5434 * @param override The update to apply to the base configuration. Can be null.
5435 * @return A Configuration representing base with override applied.
5436 */
5437 private static Configuration createNewConfigAndUpdateIfNotNull(@NonNull Configuration base,
5438 @Nullable Configuration override) {
5439 if (override == null) {
5440 return base;
5441 }
5442 Configuration newConfig = new Configuration(base);
5443 newConfig.updateFrom(override);
5444 return newConfig;
5445 }
5446
5447 /**
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005448 * Decides whether to update a component's configuration and whether to inform it.
Adam Lesinski082614c2016-03-04 14:33:47 -08005449 * @param cb The component callback to notify of configuration change.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005450 * @param newConfig The new configuration.
5451 */
5452 private void performConfigurationChanged(ComponentCallbacks2 cb, Configuration newConfig) {
5453 if (!REPORT_TO_ACTIVITY) {
5454 return;
5455 }
5456
5457 // ContextThemeWrappers may override the configuration for that context. We must check and
5458 // apply any overrides defined.
5459 Configuration contextThemeWrapperOverrideConfig = null;
5460 if (cb instanceof ContextThemeWrapper) {
5461 final ContextThemeWrapper contextThemeWrapper = (ContextThemeWrapper) cb;
5462 contextThemeWrapperOverrideConfig = contextThemeWrapper.getOverrideConfiguration();
5463 }
5464
5465 // Apply the ContextThemeWrapper override if necessary.
5466 // NOTE: Make sure the configurations are not modified, as they are treated as immutable
5467 // in many places.
5468 final Configuration configToReport = createNewConfigAndUpdateIfNotNull(
5469 newConfig, contextThemeWrapperOverrideConfig);
5470 cb.onConfigurationChanged(configToReport);
5471 }
5472
5473 /**
5474 * Decides whether to update an Activity's configuration and whether to inform it.
5475 * @param activity The activity to notify of configuration change.
Adam Lesinski082614c2016-03-04 14:33:47 -08005476 * @param newConfig The new configuration.
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -07005477 * @param amOverrideConfig The override config that differentiates the Activity's configuration
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005478 * from the base global configuration. This is supplied by
5479 * ActivityManager.
5480 * @param displayId Id of the display where activity currently resides.
5481 * @param movedToDifferentDisplay Indicates if the activity was moved to different display.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005482 * @return Configuration sent to client, null if no changes and not moved to different display.
Adam Lesinski082614c2016-03-04 14:33:47 -08005483 */
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005484 private Configuration performActivityConfigurationChanged(Activity activity,
5485 Configuration newConfig, Configuration amOverrideConfig, int displayId,
5486 boolean movedToDifferentDisplay) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005487 if (activity == null) {
5488 throw new IllegalArgumentException("No activity provided.");
5489 }
5490 final IBinder activityToken = activity.getActivityToken();
5491 if (activityToken == null) {
5492 throw new IllegalArgumentException("Activity token not set. Is the activity attached?");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005493 }
Bob Leee5408332009-09-04 18:31:17 -07005494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 boolean shouldChangeConfig = false;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005496 if (activity.mCurrentConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005497 shouldChangeConfig = true;
5498 } else {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005499 // If the new config is the same as the config this Activity is already running with and
5500 // the override config also didn't change, then don't bother calling
5501 // onConfigurationChanged.
Bryce Lee658d9842017-07-28 08:33:36 -07005502 final int diff = activity.mCurrentConfig.diffPublicOnly(newConfig);
5503
Andrii Kulian3b3c9142016-07-18 19:15:56 -07005504 if (diff != 0 || !mResourcesManager.isSameResourcesOverrideConfig(activityToken,
5505 amOverrideConfig)) {
Chong Zhang4951f9d2016-06-23 13:15:08 -07005506 // Always send the task-level config changes. For system-level configuration, if
5507 // this activity doesn't handle any of the config changes, then don't bother
5508 // calling onConfigurationChanged as we're going to destroy it.
5509 if (!mUpdatingSystemConfig
5510 || (~activity.mActivityInfo.getRealConfigChanged() & diff) == 0
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005511 || !REPORT_TO_ACTIVITY) {
Chong Zhang4951f9d2016-06-23 13:15:08 -07005512 shouldChangeConfig = true;
5513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005514 }
5515 }
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005516 if (!shouldChangeConfig && !movedToDifferentDisplay) {
5517 // Nothing significant, don't proceed with updating and reporting.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005518 return null;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005519 }
5520
5521 // Propagate the configuration change to ResourcesManager and Activity.
5522
5523 // ContextThemeWrappers may override the configuration for that context. We must check and
5524 // apply any overrides defined.
5525 Configuration contextThemeWrapperOverrideConfig = activity.getOverrideConfiguration();
5526
5527 // We only update an Activity's configuration if this is not a global configuration change.
5528 // This must also be done before the callback, or else we violate the contract that the new
5529 // resources are available in ComponentCallbacks2#onConfigurationChanged(Configuration).
5530 // Also apply the ContextThemeWrapper override if necessary.
5531 // NOTE: Make sure the configurations are not modified, as they are treated as immutable in
5532 // many places.
5533 final Configuration finalOverrideConfig = createNewConfigAndUpdateIfNotNull(
5534 amOverrideConfig, contextThemeWrapperOverrideConfig);
5535 mResourcesManager.updateResourcesForActivity(activityToken, finalOverrideConfig,
5536 displayId, movedToDifferentDisplay);
5537
5538 activity.mConfigChangeFlags = 0;
5539 activity.mCurrentConfig = new Configuration(newConfig);
5540
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005541 // Apply the ContextThemeWrapper override if necessary.
5542 // NOTE: Make sure the configurations are not modified, as they are treated as immutable
5543 // in many places.
5544 final Configuration configToReport = createNewConfigAndUpdateIfNotNull(newConfig,
5545 contextThemeWrapperOverrideConfig);
5546
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005547 if (!REPORT_TO_ACTIVITY) {
5548 // Not configured to report to activity.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005549 return configToReport;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005550 }
5551
5552 if (movedToDifferentDisplay) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005553 activity.dispatchMovedToDisplay(displayId, configToReport);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005554 }
Bob Leee5408332009-09-04 18:31:17 -07005555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005556 if (shouldChangeConfig) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005557 activity.mCalled = false;
5558 activity.onConfigurationChanged(configToReport);
5559 if (!activity.mCalled) {
5560 throw new SuperNotCalledException("Activity " + activity.getLocalClassName() +
5561 " did not call through to super.onConfigurationChanged()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005562 }
5563 }
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005564
5565 return configToReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005566 }
5567
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07005568 public final void applyConfigurationToResources(Configuration config) {
Craig Mautner88c05892013-06-28 09:47:45 -07005569 synchronized (mResourcesManager) {
5570 mResourcesManager.applyConfigurationToResourcesLocked(config, null);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07005571 }
5572 }
5573
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005574 final Configuration applyCompatConfiguration(int displayDensity) {
Dianne Hackborn836e2622011-10-04 18:32:39 -07005575 Configuration config = mConfiguration;
5576 if (mCompatConfiguration == null) {
5577 mCompatConfiguration = new Configuration();
5578 }
5579 mCompatConfiguration.setTo(mConfiguration);
Adam Lesinski082614c2016-03-04 14:33:47 -08005580 if (mResourcesManager.applyCompatConfigurationLocked(displayDensity,
5581 mCompatConfiguration)) {
Dianne Hackborn836e2622011-10-04 18:32:39 -07005582 config = mCompatConfiguration;
5583 }
5584 return config;
5585 }
5586
Andrii Kulian446e8242017-10-26 15:17:29 -07005587 @Override
5588 public void handleConfigurationChanged(Configuration config) {
5589 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "configChanged");
5590 mCurDefaultDisplayDpi = config.densityDpi;
5591 mUpdatingSystemConfig = true;
5592 try {
5593 handleConfigurationChanged(config, null /* compat */);
5594 } finally {
5595 mUpdatingSystemConfig = false;
5596 }
5597 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
5598 }
5599
5600 private void handleConfigurationChanged(Configuration config, CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005601
Tiger Huang968064b2019-05-28 14:36:18 +08005602 int configDiff;
5603 boolean equivalent;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005604
Todd Kennedy35a9a382018-01-25 13:25:37 -08005605 final Theme systemTheme = getSystemContext().getTheme();
5606 final Theme systemUiTheme = getSystemUiContext().getTheme();
Bryce Lee658d9842017-07-28 08:33:36 -07005607
Craig Mautner88c05892013-06-28 09:47:45 -07005608 synchronized (mResourcesManager) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005609 if (mPendingConfiguration != null) {
5610 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
5611 config = mPendingConfiguration;
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005612 mCurDefaultDisplayDpi = config.densityDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -07005613 updateDefaultDensity();
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005614 }
5615 mPendingConfiguration = null;
5616 }
5617
5618 if (config == null) {
5619 return;
5620 }
Tim Murraye1e6c662015-04-07 13:24:14 -07005621
Tiger Huang968064b2019-05-28 14:36:18 +08005622 // This flag tracks whether the new configuration is fundamentally equivalent to the
5623 // existing configuration. This is necessary to determine whether non-activity callbacks
5624 // should receive notice when the only changes are related to non-public fields.
5625 // We do not gate calling {@link #performActivityConfigurationChanged} based on this
5626 // flag as that method uses the same check on the activity config override as well.
5627 equivalent = mConfiguration != null && (0 == mConfiguration.diffPublicOnly(config));
5628
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005629 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005630 + config);
Craig Mautner88c05892013-06-28 09:47:45 -07005631
5632 mResourcesManager.applyConfigurationToResourcesLocked(config, compat);
Adam Lesinskib61e4052016-05-19 18:23:05 -07005633 updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
5634 mResourcesManager.getConfiguration().getLocales());
Craig Mautner88c05892013-06-28 09:47:45 -07005635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005636 if (mConfiguration == null) {
5637 mConfiguration = new Configuration();
5638 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04005639 if (!mConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005640 return;
5641 }
Alan Viverettee54d2452015-05-06 10:41:43 -07005642
5643 configDiff = mConfiguration.updateFrom(config);
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005644 config = applyCompatConfiguration(mCurDefaultDisplayDpi);
Alan Viverette395cd012015-08-11 17:27:04 -04005645
Alan Viverette395cd012015-08-11 17:27:04 -04005646 if ((systemTheme.getChangingConfigurations() & configDiff) != 0) {
5647 systemTheme.rebase();
5648 }
Adam Lesinskia82b6262017-03-21 16:56:17 -07005649
Adam Lesinskia82b6262017-03-21 16:56:17 -07005650 if ((systemUiTheme.getChangingConfigurations() & configDiff) != 0) {
5651 systemUiTheme.rebase();
5652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005653 }
Dianne Hackborn73c14162012-09-19 15:45:06 -07005654
5655 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(false, config);
5656
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005657 freeTextLayoutCachesIfNeeded(configDiff);
5658
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005659 if (callbacks != null) {
5660 final int N = callbacks.size();
5661 for (int i=0; i<N; i++) {
Andrii Kulian701214b2016-04-07 09:36:33 -07005662 ComponentCallbacks2 cb = callbacks.get(i);
5663 if (cb instanceof Activity) {
5664 // If callback is an Activity - call corresponding method to consider override
5665 // config and avoid onConfigurationChanged if it hasn't changed.
5666 Activity a = (Activity) cb;
5667 performConfigurationChangedForActivity(mActivities.get(a.getActivityToken()),
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005668 config);
Bryce Lee658d9842017-07-28 08:33:36 -07005669 } else if (!equivalent) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005670 performConfigurationChanged(cb, config);
Andrii Kulian701214b2016-04-07 09:36:33 -07005671 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005673 }
5674 }
5675
Winson72dbe7e2019-04-29 14:55:30 -07005676 /**
5677 * Updates the application info.
5678 *
5679 * This only works in the system process. Must be called on the main thread.
5680 */
5681 public void handleSystemApplicationInfoChanged(@NonNull ApplicationInfo ai) {
5682 Preconditions.checkState(mSystemThread, "Must only be called in the system process");
5683 handleApplicationInfoChanged(ai);
5684 }
5685
Adrian Roos03dd48c2019-03-19 17:17:37 -04005686 @VisibleForTesting(visibility = PACKAGE)
5687 public void handleApplicationInfoChanged(@NonNull final ApplicationInfo ai) {
Adam Lesinskid33ef562017-01-19 14:49:59 -08005688 // Updates triggered by package installation go through a package update
5689 // receiver. Here we try to capture ApplicationInfo changes that are
5690 // caused by other sources, such as overlays. That means we want to be as conservative
5691 // about code changes as possible. Take the diff of the old ApplicationInfo and the new
5692 // to see if anything needs to change.
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005693 LoadedApk apk;
5694 LoadedApk resApk;
5695 // Update all affected loaded packages with new package information
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005696 synchronized (mResourcesManager) {
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005697 WeakReference<LoadedApk> ref = mPackages.get(ai.packageName);
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005698 apk = ref != null ? ref.get() : null;
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005699 ref = mResourcePackages.get(ai.packageName);
5700 resApk = ref != null ? ref.get() : null;
5701 }
Winsond605e2d2019-02-11 16:05:51 -08005702
5703 final String[] oldResDirs = new String[2];
5704
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005705 if (apk != null) {
Winsond605e2d2019-02-11 16:05:51 -08005706 oldResDirs[0] = apk.getResDir();
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005707 final ArrayList<String> oldPaths = new ArrayList<>();
5708 LoadedApk.makePaths(this, apk.getApplicationInfo(), oldPaths);
5709 apk.updateApplicationInfo(ai, oldPaths);
5710 }
5711 if (resApk != null) {
Winsond605e2d2019-02-11 16:05:51 -08005712 oldResDirs[1] = resApk.getResDir();
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005713 final ArrayList<String> oldPaths = new ArrayList<>();
5714 LoadedApk.makePaths(this, resApk.getApplicationInfo(), oldPaths);
5715 resApk.updateApplicationInfo(ai, oldPaths);
5716 }
Winsond605e2d2019-02-11 16:05:51 -08005717
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005718 synchronized (mResourcesManager) {
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005719 // Update all affected Resources objects to use new ResourcesImpl
Winsond605e2d2019-02-11 16:05:51 -08005720 mResourcesManager.applyNewResourceDirsLocked(ai, oldResDirs);
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005721 }
5722
5723 ApplicationPackageManager.configurationChanged();
5724
5725 // Trigger a regular Configuration change event, only with a different assetsSeq number
5726 // so that we actually call through to all components.
Adam Lesinskia82b6262017-03-21 16:56:17 -07005727 // TODO(adamlesinski): Change this to make use of ActivityManager's upcoming ability to
5728 // store configurations per-process.
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005729 Configuration newConfig = new Configuration();
Adam Lesinskia82b6262017-03-21 16:56:17 -07005730 newConfig.assetsSeq = (mConfiguration != null ? mConfiguration.assetsSeq : 0) + 1;
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005731 handleConfigurationChanged(newConfig, null);
5732
Adrian Roos03dd48c2019-03-19 17:17:37 -04005733 // Preserve windows to avoid black flickers when overlays change.
5734 relaunchAllActivities(true /* preserveWindows */);
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005735 }
5736
Romain Guy46bfc482013-08-16 18:38:29 -07005737 static void freeTextLayoutCachesIfNeeded(int configDiff) {
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005738 if (configDiff != 0) {
5739 // Ask text layout engine to free its caches if there is a locale change
5740 boolean hasLocaleConfigChange = ((configDiff & ActivityInfo.CONFIG_LOCALE) != 0);
5741 if (hasLocaleConfigChange) {
5742 Canvas.freeTextLayoutCaches();
5743 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Cleared TextLayout Caches");
5744 }
5745 }
5746 }
5747
Garfield Tan0443b372019-01-04 15:00:13 -08005748 @Override
5749 public void updatePendingActivityConfiguration(IBinder activityToken,
5750 Configuration overrideConfig) {
5751 final ActivityClientRecord r;
5752 synchronized (mResourcesManager) {
5753 r = mActivities.get(activityToken);
5754 }
5755
5756 if (r == null) {
5757 if (DEBUG_CONFIGURATION) {
5758 Slog.w(TAG, "Not found target activity to update its pending config.");
5759 }
5760 return;
5761 }
5762
5763 synchronized (r) {
5764 r.mPendingOverrideConfig = overrideConfig;
5765 }
5766 }
5767
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005768 /**
5769 * Handle new activity configuration and/or move to a different display.
Andrii Kulian446e8242017-10-26 15:17:29 -07005770 * @param activityToken Target activity token.
5771 * @param overrideConfig Activity override config.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005772 * @param displayId Id of the display where activity was moved to, -1 if there was no move and
5773 * value didn't change.
5774 */
Andrii Kulian446e8242017-10-26 15:17:29 -07005775 @Override
5776 public void handleActivityConfigurationChanged(IBinder activityToken,
5777 Configuration overrideConfig, int displayId) {
5778 ActivityClientRecord r = mActivities.get(activityToken);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005779 // Check input params.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005780 if (r == null || r.activity == null) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005781 if (DEBUG_CONFIGURATION) Slog.w(TAG, "Not found target activity to report to: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005782 return;
5783 }
Andrii Kulian51c1b672017-04-07 18:39:32 -07005784 final boolean movedToDifferentDisplay = displayId != INVALID_DISPLAY
Yohei Yukawa5281b6b2018-10-15 07:38:25 +08005785 && displayId != r.activity.getDisplayId();
Bob Leee5408332009-09-04 18:31:17 -07005786
Garfield Tan0443b372019-01-04 15:00:13 -08005787 synchronized (r) {
5788 if (r.mPendingOverrideConfig != null
5789 && !r.mPendingOverrideConfig.isOtherSeqNewer(overrideConfig)) {
5790 overrideConfig = r.mPendingOverrideConfig;
5791 }
5792 r.mPendingOverrideConfig = null;
5793 }
5794
5795 if (r.overrideConfig != null && !r.overrideConfig.isOtherSeqNewer(overrideConfig)
5796 && !movedToDifferentDisplay) {
5797 if (DEBUG_CONFIGURATION) {
5798 Slog.v(TAG, "Activity already handled newer configuration so drop this"
5799 + " transaction. overrideConfig=" + overrideConfig + " r.overrideConfig="
5800 + r.overrideConfig);
5801 }
5802 return;
5803 }
5804
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005805 // Perform updates.
Andrii Kulian446e8242017-10-26 15:17:29 -07005806 r.overrideConfig = overrideConfig;
Stephen Kiazykf903b732017-03-20 16:23:45 -07005807 final ViewRootImpl viewRoot = r.activity.mDecor != null
5808 ? r.activity.mDecor.getViewRootImpl() : null;
5809
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005810 if (movedToDifferentDisplay) {
5811 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity moved to display, activity:"
5812 + r.activityInfo.name + ", displayId=" + displayId
Andrii Kulian446e8242017-10-26 15:17:29 -07005813 + ", config=" + overrideConfig);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005814
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005815 final Configuration reportedConfig = performConfigurationChangedForActivity(r,
5816 mCompatConfiguration, displayId, true /* movedToDifferentDisplay */);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005817 if (viewRoot != null) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005818 viewRoot.onMovedToDisplay(displayId, reportedConfig);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005819 }
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005820 } else {
5821 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Andrii Kulian446e8242017-10-26 15:17:29 -07005822 + r.activityInfo.name + ", config=" + overrideConfig);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005823 performConfigurationChangedForActivity(r, mCompatConfiguration);
5824 }
Andrii Kulian44607962017-03-16 11:06:24 -07005825 // Notify the ViewRootImpl instance about configuration changes. It may have initiated this
5826 // update to make sure that resources are updated before updating itself.
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005827 if (viewRoot != null) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005828 viewRoot.updateConfiguration(displayId);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005829 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07005830 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005831 }
5832
Jeff Hao1b012d32014-08-20 10:35:34 -07005833 final void handleProfilerControl(boolean start, ProfilerInfo profilerInfo, int profileType) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005834 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005835 try {
Romain Guy7eabe552011-07-21 14:56:34 -07005836 switch (profileType) {
Jeff Hao1b012d32014-08-20 10:35:34 -07005837 default:
5838 mProfiler.setProfiler(profilerInfo);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005839 mProfiler.startProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07005840 break;
5841 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005842 } catch (RuntimeException e) {
Jeff Hao1b012d32014-08-20 10:35:34 -07005843 Slog.w(TAG, "Profiling failed on path " + profilerInfo.profileFile
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005844 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07005845 } finally {
Andreas Gampe2b073a02017-06-22 17:28:57 -07005846 profilerInfo.closeFd();
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005847 }
5848 } else {
Romain Guy7eabe552011-07-21 14:56:34 -07005849 switch (profileType) {
Romain Guy7eabe552011-07-21 14:56:34 -07005850 default:
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005851 mProfiler.stopProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07005852 break;
Romain Guy7eabe552011-07-21 14:56:34 -07005853 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005854 }
5855 }
Bob Leee5408332009-09-04 18:31:17 -07005856
Andreas Gampe4c79fea2016-01-28 20:11:41 -08005857 /**
5858 * Public entrypoint to stop profiling. This is required to end profiling when the app crashes,
5859 * so that profiler data won't be lost.
5860 *
5861 * @hide
5862 */
5863 public void stopProfiling() {
Amith Yamasanib1684432017-01-26 14:57:20 -08005864 if (mProfiler != null) {
5865 mProfiler.stopProfiling();
5866 }
Andreas Gampe4c79fea2016-01-28 20:11:41 -08005867 }
5868
Christopher Ferris8d652f82017-04-11 16:29:18 -07005869 static void handleDumpHeap(DumpHeapData dhd) {
Makoto Onuki4556b7b2017-07-07 14:58:58 -07005870 if (dhd.runGc) {
5871 System.gc();
5872 System.runFinalization();
5873 System.gc();
5874 }
Kweku Adams4af1b502019-05-23 16:23:48 -07005875 try (ParcelFileDescriptor fd = dhd.fd) {
5876 if (dhd.managed) {
5877 Debug.dumpHprofData(dhd.path, fd.getFileDescriptor());
5878 } else if (dhd.mallocInfo) {
5879 Debug.dumpNativeMallocInfo(fd.getFileDescriptor());
5880 } else {
5881 Debug.dumpNativeHeap(fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07005882 }
Kweku Adams4af1b502019-05-23 16:23:48 -07005883 } catch (IOException e) {
5884 if (dhd.managed) {
5885 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
5886 + " -- can the process access this path?", e);
5887 } else {
5888 Slog.w(TAG, "Failed to dump heap", e);
5889 }
5890 } catch (RuntimeException e) {
5891 // This should no longer happening now that we're copying the file descriptor.
5892 Slog.wtf(TAG, "Heap dumper threw a runtime exception", e);
Andy McFadden824c5102010-07-09 16:26:57 -07005893 }
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005894 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005895 ActivityManager.getService().dumpHeapFinished(dhd.path);
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005896 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005897 throw e.rethrowFromSystemServer();
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005898 }
Makoto Onuki2c6657f2018-06-06 15:24:02 -07005899 if (dhd.finishCallback != null) {
5900 dhd.finishCallback.sendResult(null);
5901 }
Andy McFadden824c5102010-07-09 16:26:57 -07005902 }
5903
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005904 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005905 boolean hasPkgInfo = false;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005906 switch (cmd) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005907 case ApplicationThreadConstants.PACKAGE_REMOVED:
5908 case ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL:
Todd Kennedy39bfee52016-02-24 10:28:21 -08005909 {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005910 final boolean killApp = cmd == ApplicationThreadConstants.PACKAGE_REMOVED;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005911 if (packages == null) {
5912 break;
5913 }
5914 synchronized (mResourcesManager) {
5915 for (int i = packages.length - 1; i >= 0; i--) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005916 if (!hasPkgInfo) {
Todd Kennedy39bfee52016-02-24 10:28:21 -08005917 WeakReference<LoadedApk> ref = mPackages.get(packages[i]);
5918 if (ref != null && ref.get() != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005919 hasPkgInfo = true;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005920 } else {
5921 ref = mResourcePackages.get(packages[i]);
5922 if (ref != null && ref.get() != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005923 hasPkgInfo = true;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005924 }
5925 }
5926 }
5927 if (killApp) {
5928 mPackages.remove(packages[i]);
5929 mResourcePackages.remove(packages[i]);
5930 }
5931 }
5932 }
5933 break;
5934 }
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005935 case ApplicationThreadConstants.PACKAGE_REPLACED:
Todd Kennedy39bfee52016-02-24 10:28:21 -08005936 {
5937 if (packages == null) {
5938 break;
5939 }
Winson23863be2019-04-04 17:41:28 -07005940
5941 List<String> packagesHandled = new ArrayList<>();
5942
Todd Kennedy39bfee52016-02-24 10:28:21 -08005943 synchronized (mResourcesManager) {
5944 for (int i = packages.length - 1; i >= 0; i--) {
Winson23863be2019-04-04 17:41:28 -07005945 String packageName = packages[i];
5946 WeakReference<LoadedApk> ref = mPackages.get(packageName);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005947 LoadedApk pkgInfo = ref != null ? ref.get() : null;
5948 if (pkgInfo != null) {
5949 hasPkgInfo = true;
mark_chen89764e32014-12-12 15:38:48 +08005950 } else {
Winson23863be2019-04-04 17:41:28 -07005951 ref = mResourcePackages.get(packageName);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005952 pkgInfo = ref != null ? ref.get() : null;
5953 if (pkgInfo != null) {
5954 hasPkgInfo = true;
mark_chen89764e32014-12-12 15:38:48 +08005955 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005956 }
Todd Kennedy39bfee52016-02-24 10:28:21 -08005957 // If the package is being replaced, yet it still has a valid
5958 // LoadedApk object, the package was updated with _DONT_KILL.
5959 // Adjust it's internal references to the application info and
5960 // resources.
Todd Kennedy233a0b12018-01-29 20:30:24 +00005961 if (pkgInfo != null) {
Winson23863be2019-04-04 17:41:28 -07005962 packagesHandled.add(packageName);
Todd Kennedy39bfee52016-02-24 10:28:21 -08005963 try {
Todd Kennedy39bfee52016-02-24 10:28:21 -08005964 final ApplicationInfo aInfo =
5965 sPackageManager.getApplicationInfo(
5966 packageName,
Svet Ganov6ce92392017-09-27 16:04:10 -07005967 PackageManager.GET_SHARED_LIBRARY_FILES,
Todd Kennedy39bfee52016-02-24 10:28:21 -08005968 UserHandle.myUserId());
5969
5970 if (mActivities.size() > 0) {
5971 for (ActivityClientRecord ar : mActivities.values()) {
5972 if (ar.activityInfo.applicationInfo.packageName
5973 .equals(packageName)) {
5974 ar.activityInfo.applicationInfo = aInfo;
Todd Kennedy233a0b12018-01-29 20:30:24 +00005975 ar.packageInfo = pkgInfo;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005976 }
5977 }
5978 }
Winsond605e2d2019-02-11 16:05:51 -08005979
5980 final String[] oldResDirs = { pkgInfo.getResDir() };
5981
Todd Kennedyb9656a92018-05-02 10:59:45 +01005982 final ArrayList<String> oldPaths = new ArrayList<>();
5983 LoadedApk.makePaths(this, pkgInfo.getApplicationInfo(), oldPaths);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005984 pkgInfo.updateApplicationInfo(aInfo, oldPaths);
Winsond605e2d2019-02-11 16:05:51 -08005985
5986 synchronized (mResourcesManager) {
5987 // Update affected Resources objects to use new ResourcesImpl
5988 mResourcesManager.applyNewResourceDirsLocked(aInfo, oldResDirs);
5989 }
Todd Kennedy39bfee52016-02-24 10:28:21 -08005990 } catch (RemoteException e) {
5991 }
5992 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005993 }
5994 }
Winson23863be2019-04-04 17:41:28 -07005995
5996 try {
5997 getPackageManager().notifyPackagesReplacedReceived(
5998 packagesHandled.toArray(new String[0]));
5999 } catch (RemoteException ignored) {
6000 }
6001
Todd Kennedy39bfee52016-02-24 10:28:21 -08006002 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07006003 }
6004 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00006005 ApplicationPackageManager.handlePackageBroadcast(cmd, packages, hasPkgInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07006006 }
Tim Murraye1e6c662015-04-07 13:24:14 -07006007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006008 final void handleLowMemory() {
Dianne Hackborn73c14162012-09-19 15:45:06 -07006009 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(true, null);
Bob Leee5408332009-09-04 18:31:17 -07006010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006011 final int N = callbacks.size();
6012 for (int i=0; i<N; i++) {
6013 callbacks.get(i).onLowMemory();
6014 }
6015
Chris Tatece229052009-03-25 16:44:52 -07006016 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
6017 if (Process.myUid() != Process.SYSTEM_UID) {
6018 int sqliteReleased = SQLiteDatabase.releaseMemory();
6019 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
6020 }
Bob Leee5408332009-09-04 18:31:17 -07006021
Mike Reedcaf0df12009-04-27 14:32:05 -04006022 // Ask graphics to free up as much as possible (font/image caches)
6023 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006024
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07006025 // Ask text layout engine to free also as much as possible
6026 Canvas.freeTextLayoutCaches();
6027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006028 BinderInternal.forceGc("mem");
6029 }
6030
Jorim Jaggib29e3182018-04-30 18:51:56 +02006031 private void handleTrimMemory(int level) {
6032 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "trimMemory");
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07006033 if (DEBUG_MEMORY_TRIM) Slog.v(TAG, "Trimming memory to level: " + level);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07006034
Dianne Hackborn73c14162012-09-19 15:45:06 -07006035 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(true, null);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07006036
6037 final int N = callbacks.size();
Romain Guya998dff2012-03-23 18:58:36 -07006038 for (int i = 0; i < N; i++) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07006039 callbacks.get(i).onTrimMemory(level);
6040 }
Romain Guy19f86e82012-04-23 15:19:07 -07006041
John Reckf47a5942014-06-30 16:20:04 -07006042 WindowManagerGlobal.getInstance().trimMemory(level);
Jorim Jaggib29e3182018-04-30 18:51:56 +02006043 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Makoto Onuki0a9ee1a2019-06-19 08:58:02 -07006044
6045 if (SystemProperties.getInt("debug.am.run_gc_trim_level", Integer.MAX_VALUE) <= level) {
6046 unscheduleGcIdler();
6047 doGcIfNeeded("tm");
6048 }
6049 if (SystemProperties.getInt("debug.am.run_mallopt_trim_level", Integer.MAX_VALUE)
6050 <= level) {
6051 unschedulePurgeIdler();
6052 purgePendingResources();
6053 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006054 }
6055
Jesse Hall317fa5a2017-05-23 15:46:55 -07006056 private void setupGraphicsSupport(Context context) {
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006057 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setupGraphicsSupport");
Romain Guya9582652011-11-10 14:20:10 -08006058
Jesse Hall317fa5a2017-05-23 15:46:55 -07006059 // The system package doesn't have real data directories, so don't set up cache paths.
6060 if (!"android".equals(context.getPackageName())) {
6061 // This cache location probably points at credential-encrypted
6062 // storage which may not be accessible yet; assign it anyway instead
6063 // of pointing at device-encrypted storage.
6064 final File cacheDir = context.getCacheDir();
6065 if (cacheDir != null) {
6066 // Provide a usable directory for temporary files
6067 System.setProperty("java.io.tmpdir", cacheDir.getAbsolutePath());
6068 } else {
6069 Log.v(TAG, "Unable to initialize \"java.io.tmpdir\" property "
6070 + "due to missing cache directory");
Romain Guya9582652011-11-10 14:20:10 -08006071 }
Jesse Hall317fa5a2017-05-23 15:46:55 -07006072
6073 // Setup a location to store generated/compiled graphics code.
6074 final Context deviceContext = context.createDeviceProtectedStorageContext();
6075 final File codeCacheDir = deviceContext.getCodeCacheDir();
6076 if (codeCacheDir != null) {
6077 try {
6078 int uid = Process.myUid();
6079 String[] packages = getPackageManager().getPackagesForUid(uid);
6080 if (packages != null) {
John Reck8785ceb2018-10-29 16:45:58 -07006081 HardwareRenderer.setupDiskCache(codeCacheDir);
Romain Guycecbe072017-07-18 15:42:06 -07006082 RenderScriptCacheDir.setupDiskCache(codeCacheDir);
Jesse Hall317fa5a2017-05-23 15:46:55 -07006083 }
6084 } catch (RemoteException e) {
6085 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6086 throw e.rethrowFromSystemServer();
6087 }
6088 } else {
6089 Log.w(TAG, "Unable to use shader/script cache: missing code-cache directory");
6090 }
Romain Guya9582652011-11-10 14:20:10 -08006091 }
Jesse Hall317fa5a2017-05-23 15:46:55 -07006092
Cody Northropdeb43282018-10-04 16:04:05 -06006093 GraphicsEnvironment.getInstance().setup(context, mCoreSettings);
Jesse Hall317fa5a2017-05-23 15:46:55 -07006094 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborndde331c2012-08-03 14:01:57 -07006095 }
6096
6097 private void updateDefaultDensity() {
Alan Viverette2ac46f12016-02-04 16:58:14 -05006098 final int densityDpi = mCurDefaultDisplayDpi;
6099 if (!mDensityCompatMode
6100 && densityDpi != Configuration.DENSITY_DPI_UNDEFINED
6101 && densityDpi != DisplayMetrics.DENSITY_DEVICE) {
6102 DisplayMetrics.DENSITY_DEVICE = densityDpi;
6103 Bitmap.setDefaultDensity(densityDpi);
Dianne Hackborndde331c2012-08-03 14:01:57 -07006104 }
6105 }
6106
Todd Kennedye713efc2016-05-10 13:45:40 -07006107 /**
6108 * Returns the correct library directory for the current ABI.
6109 * <p>
6110 * If we're dealing with a multi-arch application that has both 32 and 64 bit shared
6111 * libraries, we might need to choose the secondary depending on what the current
6112 * runtime's instruction set is.
6113 */
6114 private String getInstrumentationLibrary(ApplicationInfo appInfo, InstrumentationInfo insInfo) {
Patrick Baumanneb595802018-04-17 09:49:55 -07006115 if (appInfo.primaryCpuAbi != null && appInfo.secondaryCpuAbi != null
6116 && appInfo.secondaryCpuAbi.equals(insInfo.secondaryCpuAbi)) {
Todd Kennedye713efc2016-05-10 13:45:40 -07006117 // Get the instruction set supported by the secondary ABI. In the presence
6118 // of a native bridge this might be different than the one secondary ABI used.
6119 String secondaryIsa =
6120 VMRuntime.getInstructionSet(appInfo.secondaryCpuAbi);
6121 final String secondaryDexCodeIsa =
6122 SystemProperties.get("ro.dalvik.vm.isa." + secondaryIsa);
6123 secondaryIsa = secondaryDexCodeIsa.isEmpty() ? secondaryIsa : secondaryDexCodeIsa;
6124
6125 final String runtimeIsa = VMRuntime.getRuntime().vmInstructionSet();
6126 if (runtimeIsa.equals(secondaryIsa)) {
6127 return insInfo.secondaryNativeLibraryDir;
6128 }
6129 }
6130 return insInfo.nativeLibraryDir;
6131 }
6132
Adam Lesinskib61e4052016-05-19 18:23:05 -07006133 /**
6134 * The LocaleList set for the app's resources may have been shuffled so that the preferred
6135 * Locale is at position 0. We must find the index of this preferred Locale in the
6136 * original LocaleList.
6137 */
6138 private void updateLocaleListFromAppContext(Context context, LocaleList newLocaleList) {
6139 final Locale bestLocale = context.getResources().getConfiguration().getLocales().get(0);
6140 final int newLocaleListSize = newLocaleList.size();
6141 for (int i = 0; i < newLocaleListSize; i++) {
6142 if (bestLocale.equals(newLocaleList.get(i))) {
6143 LocaleList.setDefault(newLocaleList, i);
6144 return;
6145 }
6146 }
Adam Lesinski27d30162016-05-25 16:45:14 -07006147
6148 // The app may have overridden the LocaleList with its own Locale
6149 // (not present in the available list). Push the chosen Locale
6150 // to the front of the list.
6151 LocaleList.setDefault(new LocaleList(bestLocale, newLocaleList));
Adam Lesinskib61e4052016-05-19 18:23:05 -07006152 }
6153
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006154 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07006155 private void handleBindApplication(AppBindData data) {
Calin Juravle8f5770d2016-04-12 14:12:04 +01006156 // Register the UI Thread as a sensitive thread to the runtime.
6157 VMRuntime.registerSensitiveThread();
Mathieu Chartier90aa9452019-03-29 13:49:35 -07006158 // In the case the stack depth property exists, pass it down to the runtime.
6159 String property = SystemProperties.get("debug.allocTracker.stackDepth");
6160 if (property.length() != 0) {
6161 VMDebug.setAllocTrackerStackDepth(Integer.parseInt(property));
6162 }
Man Caocfa78b22015-06-11 20:14:34 -07006163 if (data.trackAllocation) {
6164 DdmVmInternal.enableRecentAllocations(true);
6165 }
6166
Dianne Hackbornd98885c2016-03-01 17:13:03 -08006167 // Note when this process has started.
6168 Process.setStartTimes(SystemClock.elapsedRealtime(), SystemClock.uptimeMillis());
6169
Mathew Inwooda1b39022019-06-24 12:07:22 +01006170 AppCompatCallbacks.install(data.disabledCompatChanges);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 mBoundApplication = data;
6172 mConfiguration = new Configuration(data.config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07006173 mCompatConfiguration = new Configuration(data.config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006174
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07006175 mProfiler = new Profiler();
Andreas Gampeab8a63b2018-01-05 13:55:15 -08006176 String agent = null;
Jeff Hao1b012d32014-08-20 10:35:34 -07006177 if (data.initProfilerInfo != null) {
6178 mProfiler.profileFile = data.initProfilerInfo.profileFile;
6179 mProfiler.profileFd = data.initProfilerInfo.profileFd;
6180 mProfiler.samplingInterval = data.initProfilerInfo.samplingInterval;
6181 mProfiler.autoStopProfiler = data.initProfilerInfo.autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -08006182 mProfiler.streamingOutput = data.initProfilerInfo.streamingOutput;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08006183 if (data.initProfilerInfo.attachAgentDuringBind) {
6184 agent = data.initProfilerInfo.agent;
6185 }
Jeff Hao1b012d32014-08-20 10:35:34 -07006186 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07006187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006188 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08006189 Process.setArgV0(data.processName);
Siva Velusamyd693dfa2012-09-10 14:36:58 -07006190 android.ddm.DdmHandleAppName.setAppName(data.processName,
6191 UserHandle.myUserId());
Mathew Inwood37b6ca82018-05-02 10:42:23 +01006192 VMRuntime.setProcessPackageName(data.appInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193
David Brazdil06f2e1292019-04-03 13:00:55 +01006194 // Pass data directory path to ART. This is used for caching information and
6195 // should be set before any application code is loaded.
6196 VMRuntime.setProcessDataDirectory(data.appInfo.dataDir);
6197
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07006198 if (mProfiler.profileFd != null) {
6199 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006200 }
6201
Joe Onoratod630f102011-03-17 18:42:26 -07006202 // If the app is Honeycomb MR1 or earlier, switch its AsyncTask
6203 // implementation to use the pool executor. Normally, we use the
6204 // serialized executor as the default. This has to happen in the
6205 // main thread so the main looper is set right.
Dianne Hackborn81e92762011-10-09 16:00:21 -07006206 if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
Joe Onoratod630f102011-03-17 18:42:26 -07006207 AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
6208 }
6209
Kweku Adams4be0b1a2019-04-25 16:16:34 -07006210 // Let the util.*Array classes maintain "undefined" for apps targeting Pie or earlier.
6211 UtilConfig.setThrowExceptionForUpperArrayOutOfBounds(
6212 data.appInfo.targetSdkVersion >= Build.VERSION_CODES.Q);
6213
Dianne Hackborn7895bc22014-09-05 15:09:03 -07006214 Message.updateCheckRecycle(data.appInfo.targetSdkVersion);
6215
Leon Scroggins III8290eab2018-03-19 10:51:44 -04006216 // Prior to P, internal calls to decode Bitmaps used BitmapFactory,
6217 // which may scale up to account for density. In P, we switched to
6218 // ImageDecoder, which skips the upscale to save memory. ImageDecoder
6219 // needs to still scale up in older apps, in case they rely on the
6220 // size of the Bitmap without considering its density.
6221 ImageDecoder.sApiLevel = data.appInfo.targetSdkVersion;
6222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006223 /*
6224 * Before spawning a new process, reset the time zone to be the system time zone.
6225 * This needs to be done because the system time zone could have changed after the
6226 * the spawning of this process. Without doing this this process would have the incorrect
6227 * system time zone.
6228 */
6229 TimeZone.setDefault(null);
6230
Adam Lesinskib61e4052016-05-19 18:23:05 -07006231 /*
6232 * Set the LocaleList. This may change once we create the App Context.
6233 */
6234 LocaleList.setDefault(data.config.getLocales());
6235
6236 synchronized (mResourcesManager) {
6237 /*
6238 * Update the system configuration since its preloaded and might not
6239 * reflect configuration changes. The configuration object passed
6240 * in AppBindData can be safely assumed to be up to date
6241 */
6242 mResourcesManager.applyConfigurationToResourcesLocked(data.config, data.compatInfo);
6243 mCurDefaultDisplayDpi = data.config.densityDpi;
6244
6245 // This calls mResourcesManager so keep it within the synchronized block.
6246 applyCompatConfiguration(mCurDefaultDisplayDpi);
6247 }
6248
Todd Kennedy233a0b12018-01-29 20:30:24 +00006249 data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250
Andreas Gampeab8a63b2018-01-05 13:55:15 -08006251 if (agent != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00006252 handleAttachAgent(agent, data.info);
Andreas Gampeab8a63b2018-01-05 13:55:15 -08006253 }
6254
Dianne Hackborndde331c2012-08-03 14:01:57 -07006255 /**
6256 * Switch this process to density compatibility mode if needed.
6257 */
6258 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
6259 == 0) {
6260 mDensityCompatMode = true;
6261 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
6262 }
6263 updateDefaultDensity();
6264
Neil Fullerc66ec402016-11-14 16:06:42 +00006265 final String use24HourSetting = mCoreSettings.getString(Settings.System.TIME_12_24);
6266 Boolean is24Hr = null;
6267 if (use24HourSetting != null) {
6268 is24Hr = "24".equals(use24HourSetting) ? Boolean.TRUE : Boolean.FALSE;
6269 }
6270 // null : use locale default for 12/24 hour formatting,
6271 // false : use 12 hour format,
6272 // true : use 24 hour format.
Narayan Kamathccb2a0862013-12-19 14:49:36 +00006273 DateFormat.set24HourTimePref(is24Hr);
6274
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08006275 updateDebugViewAttributeState();
Jon Miranda836c0a82014-08-11 12:32:26 -07006276
Jeff Sharkey89182982017-11-01 19:02:56 -06006277 StrictMode.initThreadDefaults(data.appInfo);
6278 StrictMode.initVmDefaults(data.appInfo);
Jeff Sharkey344744b2016-01-28 19:03:30 -07006279
Sudheer Shankacc6418f2016-10-13 12:03:44 -07006280 if (data.debugMode != ApplicationThreadConstants.DEBUG_OFF) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006281 // XXX should have option to change the port.
6282 Debug.changeDebugPort(8100);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07006283 if (data.debugMode == ApplicationThreadConstants.DEBUG_WAIT) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00006284 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006285 + " is waiting for the debugger on port 8100...");
6286
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006287 IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 try {
6289 mgr.showWaitingForDebugger(mAppThread, true);
6290 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006291 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 }
6293
6294 Debug.waitForDebugger();
6295
6296 try {
6297 mgr.showWaitingForDebugger(mAppThread, false);
6298 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006299 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006300 }
6301
6302 } else {
Todd Kennedy233a0b12018-01-29 20:30:24 +00006303 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304 + " can be debugged on port 8100...");
6305 }
6306 }
6307
Chris Craikce030282018-10-16 14:33:11 -07006308 // Allow binder tracing, and application-generated systrace messages if we're profileable.
6309 boolean isAppProfileable = data.appInfo.isProfileableByShell();
6310 Trace.setAppTracingAllowed(isAppProfileable);
6311 if (isAppProfileable && data.enableBinderTracking) {
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04006312 Binder.enableTracing();
6313 }
Jamie Gennisf9c7d6b2013-03-25 14:18:25 -07006314
Ryan Savitskicfdc1512018-12-14 16:20:52 +00006315 // Initialize heap profiling.
6316 if (isAppProfileable || Build.IS_DEBUGGABLE) {
6317 nInitZygoteChildHeapProfiling();
6318 }
6319
Chris Craikce030282018-10-16 14:33:11 -07006320 // Allow renderer debugging features if we're debuggable.
6321 boolean isAppDebuggable = (data.appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
John Reck8785ceb2018-10-29 16:45:58 -07006322 HardwareRenderer.setDebuggingEnabled(isAppDebuggable || Build.IS_DEBUGGABLE);
6323 HardwareRenderer.setPackageName(data.appInfo.packageName);
Chris Craikce030282018-10-16 14:33:11 -07006324
Robert Greenwalt434203a2010-10-11 16:00:27 -07006325 /**
6326 * Initialize the default http proxy in this process for the reasons we set the time zone.
6327 */
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006328 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Setup proxies");
Alan Viverettebe64eae2015-09-03 14:56:04 -04006329 final IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08006330 if (b != null) {
6331 // In pre-boot mode (doing initial launch to collect password), not
6332 // all system is up. This includes the connectivity service, so don't
6333 // crash if we can't get it.
Alan Viverettebe64eae2015-09-03 14:56:04 -04006334 final IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08006335 try {
Irina Dumitrescu18622d32018-12-05 16:19:47 +00006336 Proxy.setHttpProxySystemProperty(service.getProxyForNetwork(null));
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006337 } catch (RemoteException e) {
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006338 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006339 throw e.rethrowFromSystemServer();
6340 }
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08006341 }
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006342 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Robert Greenwalt434203a2010-10-11 16:00:27 -07006343
Alan Viverette2107d692015-09-03 14:55:27 -04006344 // Instrumentation info affects the class loader, so load it before
6345 // setting up the app context.
6346 final InstrumentationInfo ii;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006347 if (data.instrumentationName != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006348 try {
Alan Viverette2107d692015-09-03 14:55:27 -04006349 ii = new ApplicationPackageManager(null, getPackageManager())
6350 .getInstrumentationInfo(data.instrumentationName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351 } catch (PackageManager.NameNotFoundException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006352 throw new RuntimeException(
Alan Viverette2107d692015-09-03 14:55:27 -04006353 "Unable to find instrumentation info for: " + data.instrumentationName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006354 }
6355
Patrick Baumanneb595802018-04-17 09:49:55 -07006356 // Warn of potential ABI mismatches.
6357 if (!Objects.equals(data.appInfo.primaryCpuAbi, ii.primaryCpuAbi)
6358 || !Objects.equals(data.appInfo.secondaryCpuAbi, ii.secondaryCpuAbi)) {
6359 Slog.w(TAG, "Package uses different ABI(s) than its instrumentation: "
6360 + "package[" + data.appInfo.packageName + "]: "
6361 + data.appInfo.primaryCpuAbi + ", " + data.appInfo.secondaryCpuAbi
6362 + " instrumentation[" + ii.packageName + "]: "
6363 + ii.primaryCpuAbi + ", " + ii.secondaryCpuAbi);
6364 }
6365
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07006366 mInstrumentationPackageName = ii.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 mInstrumentationAppDir = ii.sourceDir;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07006368 mInstrumentationSplitAppDirs = ii.splitSourceDirs;
Todd Kennedye713efc2016-05-10 13:45:40 -07006369 mInstrumentationLibDir = getInstrumentationLibrary(data.appInfo, ii);
Todd Kennedy233a0b12018-01-29 20:30:24 +00006370 mInstrumentedAppDir = data.info.getAppDir();
6371 mInstrumentedSplitAppDirs = data.info.getSplitAppDirs();
6372 mInstrumentedLibDir = data.info.getLibDir();
Alan Viverette2107d692015-09-03 14:55:27 -04006373 } else {
6374 ii = null;
6375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006376
Todd Kennedy233a0b12018-01-29 20:30:24 +00006377 final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
Adam Lesinskib61e4052016-05-19 18:23:05 -07006378 updateLocaleListFromAppContext(appContext,
6379 mResourcesManager.getConfiguration().getLocales());
Seigo Nonakac14dd782016-03-30 23:09:16 +09006380
Jesse Hall317fa5a2017-05-23 15:46:55 -07006381 if (!Process.isIsolated()) {
Jeff Sharkey89182982017-11-01 19:02:56 -06006382 final int oldMask = StrictMode.allowThreadDiskWritesMask();
6383 try {
6384 setupGraphicsSupport(appContext);
6385 } finally {
6386 StrictMode.setThreadPolicyMask(oldMask);
6387 }
John Reck56428472018-03-16 17:27:17 -07006388 } else {
John Reck8785ceb2018-10-29 16:45:58 -07006389 HardwareRenderer.setIsolatedProcess(true);
Michael Lentine2ba303f2016-02-01 20:44:34 -06006390 }
Michael Lentine03d8f7682016-01-31 15:37:11 -06006391
Chad Brubaker78d47122015-11-17 22:26:58 -08006392 // Install the Network Security Config Provider. This must happen before the application
6393 // code is loaded to prevent issues with instances of TLS objects being created before
6394 // the provider is installed.
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006395 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "NetworkSecurityConfigProvider.install");
Chad Brubaker276ee962016-06-08 12:57:46 -07006396 NetworkSecurityConfigProvider.install(appContext);
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006397 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Chad Brubaker78d47122015-11-17 22:26:58 -08006398
Alan Viverette2107d692015-09-03 14:55:27 -04006399 // Continue loading instrumentation.
6400 if (ii != null) {
Dianne Hackbornf4ef6eb2017-12-07 13:57:21 -08006401 ApplicationInfo instrApp;
6402 try {
6403 instrApp = getPackageManager().getApplicationInfo(ii.packageName, 0,
6404 UserHandle.myUserId());
6405 } catch (RemoteException e) {
6406 instrApp = null;
6407 }
6408 if (instrApp == null) {
6409 instrApp = new ApplicationInfo();
6410 }
Jeff Sharkey15447792015-11-05 16:18:51 -08006411 ii.copyTo(instrApp);
Fyodor Kupolovaf38b8e2015-12-02 16:16:07 -08006412 instrApp.initForUser(UserHandle.myUserId());
Todd Kennedy233a0b12018-01-29 20:30:24 +00006413 final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07006414 appContext.getClassLoader(), false, true, false);
Makoto Onuki4becc352019-01-30 13:30:41 -08006415
6416 // The test context's op package name == the target app's op package name, because
6417 // the app ops manager checks the op package name against the real calling UID,
6418 // which is what the target package name is associated with.
6419 final ContextImpl instrContext = ContextImpl.createAppContext(this, pi,
6420 appContext.getOpPackageName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006421
6422 try {
Alan Viverettebe64eae2015-09-03 14:56:04 -04006423 final ClassLoader cl = instrContext.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04006424 mInstrumentation = (Instrumentation)
6425 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006426 } catch (Exception e) {
6427 throw new RuntimeException(
6428 "Unable to instantiate instrumentation "
6429 + data.instrumentationName + ": " + e.toString(), e);
6430 }
6431
Alan Viverettebe64eae2015-09-03 14:56:04 -04006432 final ComponentName component = new ComponentName(ii.packageName, ii.name);
6433 mInstrumentation.init(this, instrContext, appContext, component,
6434 data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006435
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07006436 if (mProfiler.profileFile != null && !ii.handleProfiling
6437 && mProfiler.profileFd == null) {
6438 mProfiler.handlingProfiling = true;
Alan Viverettebe64eae2015-09-03 14:56:04 -04006439 final File file = new File(mProfiler.profileFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006440 file.getParentFile().mkdirs();
6441 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
6442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006443 } else {
6444 mInstrumentation = new Instrumentation();
Jason Monka80bfb52017-11-16 17:15:37 -05006445 mInstrumentation.basicInit(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006446 }
6447
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08006448 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
Dianne Hackbornde398512011-01-18 18:45:21 -08006449 dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
Mathieu Chartier24cee072015-01-08 14:42:20 -08006450 } else {
6451 // Small heap, clamp to the current growth limit and let the heap release
6452 // pages after the growth limit to the non growth limit capacity. b/18387825
6453 dalvik.system.VMRuntime.getRuntime().clampGrowthLimit();
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08006454 }
6455
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006456 // Allow disk access during application and provider setup. This could
Jeff Sharkey7c501672012-02-28 12:08:37 -08006457 // block processing ordered broadcasts, but later processing would
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006458 // probably end up doing the same disk access.
Kurt Nelson5e154362017-06-29 17:20:56 -07006459 Application app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08006460 final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
Kurt Nelson571c3f62017-07-10 11:09:04 -07006461 final StrictMode.ThreadPolicy writesAllowedPolicy = StrictMode.getThreadPolicy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 try {
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006463 // If the app is being launched for full backup or restore, bring it up in
6464 // a restricted environment with the base application class.
Todd Kennedy233a0b12018-01-29 20:30:24 +00006465 app = data.info.makeApplication(data.restrictedBackupMode, null);
Svetoslav Ganov24c90452017-12-27 15:17:14 -08006466
6467 // Propagate autofill compat state
Felipe Lemea4f39cd2019-02-19 15:08:59 -08006468 app.setAutofillOptions(data.autofillOptions);
Svetoslav Ganov24c90452017-12-27 15:17:14 -08006469
Felipe Leme326f15a2019-02-19 09:42:24 -08006470 // Propagate Content Capture options
6471 app.setContentCaptureOptions(data.contentCaptureOptions);
6472
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006473 mInitialApplication = app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08006474
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006475 // don't bring up providers in restricted mode; they may depend on the
6476 // app's custom Application class
6477 if (!data.restrictedBackupMode) {
Jeff Sharkey3e195892016-03-05 19:48:59 -07006478 if (!ArrayUtils.isEmpty(data.providers)) {
6479 installContentProviders(app, data.providers);
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006480 }
6481 }
6482
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006483 // Do this after providers, since instrumentation tests generally start their
6484 // test thread at this point, and we don't want that racing.
6485 try {
6486 mInstrumentation.onCreate(data.instrumentationArgs);
6487 }
6488 catch (Exception e) {
6489 throw new RuntimeException(
6490 "Exception thrown in onCreate() of "
6491 + data.instrumentationName + ": " + e.toString(), e);
6492 }
Kurt Nelson571c3f62017-07-10 11:09:04 -07006493 try {
6494 mInstrumentation.callApplicationOnCreate(app);
6495 } catch (Exception e) {
6496 if (!mInstrumentation.onException(app, e)) {
6497 throw new RuntimeException(
6498 "Unable to create application " + app.getClass().getName()
6499 + ": " + e.toString(), e);
6500 }
6501 }
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006502 } finally {
Kurt Nelson571c3f62017-07-10 11:09:04 -07006503 // If the app targets < O-MR1, or doesn't change the thread policy
6504 // during startup, clobber the policy to maintain behavior of b/36951662
Jeff Sharkeyaa1a9112018-04-10 15:18:12 -06006505 if (data.appInfo.targetSdkVersion < Build.VERSION_CODES.O_MR1
Kurt Nelson571c3f62017-07-10 11:09:04 -07006506 || StrictMode.getThreadPolicy().equals(writesAllowedPolicy)) {
6507 StrictMode.setThreadPolicy(savedPolicy);
Kurt Nelson5e154362017-06-29 17:20:56 -07006508 }
6509 }
6510
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00006511 // Preload fonts resources
Seigo Nonaka54084b62017-04-24 14:46:23 -07006512 FontsContract.setApplicationContextForResources(appContext);
Torne (Richard Coles)85ecae52018-01-30 18:13:00 -05006513 if (!Process.isIsolated()) {
6514 try {
6515 final ApplicationInfo info =
6516 getPackageManager().getApplicationInfo(
6517 data.appInfo.packageName,
6518 PackageManager.GET_META_DATA /*flags*/,
6519 UserHandle.myUserId());
6520 if (info.metaData != null) {
6521 final int preloadedFontsResource = info.metaData.getInt(
6522 ApplicationInfo.METADATA_PRELOADED_FONTS, 0);
6523 if (preloadedFontsResource != 0) {
6524 data.info.getResources().preloadFonts(preloadedFontsResource);
6525 }
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00006526 }
Torne (Richard Coles)85ecae52018-01-30 18:13:00 -05006527 } catch (RemoteException e) {
6528 throw e.rethrowFromSystemServer();
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00006529 }
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00006530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531 }
6532
6533 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006534 IActivityManager am = ActivityManager.getService();
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07006535 if (mProfiler.profileFile != null && mProfiler.handlingProfiling
6536 && mProfiler.profileFd == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006537 Debug.stopMethodTracing();
6538 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006539 //Slog.i(TAG, "am: " + ActivityManager.getService()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006540 // + ", app thr: " + mAppThread);
6541 try {
6542 am.finishInstrumentation(mAppThread, resultCode, results);
6543 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006544 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006545 }
6546 }
6547
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006548 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07006549 private void installContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006550 Context context, List<ProviderInfo> providers) {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006551 final ArrayList<ContentProviderHolder> results = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006552
Romain Guya998dff2012-03-23 18:58:36 -07006553 for (ProviderInfo cpi : providers) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08006554 if (DEBUG_PROVIDER) {
6555 StringBuilder buf = new StringBuilder(128);
6556 buf.append("Pub ");
6557 buf.append(cpi.authority);
6558 buf.append(": ");
6559 buf.append(cpi.name);
6560 Log.i(TAG, buf.toString());
6561 }
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006562 ContentProviderHolder cph = installProvider(context, null, cpi,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006563 false /*noisy*/, true /*noReleaseNeeded*/, true /*stable*/);
6564 if (cph != null) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006565 cph.noReleaseNeeded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006566 results.add(cph);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006567 }
6568 }
6569
6570 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006571 ActivityManager.getService().publishContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006572 getApplicationThread(), results);
6573 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006574 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006575 }
6576 }
6577
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006578 @UnsupportedAppUsage
Jeff Sharkey6d515712012-09-20 16:06:08 -07006579 public final IContentProvider acquireProvider(
6580 Context c, String auth, int userId, boolean stable) {
Wale Ogunwale1d646122015-04-24 14:45:14 -07006581 final IContentProvider provider = acquireExistingProvider(c, auth, userId, stable);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006582 if (provider != null) {
6583 return provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006584 }
6585
Wale Ogunwale1d646122015-04-24 14:45:14 -07006586 // There is a possible race here. Another thread may try to acquire
6587 // the same provider at the same time. When this happens, we want to ensure
6588 // that the first one wins.
6589 // Note that we cannot hold the lock while acquiring and installing the
6590 // provider since it might take a long time to run and it could also potentially
6591 // be re-entrant in the case where the provider is in the same process.
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006592 ContentProviderHolder holder = null;
Wale Ogunwale1d646122015-04-24 14:45:14 -07006593 try {
Makoto Onukib6c79ea2018-05-31 11:03:56 -07006594 synchronized (getGetProviderLock(auth, userId)) {
6595 holder = ActivityManager.getService().getContentProvider(
Dianne Hackborn24bbe582018-12-17 11:58:31 -08006596 getApplicationThread(), c.getOpPackageName(), auth, userId, stable);
Makoto Onukib6c79ea2018-05-31 11:03:56 -07006597 }
Wale Ogunwale1d646122015-04-24 14:45:14 -07006598 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006599 throw ex.rethrowFromSystemServer();
Wale Ogunwale67fe0a42015-04-24 14:44:54 -07006600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006601 if (holder == null) {
Jeff Sharkey6d515712012-09-20 16:06:08 -07006602 Slog.e(TAG, "Failed to find provider info for " + auth);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006603 return null;
6604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006605
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006606 // Install provider will increment the reference count for us, and break
6607 // any ties in the race.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006608 holder = installProvider(c, holder, holder.info,
6609 true /*noisy*/, holder.noReleaseNeeded, stable);
6610 return holder.provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006611 }
6612
Makoto Onukib6c79ea2018-05-31 11:03:56 -07006613 private Object getGetProviderLock(String auth, int userId) {
6614 final ProviderKey key = new ProviderKey(auth, userId);
6615 synchronized (mGetProviderLocks) {
6616 Object lock = mGetProviderLocks.get(key);
6617 if (lock == null) {
6618 lock = key;
6619 mGetProviderLocks.put(key, lock);
6620 }
6621 return lock;
6622 }
6623 }
6624
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006625 private final void incProviderRefLocked(ProviderRefCount prc, boolean stable) {
6626 if (stable) {
6627 prc.stableCount += 1;
6628 if (prc.stableCount == 1) {
6629 // We are acquiring a new stable reference on the provider.
6630 int unstableDelta;
6631 if (prc.removePending) {
6632 // We have a pending remove operation, which is holding the
6633 // last unstable reference. At this point we are converting
6634 // that unstable reference to our new stable reference.
6635 unstableDelta = -1;
6636 // Cancel the removal of the provider.
6637 if (DEBUG_PROVIDER) {
6638 Slog.v(TAG, "incProviderRef: stable "
6639 + "snatched provider from the jaws of death");
6640 }
6641 prc.removePending = false;
Guobin Zhang9e3e52662013-03-21 13:57:11 +08006642 // There is a race! It fails to remove the message, which
6643 // will be handled in completeRemoveProvider().
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006644 mH.removeMessages(H.REMOVE_PROVIDER, prc);
6645 } else {
6646 unstableDelta = 0;
6647 }
6648 try {
6649 if (DEBUG_PROVIDER) {
6650 Slog.v(TAG, "incProviderRef Now stable - "
6651 + prc.holder.info.name + ": unstableDelta="
6652 + unstableDelta);
6653 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006654 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006655 prc.holder.connection, 1, unstableDelta);
6656 } catch (RemoteException e) {
6657 //do nothing content provider object is dead any way
6658 }
6659 }
6660 } else {
6661 prc.unstableCount += 1;
6662 if (prc.unstableCount == 1) {
6663 // We are acquiring a new unstable reference on the provider.
6664 if (prc.removePending) {
6665 // Oh look, we actually have a remove pending for the
6666 // provider, which is still holding the last unstable
6667 // reference. We just need to cancel that to take new
6668 // ownership of the reference.
6669 if (DEBUG_PROVIDER) {
6670 Slog.v(TAG, "incProviderRef: unstable "
6671 + "snatched provider from the jaws of death");
6672 }
6673 prc.removePending = false;
6674 mH.removeMessages(H.REMOVE_PROVIDER, prc);
6675 } else {
6676 // First unstable ref, increment our count in the
6677 // activity manager.
6678 try {
6679 if (DEBUG_PROVIDER) {
6680 Slog.v(TAG, "incProviderRef: Now unstable - "
6681 + prc.holder.info.name);
6682 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006683 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006684 prc.holder.connection, 0, 1);
6685 } catch (RemoteException e) {
6686 //do nothing content provider object is dead any way
6687 }
6688 }
6689 }
6690 }
6691 }
6692
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006693 @UnsupportedAppUsage
Jeff Sharkey6d515712012-09-20 16:06:08 -07006694 public final IContentProvider acquireExistingProvider(
6695 Context c, String auth, int userId, boolean stable) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006696 synchronized (mProviderMap) {
Wale Ogunwale1d646122015-04-24 14:45:14 -07006697 final ProviderKey key = new ProviderKey(auth, userId);
Jeff Sharkey6d515712012-09-20 16:06:08 -07006698 final ProviderClientRecord pr = mProviderMap.get(key);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006699 if (pr == null) {
6700 return null;
6701 }
6702
6703 IContentProvider provider = pr.mProvider;
6704 IBinder jBinder = provider.asBinder();
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006705 if (!jBinder.isBinderAlive()) {
6706 // The hosting process of the provider has died; we can't
6707 // use this one.
Wale Ogunwale1d646122015-04-24 14:45:14 -07006708 Log.i(TAG, "Acquiring provider " + auth + " for user " + userId
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006709 + ": existing object's process dead");
6710 handleUnstableProviderDiedLocked(jBinder, true);
6711 return null;
6712 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006713
6714 // Only increment the ref count if we have one. If we don't then the
6715 // provider is not reference counted and never needs to be released.
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006716 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006717 if (prc != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006718 incProviderRefLocked(prc, stable);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006719 }
6720 return provider;
6721 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006722 }
6723
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006724 @UnsupportedAppUsage
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006725 public final boolean releaseProvider(IContentProvider provider, boolean stable) {
6726 if (provider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006727 return false;
6728 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006730 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006731 synchronized (mProviderMap) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006732 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006733 if (prc == null) {
6734 // The provider has no ref count, no release is needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006735 return false;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006736 }
6737
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006738 boolean lastRef = false;
6739 if (stable) {
6740 if (prc.stableCount == 0) {
6741 if (DEBUG_PROVIDER) Slog.v(TAG,
6742 "releaseProvider: stable ref count already 0, how?");
6743 return false;
6744 }
6745 prc.stableCount -= 1;
6746 if (prc.stableCount == 0) {
6747 // What we do at this point depends on whether there are
6748 // any unstable refs left: if there are, we just tell the
6749 // activity manager to decrement its stable count; if there
6750 // aren't, we need to enqueue this provider to be removed,
6751 // and convert to holding a single unstable ref while
6752 // doing so.
6753 lastRef = prc.unstableCount == 0;
6754 try {
6755 if (DEBUG_PROVIDER) {
6756 Slog.v(TAG, "releaseProvider: No longer stable w/lastRef="
6757 + lastRef + " - " + prc.holder.info.name);
6758 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006759 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006760 prc.holder.connection, -1, lastRef ? 1 : 0);
6761 } catch (RemoteException e) {
6762 //do nothing content provider object is dead any way
6763 }
6764 }
6765 } else {
6766 if (prc.unstableCount == 0) {
6767 if (DEBUG_PROVIDER) Slog.v(TAG,
6768 "releaseProvider: unstable ref count already 0, how?");
6769 return false;
6770 }
6771 prc.unstableCount -= 1;
6772 if (prc.unstableCount == 0) {
6773 // If this is the last reference, we need to enqueue
6774 // this provider to be removed instead of telling the
6775 // activity manager to remove it at this point.
6776 lastRef = prc.stableCount == 0;
6777 if (!lastRef) {
6778 try {
6779 if (DEBUG_PROVIDER) {
6780 Slog.v(TAG, "releaseProvider: No longer unstable - "
6781 + prc.holder.info.name);
6782 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006783 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006784 prc.holder.connection, 0, -1);
6785 } catch (RemoteException e) {
6786 //do nothing content provider object is dead any way
6787 }
6788 }
6789 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006790 }
6791
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006792 if (lastRef) {
6793 if (!prc.removePending) {
6794 // Schedule the actual remove asynchronously, since we don't know the context
6795 // this will be called in.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006796 if (DEBUG_PROVIDER) {
6797 Slog.v(TAG, "releaseProvider: Enqueueing pending removal - "
6798 + prc.holder.info.name);
6799 }
6800 prc.removePending = true;
6801 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, prc);
Riddle Hsu4e8e3b02019-04-12 17:37:10 +08006802 mH.sendMessageDelayed(msg, CONTENT_PROVIDER_RETAIN_TIME);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006803 } else {
6804 Slog.w(TAG, "Duplicate remove pending of provider " + prc.holder.info.name);
6805 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006806 }
6807 return true;
6808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006809 }
6810
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006811 final void completeRemoveProvider(ProviderRefCount prc) {
6812 synchronized (mProviderMap) {
6813 if (!prc.removePending) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006814 // There was a race! Some other client managed to acquire
6815 // the provider before the removal was completed.
6816 // Abort the removal. We will do it later.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006817 if (DEBUG_PROVIDER) Slog.v(TAG, "completeRemoveProvider: lost the race, "
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006818 + "provider still in use");
6819 return;
6820 }
6821
Guobin Zhang9e3e52662013-03-21 13:57:11 +08006822 // More complicated race!! Some client managed to acquire the
6823 // provider and release it before the removal was completed.
6824 // Continue the removal, and abort the next remove message.
6825 prc.removePending = false;
6826
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006827 final IBinder jBinder = prc.holder.provider.asBinder();
6828 ProviderRefCount existingPrc = mProviderRefCountMap.get(jBinder);
6829 if (existingPrc == prc) {
6830 mProviderRefCountMap.remove(jBinder);
6831 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006832
Dianne Hackbornadd005c2013-07-17 18:43:12 -07006833 for (int i=mProviderMap.size()-1; i>=0; i--) {
6834 ProviderClientRecord pr = mProviderMap.valueAt(i);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006835 IBinder myBinder = pr.mProvider.asBinder();
6836 if (myBinder == jBinder) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07006837 mProviderMap.removeAt(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006838 }
6839 }
6840 }
6841
6842 try {
6843 if (DEBUG_PROVIDER) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006844 Slog.v(TAG, "removeProvider: Invoking ActivityManagerService."
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006845 + "removeContentProvider(" + prc.holder.info.name + ")");
6846 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006847 ActivityManager.getService().removeContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006848 prc.holder.connection, false);
6849 } catch (RemoteException e) {
6850 //do nothing content provider object is dead any way
6851 }
6852 }
6853
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006854 @UnsupportedAppUsage
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006855 final void handleUnstableProviderDied(IBinder provider, boolean fromClient) {
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006856 synchronized (mProviderMap) {
6857 handleUnstableProviderDiedLocked(provider, fromClient);
6858 }
6859 }
6860
6861 final void handleUnstableProviderDiedLocked(IBinder provider, boolean fromClient) {
6862 ProviderRefCount prc = mProviderRefCountMap.get(provider);
6863 if (prc != null) {
6864 if (DEBUG_PROVIDER) Slog.v(TAG, "Cleaning up dead provider "
6865 + provider + " " + prc.holder.info.name);
6866 mProviderRefCountMap.remove(provider);
You Kimbc74de62013-10-01 00:13:26 +09006867 for (int i=mProviderMap.size()-1; i>=0; i--) {
6868 ProviderClientRecord pr = mProviderMap.valueAt(i);
6869 if (pr != null && pr.mProvider.asBinder() == provider) {
6870 Slog.i(TAG, "Removing dead content provider:" + pr.mProvider.toString());
6871 mProviderMap.removeAt(i);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006872 }
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006873 }
You Kimbc74de62013-10-01 00:13:26 +09006874
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006875 if (fromClient) {
6876 // We found out about this due to execution in our client
6877 // code. Tell the activity manager about it now, to ensure
6878 // that the next time we go to do anything with the provider
6879 // it knows it is dead (so we don't race with its death
6880 // notification).
6881 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006882 ActivityManager.getService().unstableProviderDied(
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006883 prc.holder.connection);
6884 } catch (RemoteException e) {
6885 //do nothing content provider object is dead any way
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006886 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07006887 }
6888 }
6889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006890
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006891 final void appNotRespondingViaProvider(IBinder provider) {
6892 synchronized (mProviderMap) {
6893 ProviderRefCount prc = mProviderRefCountMap.get(provider);
6894 if (prc != null) {
6895 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006896 ActivityManager.getService()
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006897 .appNotRespondingViaProvider(prc.holder.connection);
6898 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006899 throw e.rethrowFromSystemServer();
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006900 }
6901 }
6902 }
6903 }
6904
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006905 private ProviderClientRecord installProviderAuthoritiesLocked(IContentProvider provider,
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006906 ContentProvider localProvider, ContentProviderHolder holder) {
Andreas Gampe18e99c12015-03-06 15:29:06 -08006907 final String auths[] = holder.info.authority.split(";");
Jeff Sharkey6d515712012-09-20 16:06:08 -07006908 final int userId = UserHandle.getUserId(holder.info.applicationInfo.uid);
6909
Jeff Sharkey0a17db12016-11-04 11:23:46 -06006910 if (provider != null) {
6911 // If this provider is hosted by the core OS and cannot be upgraded,
6912 // then I guess we're okay doing blocking calls to it.
6913 for (String auth : auths) {
6914 switch (auth) {
6915 case ContactsContract.AUTHORITY:
6916 case CallLog.AUTHORITY:
6917 case CallLog.SHADOW_AUTHORITY:
6918 case BlockedNumberContract.AUTHORITY:
6919 case CalendarContract.AUTHORITY:
6920 case Downloads.Impl.AUTHORITY:
Jeff Sharkeycb621622016-11-11 14:04:32 -07006921 case "telephony":
Jeff Sharkey0a17db12016-11-04 11:23:46 -06006922 Binder.allowBlocking(provider.asBinder());
6923 }
6924 }
6925 }
6926
Jeff Sharkey6d515712012-09-20 16:06:08 -07006927 final ProviderClientRecord pcr = new ProviderClientRecord(
6928 auths, provider, localProvider, holder);
6929 for (String auth : auths) {
6930 final ProviderKey key = new ProviderKey(auth, userId);
6931 final ProviderClientRecord existing = mProviderMap.get(key);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006932 if (existing != null) {
6933 Slog.w(TAG, "Content provider " + pcr.mHolder.info.name
Jeff Sharkey6d515712012-09-20 16:06:08 -07006934 + " already published as " + auth);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006935 } else {
Jeff Sharkey6d515712012-09-20 16:06:08 -07006936 mProviderMap.put(key, pcr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006937 }
6938 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006939 return pcr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006940 }
6941
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006942 /**
6943 * Installs the provider.
6944 *
6945 * Providers that are local to the process or that come from the system server
6946 * may be installed permanently which is indicated by setting noReleaseNeeded to true.
6947 * Other remote providers are reference counted. The initial reference count
6948 * for all reference counted providers is one. Providers that are not reference
6949 * counted do not have a reference count (at all).
6950 *
6951 * This method detects when a provider has already been installed. When this happens,
6952 * it increments the reference count of the existing provider (if appropriate)
6953 * and returns the existing provider. This can happen due to concurrent
6954 * attempts to acquire the same provider.
6955 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006956 @UnsupportedAppUsage
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006957 private ContentProviderHolder installProvider(Context context,
6958 ContentProviderHolder holder, ProviderInfo info,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006959 boolean noisy, boolean noReleaseNeeded, boolean stable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006960 ContentProvider localProvider = null;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006961 IContentProvider provider;
Dianne Hackborn5f48fca2012-05-30 11:06:31 -07006962 if (holder == null || holder.provider == null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006963 if (DEBUG_PROVIDER || noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006964 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006965 + info.name);
6966 }
6967 Context c = null;
6968 ApplicationInfo ai = info.applicationInfo;
6969 if (context.getPackageName().equals(ai.packageName)) {
6970 c = context;
6971 } else if (mInitialApplication != null &&
6972 mInitialApplication.getPackageName().equals(ai.packageName)) {
6973 c = mInitialApplication;
6974 } else {
6975 try {
6976 c = context.createPackageContext(ai.packageName,
6977 Context.CONTEXT_INCLUDE_CODE);
6978 } catch (PackageManager.NameNotFoundException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07006979 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006980 }
6981 }
6982 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08006983 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006984 ai.packageName +
6985 " while loading content provider " +
6986 info.name);
6987 return null;
6988 }
Adam Lesinski4e862812016-11-21 16:02:24 -08006989
6990 if (info.splitName != null) {
6991 try {
6992 c = c.createContextForSplit(info.splitName);
6993 } catch (NameNotFoundException e) {
6994 throw new RuntimeException(e);
6995 }
6996 }
6997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006998 try {
6999 final java.lang.ClassLoader cl = c.getClassLoader();
Todd Kennedy233a0b12018-01-29 20:30:24 +00007000 LoadedApk packageInfo = peekPackageInfo(ai.packageName, true);
7001 if (packageInfo == null) {
Jason Monka80bfb52017-11-16 17:15:37 -05007002 // System startup case.
Todd Kennedy233a0b12018-01-29 20:30:24 +00007003 packageInfo = getSystemContext().mPackageInfo;
Jason Monka80bfb52017-11-16 17:15:37 -05007004 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00007005 localProvider = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05007006 .instantiateProvider(cl, info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007007 provider = localProvider.getIContentProvider();
7008 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08007009 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007010 info.name + " from sourceDir " +
7011 info.applicationInfo.sourceDir);
7012 return null;
7013 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007014 if (DEBUG_PROVIDER) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007015 TAG, "Instantiating local provider " + info.name);
7016 // XXX Need to create the correct context for this provider.
7017 localProvider.attachInfo(c, info);
7018 } catch (java.lang.Exception e) {
7019 if (!mInstrumentation.onException(null, e)) {
7020 throw new RuntimeException(
7021 "Unable to get provider " + info.name
7022 + ": " + e.toString(), e);
7023 }
7024 return null;
7025 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007026 } else {
7027 provider = holder.provider;
7028 if (DEBUG_PROVIDER) Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007029 + info.name);
7030 }
7031
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07007032 ContentProviderHolder retHolder;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007033
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007034 synchronized (mProviderMap) {
7035 if (DEBUG_PROVIDER) Slog.v(TAG, "Checking to add " + provider
7036 + " / " + info.name);
7037 IBinder jBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007038 if (localProvider != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007039 ComponentName cname = new ComponentName(info.packageName, info.name);
7040 ProviderClientRecord pr = mLocalProvidersByName.get(cname);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007041 if (pr != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007042 if (DEBUG_PROVIDER) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007043 Slog.v(TAG, "installProvider: lost the race, "
7044 + "using existing local provider");
7045 }
7046 provider = pr.mProvider;
7047 } else {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07007048 holder = new ContentProviderHolder(info);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007049 holder.provider = provider;
7050 holder.noReleaseNeeded = true;
7051 pr = installProviderAuthoritiesLocked(provider, localProvider, holder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007052 mLocalProviders.put(jBinder, pr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007053 mLocalProvidersByName.put(cname, pr);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007054 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007055 retHolder = pr.mHolder;
7056 } else {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007057 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
7058 if (prc != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007059 if (DEBUG_PROVIDER) {
7060 Slog.v(TAG, "installProvider: lost the race, updating ref count");
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007061 }
Wale Ogunwale1d646122015-04-24 14:45:14 -07007062 // We need to transfer our new reference to the existing
7063 // ref count, releasing the old one... but only if
7064 // release is needed (that is, it is not running in the
7065 // system process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007066 if (!noReleaseNeeded) {
7067 incProviderRefLocked(prc, stable);
Wale Ogunwale1d646122015-04-24 14:45:14 -07007068 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08007069 ActivityManager.getService().removeContentProvider(
Wale Ogunwale1d646122015-04-24 14:45:14 -07007070 holder.connection, stable);
7071 } catch (RemoteException e) {
7072 //do nothing content provider object is dead any way
7073 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007074 }
7075 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007076 ProviderClientRecord client = installProviderAuthoritiesLocked(
7077 provider, localProvider, holder);
7078 if (noReleaseNeeded) {
7079 prc = new ProviderRefCount(holder, client, 1000, 1000);
7080 } else {
7081 prc = stable
7082 ? new ProviderRefCount(holder, client, 1, 0)
7083 : new ProviderRefCount(holder, client, 0, 1);
7084 }
7085 mProviderRefCountMap.put(jBinder, prc);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007086 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007087 retHolder = prc.holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007088 }
7089 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007090 return retHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007091 }
7092
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04007093 private void handleRunIsolatedEntryPoint(String entryPoint, String[] entryPointArgs) {
7094 try {
7095 Method main = Class.forName(entryPoint).getMethod("main", String[].class);
7096 main.invoke(null, new Object[]{entryPointArgs});
7097 } catch (ReflectiveOperationException e) {
7098 throw new AndroidRuntimeException("runIsolatedEntryPoint failed", e);
7099 }
7100 // The process will be empty after this method returns; exit the VM now.
7101 System.exit(0);
7102 }
7103
Mathew Inwood61e8ae62018-08-14 14:17:44 +01007104 @UnsupportedAppUsage
Sudheer Shankaf6690102017-10-16 10:20:32 -07007105 private void attach(boolean system, long startSeq) {
Jeff Sharkey66a017b2013-01-17 18:18:22 -08007106 sCurrentActivityThread = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007107 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007108 if (!system) {
Siva Velusamyd693dfa2012-09-10 14:36:58 -07007109 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
7110 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007111 RuntimeInit.setApplicationObject(mAppThread.asBinder());
Sudheer Shankadc589ac2016-11-10 15:30:17 -08007112 final IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007113 try {
Sudheer Shankaf6690102017-10-16 10:20:32 -07007114 mgr.attachApplication(mAppThread, startSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007115 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07007116 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007117 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07007118 // Watch for getting close to heap limit.
7119 BinderInternal.addGcWatcher(new Runnable() {
7120 @Override public void run() {
7121 if (!mSomeActivitiesChanged) {
7122 return;
7123 }
7124 Runtime runtime = Runtime.getRuntime();
7125 long dalvikMax = runtime.maxMemory();
7126 long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
7127 if (dalvikUsed > ((3*dalvikMax)/4)) {
7128 if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
7129 + " total=" + (runtime.totalMemory()/1024)
7130 + " used=" + (dalvikUsed/1024));
7131 mSomeActivitiesChanged = false;
7132 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07007133 ActivityTaskManager.getService().releaseSomeActivities(mAppThread);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07007134 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07007135 throw e.rethrowFromSystemServer();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07007136 }
7137 }
7138 }
7139 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007140 } else {
7141 // Don't set application object here -- if the system crashes,
7142 // we can't display an alert, we just want to die die die.
Siva Velusamyd693dfa2012-09-10 14:36:58 -07007143 android.ddm.DdmHandleAppName.setAppName("system_process",
Dianne Hackborn89ad4562014-08-24 16:45:38 -07007144 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007145 try {
7146 mInstrumentation = new Instrumentation();
Jason Monka80bfb52017-11-16 17:15:37 -05007147 mInstrumentation.basicInit(this);
Jeff Browndefd4a62014-03-10 21:24:37 -07007148 ContextImpl context = ContextImpl.createAppContext(
Todd Kennedy233a0b12018-01-29 20:30:24 +00007149 this, getSystemContext().mPackageInfo);
7150 mInitialApplication = context.mPackageInfo.makeApplication(true, null);
Jeff Brown7fc8e352014-09-16 18:06:47 -07007151 mInitialApplication.onCreate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007152 } catch (Exception e) {
7153 throw new RuntimeException(
7154 "Unable to instantiate Application():" + e.toString(), e);
7155 }
7156 }
Geremy Condrab7faaf42012-09-19 18:07:42 -07007157
Andrii Kulian44607962017-03-16 11:06:24 -07007158 ViewRootImpl.ConfigChangedCallback configChangedCallback
7159 = (Configuration globalConfig) -> {
7160 synchronized (mResourcesManager) {
7161 // We need to apply this change to the resources immediately, because upon returning
7162 // the view hierarchy will be informed about it.
7163 if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,
7164 null /* compat */)) {
7165 updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
7166 mResourcesManager.getConfiguration().getLocales());
Adam Lesinskib61e4052016-05-19 18:23:05 -07007167
Andrii Kulian44607962017-03-16 11:06:24 -07007168 // This actually changed the resources! Tell everyone about it.
7169 if (mPendingConfiguration == null
7170 || mPendingConfiguration.isOtherSeqNewer(globalConfig)) {
7171 mPendingConfiguration = globalConfig;
7172 sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08007173 }
7174 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08007175 }
Andrii Kulian44607962017-03-16 11:06:24 -07007176 };
7177 ViewRootImpl.addConfigCallback(configChangedCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007178 }
7179
Mathew Inwood61e8ae62018-08-14 14:17:44 +01007180 @UnsupportedAppUsage
Romain Guy5e9120d2012-01-30 12:17:22 -08007181 public static ActivityThread systemMain() {
Alan Viverette5e1565e2014-07-29 16:14:25 -07007182 // The system process on low-memory devices do not get to use hardware
7183 // accelerated drawing, since this can add too much overhead to the
7184 // process.
7185 if (!ActivityManager.isHighEndGfx()) {
John Reck51aaf902015-12-02 15:08:07 -08007186 ThreadedRenderer.disable(true);
John Reck73840ea2014-09-22 07:39:18 -07007187 } else {
John Reck51aaf902015-12-02 15:08:07 -08007188 ThreadedRenderer.enableForegroundTrimming();
Alan Viverette5e1565e2014-07-29 16:14:25 -07007189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007190 ActivityThread thread = new ActivityThread();
Sudheer Shankaf6690102017-10-16 10:20:32 -07007191 thread.attach(true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007192 return thread;
7193 }
7194
Irina Dumitrescu34a27c42019-04-15 19:20:38 +01007195 public static void updateHttpProxy(@NonNull Context context) {
7196 final ConnectivityManager cm = ConnectivityManager.from(context);
7197 Proxy.setHttpProxySystemProperty(cm.getDefaultProxy());
7198 }
7199
Mathew Inwood61e8ae62018-08-14 14:17:44 +01007200 @UnsupportedAppUsage
Jeff Brown10e89712011-07-08 18:52:57 -07007201 public final void installSystemProviders(List<ProviderInfo> providers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007202 if (providers != null) {
Jeff Brown10e89712011-07-08 18:52:57 -07007203 installContentProviders(mInitialApplication, providers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007204 }
7205 }
7206
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08007207 public int getIntCoreSetting(String key, int defaultValue) {
Craig Mautner88c05892013-06-28 09:47:45 -07007208 synchronized (mResourcesManager) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08007209 if (mCoreSettings != null) {
7210 return mCoreSettings.getInt(key, defaultValue);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08007211 }
Craig Mautner88c05892013-06-28 09:47:45 -07007212 return defaultValue;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08007213 }
7214 }
7215
Jeff Sharkeybc2ae002018-07-31 10:45:37 -06007216 private static class AndroidOs extends ForwardingOs {
7217 /**
7218 * Install selective syscall interception. For example, this is used to
7219 * implement special filesystem paths that will be redirected to
7220 * {@link ContentResolver#openFileDescriptor(Uri, String)}.
7221 */
7222 public static void install() {
7223 // If feature is disabled, we don't need to install
7224 if (!DEPRECATE_DATA_COLUMNS) return;
7225
Jeff Sharkeybc2ae002018-07-31 10:45:37 -06007226 // Install interception and make sure it sticks!
7227 Os def = null;
7228 do {
7229 def = Os.getDefault();
7230 } while (!Os.compareAndSetDefault(def, new AndroidOs(def)));
7231 }
7232
7233 private AndroidOs(Os os) {
7234 super(os);
7235 }
7236
7237 private FileDescriptor openDeprecatedDataPath(String path, int mode) throws ErrnoException {
7238 final Uri uri = ContentResolver.translateDeprecatedDataPath(path);
7239 Log.v(TAG, "Redirecting " + path + " to " + uri);
7240
7241 final ContentResolver cr = currentActivityThread().getApplication()
7242 .getContentResolver();
7243 try {
7244 final FileDescriptor fd = new FileDescriptor();
7245 fd.setInt$(cr.openFileDescriptor(uri,
7246 FileUtils.translateModePosixToString(mode)).detachFd());
7247 return fd;
Jeff Sharkeyb50f51e2019-02-27 13:55:38 -07007248 } catch (SecurityException e) {
7249 throw new ErrnoException(e.getMessage(), OsConstants.EACCES);
Jeff Sharkeybc2ae002018-07-31 10:45:37 -06007250 } catch (FileNotFoundException e) {
7251 throw new ErrnoException(e.getMessage(), OsConstants.ENOENT);
7252 }
7253 }
7254
Jeff Sharkey416d4622019-02-27 22:14:16 -07007255 private void deleteDeprecatedDataPath(String path) throws ErrnoException {
7256 final Uri uri = ContentResolver.translateDeprecatedDataPath(path);
7257 Log.v(TAG, "Redirecting " + path + " to " + uri);
7258
7259 final ContentResolver cr = currentActivityThread().getApplication()
7260 .getContentResolver();
7261 try {
7262 if (cr.delete(uri, null, null) == 0) {
7263 throw new FileNotFoundException();
7264 }
7265 } catch (SecurityException e) {
7266 throw new ErrnoException(e.getMessage(), OsConstants.EACCES);
7267 } catch (FileNotFoundException e) {
7268 throw new ErrnoException(e.getMessage(), OsConstants.ENOENT);
7269 }
7270 }
7271
Jeff Sharkeybc2ae002018-07-31 10:45:37 -06007272 @Override
7273 public boolean access(String path, int mode) throws ErrnoException {
7274 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7275 // If we opened it okay, then access check succeeded
7276 IoUtils.closeQuietly(
7277 openDeprecatedDataPath(path, FileUtils.translateModeAccessToPosix(mode)));
7278 return true;
7279 } else {
7280 return super.access(path, mode);
7281 }
7282 }
7283
7284 @Override
7285 public FileDescriptor open(String path, int flags, int mode) throws ErrnoException {
7286 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7287 return openDeprecatedDataPath(path, mode);
7288 } else {
7289 return super.open(path, flags, mode);
7290 }
7291 }
7292
7293 @Override
7294 public StructStat stat(String path) throws ErrnoException {
7295 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7296 final FileDescriptor fd = openDeprecatedDataPath(path, OsConstants.O_RDONLY);
7297 try {
7298 return android.system.Os.fstat(fd);
7299 } finally {
7300 IoUtils.closeQuietly(fd);
7301 }
7302 } else {
7303 return super.stat(path);
Narayan Kamath7f062242015-04-08 13:24:13 +01007304 }
7305 }
Jeff Sharkey416d4622019-02-27 22:14:16 -07007306
7307 @Override
7308 public void unlink(String path) throws ErrnoException {
7309 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7310 deleteDeprecatedDataPath(path);
7311 } else {
7312 super.unlink(path);
7313 }
7314 }
7315
7316 @Override
7317 public void remove(String path) throws ErrnoException {
7318 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7319 deleteDeprecatedDataPath(path);
7320 } else {
7321 super.remove(path);
7322 }
7323 }
7324
7325 @Override
7326 public void rename(String oldPath, String newPath) throws ErrnoException {
7327 try {
7328 super.rename(oldPath, newPath);
7329 } catch (ErrnoException e) {
7330 if (e.errno == OsConstants.EXDEV) {
7331 Log.v(TAG, "Recovering failed rename " + oldPath + " to " + newPath);
7332 try {
7333 Files.move(new File(oldPath).toPath(), new File(newPath).toPath());
7334 } catch (IOException e2) {
7335 throw e;
7336 }
7337 } else {
7338 throw e;
7339 }
7340 }
7341 }
Geremy Condrab7faaf42012-09-19 18:07:42 -07007342 }
7343
Romain Guy65b345f2011-07-27 18:51:50 -07007344 public static void main(String[] args) {
Narayan Kamathfbb32f62015-06-12 15:34:35 +01007345 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
Bob Leee5408332009-09-04 18:31:17 -07007346
Jeff Sharkeybc2ae002018-07-31 10:45:37 -06007347 // Install selective syscall interception
7348 AndroidOs.install();
7349
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08007350 // CloseGuard defaults to true and can be quite spammy. We
7351 // disable it here, but selectively enable it later (via
7352 // StrictMode) on debug builds, but using DropBox, not logs.
7353 CloseGuard.setEnabled(false);
7354
Andreas Gamped281b422016-07-08 03:50:27 +00007355 Environment.initForCurrentUser();
Jeff Sharkeyb049e212012-09-07 23:16:01 -07007356
Robin Lee3d076af2014-04-25 14:57:49 +01007357 // Make sure TrustedCertificateStore looks in the right place for CA certificates
7358 final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
7359 TrustedCertificateStore.setDefaultUserDirectory(configDir);
7360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007361 Process.setArgV0("<pre-initialized>");
7362
7363 Looper.prepareMainLooper();
7364
Sudheer Shankaf6690102017-10-16 10:20:32 -07007365 // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
7366 // It will be in the format "seq=114"
7367 long startSeq = 0;
7368 if (args != null) {
7369 for (int i = args.length - 1; i >= 0; --i) {
7370 if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
7371 startSeq = Long.parseLong(
7372 args[i].substring(PROC_START_SEQ_IDENT.length()));
7373 }
7374 }
7375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007376 ActivityThread thread = new ActivityThread();
Sudheer Shankaf6690102017-10-16 10:20:32 -07007377 thread.attach(false, startSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007378
Vairavan Srinivasan7335cfd2012-08-18 18:36:03 -07007379 if (sMainThreadHandler == null) {
7380 sMainThreadHandler = thread.getHandler();
7381 }
7382
Dianne Hackborn287952c2010-09-22 22:34:31 -07007383 if (false) {
7384 Looper.myLooper().setMessageLogging(new
7385 LogPrinter(Log.DEBUG, "ActivityThread"));
7386 }
7387
Narayan Kamathfbb32f62015-06-12 15:34:35 +01007388 // End of event ActivityThreadMain.
7389 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007390 Looper.loop();
7391
Jeff Brown10e89712011-07-08 18:52:57 -07007392 throw new RuntimeException("Main thread loop unexpectedly exited");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007393 }
Chris Craikfc294242016-12-13 18:10:46 -08007394
Makoto Onuki0a9ee1a2019-06-19 08:58:02 -07007395 private void purgePendingResources() {
7396 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "purgePendingResources");
7397 nPurgePendingResources();
7398 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
7399 }
7400
Chris Craikfc294242016-12-13 18:10:46 -08007401 // ------------------ Regular JNI ------------------------
Tim Murray59f3dc12018-10-22 15:26:08 -07007402 private native void nPurgePendingResources();
Chris Craikfc294242016-12-13 18:10:46 -08007403 private native void nDumpGraphicsInfo(FileDescriptor fd);
Ryan Savitskicfdc1512018-12-14 16:20:52 +00007404 private native void nInitZygoteChildHeapProfiling();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007405}