blob: eea1d69b6326a3c0f7cf1a762294c67025d31630 [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;
Hongwei Wang5711b8f2019-11-15 15:44:12 -080020import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
21import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080022import static android.app.servertransaction.ActivityLifecycleItem.ON_CREATE;
23import static android.app.servertransaction.ActivityLifecycleItem.ON_DESTROY;
24import static android.app.servertransaction.ActivityLifecycleItem.ON_PAUSE;
25import static android.app.servertransaction.ActivityLifecycleItem.ON_RESUME;
26import static android.app.servertransaction.ActivityLifecycleItem.ON_START;
27import static android.app.servertransaction.ActivityLifecycleItem.ON_STOP;
28import static android.app.servertransaction.ActivityLifecycleItem.PRE_ON_CREATE;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -060029import static android.content.ContentResolver.DEPRECATE_DATA_COLUMNS;
30import static android.content.ContentResolver.DEPRECATE_DATA_PREFIX;
Andrii Kulianb047b8b2017-02-08 18:38:26 -080031import static android.view.Display.INVALID_DISPLAY;
32
Adrian Roos03dd48c2019-03-19 17:17:37 -040033import static com.android.internal.annotations.VisibleForTesting.Visibility.PACKAGE;
34
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -070035import android.annotation.NonNull;
36import android.annotation.Nullable;
Dianne Hackborn69c6adc2015-06-02 10:52:59 -070037import android.app.assist.AssistContent;
38import android.app.assist.AssistStructure;
Christopher Tate45281862010-03-05 15:46:30 -080039import android.app.backup.BackupAgent;
Andrii Kulian914aa7d2018-03-19 21:51:53 -070040import android.app.servertransaction.ActivityLifecycleItem;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080041import android.app.servertransaction.ActivityLifecycleItem.LifecycleState;
Andrii Kulian914aa7d2018-03-19 21:51:53 -070042import android.app.servertransaction.ActivityRelaunchItem;
Andrii Kulian446e8242017-10-26 15:17:29 -070043import android.app.servertransaction.ActivityResultItem;
44import android.app.servertransaction.ClientTransaction;
Riddle Hsud3062cb2018-06-30 02:06:42 +080045import android.app.servertransaction.ClientTransactionItem;
jorgegil@google.com06bc3232019-10-31 14:51:22 -070046import android.app.servertransaction.PauseActivityItem;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080047import android.app.servertransaction.PendingTransactionActions;
48import android.app.servertransaction.PendingTransactionActions.StopInfo;
jorgegil@google.com06bc3232019-10-31 14:51:22 -070049import android.app.servertransaction.ResumeActivityItem;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080050import android.app.servertransaction.TransactionExecutor;
Andrii Kulian914aa7d2018-03-19 21:51:53 -070051import android.app.servertransaction.TransactionExecutorHelper;
Artur Satayevc895b1b2019-12-10 17:47:51 +000052import android.compat.annotation.UnsupportedAppUsage;
Felipe Lemea4f39cd2019-02-19 15:08:59 -080053import android.content.AutofillOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.content.BroadcastReceiver;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070055import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.ComponentName;
Felipe Leme326f15a2019-02-19 09:42:24 -080057import android.content.ContentCaptureOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.content.ContentProvider;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -060059import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.content.Context;
61import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070062import android.content.IIntentReceiver;
Jesse Hall317fa5a2017-05-23 15:46:55 -070063import android.content.Intent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.content.pm.ActivityInfo;
65import android.content.pm.ApplicationInfo;
66import android.content.pm.IPackageManager;
67import android.content.pm.InstrumentationInfo;
Christopher Tate346acb12012-10-15 19:20:25 -070068import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.content.pm.PackageManager;
Sen Hubde75702010-05-28 01:54:03 -070070import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070071import android.content.pm.ParceledListSlice;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.content.pm.ProviderInfo;
Makoto Onuki2d80ca02020-02-12 14:20:36 -080073import android.content.pm.ProviderInfoList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.content.pm.ServiceInfo;
75import android.content.res.AssetManager;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -070076import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.content.res.Configuration;
78import android.content.res.Resources;
Alan Viverettee54d2452015-05-06 10:41:43 -070079import android.content.res.Resources.Theme;
Ryan Mitchell0cbfd2b2020-02-07 11:19:16 -080080import android.content.res.loader.ResourcesLoader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.database.sqlite.SQLiteDatabase;
82import android.database.sqlite.SQLiteDebug;
Vasu Noric3849202010-03-09 10:47:25 -080083import android.database.sqlite.SQLiteDebug.DbStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.graphics.Bitmap;
85import android.graphics.Canvas;
John Reck8785ceb2018-10-29 16:45:58 -070086import android.graphics.HardwareRenderer;
Leon Scroggins III8290eab2018-03-19 10:51:44 -040087import android.graphics.ImageDecoder;
Jeff Brownbd6e1502012-08-28 03:27:37 -070088import android.hardware.display.DisplayManagerGlobal;
lumarkddc77fb2019-06-27 22:22:23 +080089import android.inputmethodservice.InputMethodService;
Paul Jensene0bef712014-12-10 15:12:18 -050090import android.net.ConnectivityManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070091import android.net.IConnectivityManager;
92import android.net.Proxy;
Jason Monk83520b92014-05-09 15:16:06 -040093import android.net.Uri;
Joe Onoratod630f102011-03-17 18:42:26 -070094import android.os.AsyncTask;
Amith Yamasani742a6712011-05-04 14:49:28 -070095import android.os.Binder;
Jeff Sharkey344744b2016-01-28 19:03:30 -070096import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import android.os.Bundle;
Sunny Goyald40c3452019-03-20 12:46:55 -070098import android.os.CancellationSignal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import android.os.Debug;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700100import android.os.Environment;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -0600101import android.os.FileUtils;
Jesse Hallb12249b2016-12-12 12:53:02 -0800102import android.os.GraphicsEnvironment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import android.os.Handler;
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700104import android.os.HandlerExecutor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import android.os.IBinder;
Sunny Goyald40c3452019-03-20 12:46:55 -0700106import android.os.ICancellationSignal;
Adam Lesinskib61e4052016-05-19 18:23:05 -0700107import android.os.LocaleList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import android.os.Looper;
109import android.os.Message;
110import android.os.MessageQueue;
Dianne Hackbornfabb70b2014-11-11 12:22:36 -0800111import android.os.Parcel;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700112import android.os.ParcelFileDescriptor;
Craig Mautnera0026042014-04-23 11:45:37 -0700113import android.os.PersistableBundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.os.Process;
Makoto Onuki2c6657f2018-06-06 15:24:02 -0700115import android.os.RemoteCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116import android.os.RemoteException;
117import android.os.ServiceManager;
Jeffrey Huangf58800b2020-01-23 13:22:10 -0800118import android.os.StatsFrameworkInitializer;
119import android.os.StatsServiceManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700120import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121import android.os.SystemClock;
Jeff Brownefd43bd2012-09-21 17:02:35 -0700122import android.os.SystemProperties;
Makoto Onuki6b0a7b82019-10-18 15:44:53 -0700123import android.os.TelephonyServiceManager;
Dianne Hackborn1ded0b12012-04-26 14:14:50 -0700124import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700125import android.os.UserHandle;
Todd Kennedy8f135982019-07-02 07:35:15 -0700126import android.permission.IPermissionManager;
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600127import android.provider.BlockedNumberContract;
128import android.provider.CalendarContract;
129import android.provider.CallLog;
130import android.provider.ContactsContract;
131import android.provider.Downloads;
Seigo Nonaka54084b62017-04-24 14:46:23 -0700132import android.provider.FontsContract;
Narayan Kamathccb2a0862013-12-19 14:49:36 +0000133import android.provider.Settings;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700134import android.renderscript.RenderScriptCacheDir;
Chad Brubakerc72875b2016-04-27 16:35:11 -0700135import android.security.NetworkSecurityPolicy;
Chad Brubaker78d47122015-11-17 22:26:58 -0800136import android.security.net.config.NetworkSecurityConfigProvider;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -0600137import android.system.ErrnoException;
138import android.system.OsConstants;
139import android.system.StructStat;
Makoto Onuki6b0a7b82019-10-18 15:44:53 -0700140import android.telephony.TelephonyFrameworkInitializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import android.util.AndroidRuntimeException;
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700142import android.util.ArrayMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143import android.util.DisplayMetrics;
144import android.util.EventLog;
145import android.util.Log;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700146import android.util.LogPrinter;
Andrii Kulianb372da62018-01-18 10:46:24 -0800147import android.util.MergedConfiguration;
Craig Mautnereb8abf72014-07-02 15:04:09 -0700148import android.util.Pair;
Jeff Brown6754ba22011-12-14 20:20:01 -0800149import android.util.PrintWriterPrinter;
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800150import android.util.Slog;
Annie Mengd5827872019-01-30 20:28:57 +0000151import android.util.SparseArray;
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -0700152import android.util.SparseIntArray;
Adam Powell14874662013-07-18 19:42:41 -0700153import android.util.SuperNotCalledException;
Kweku Adams4be0b1a2019-04-25 16:16:34 -0700154import android.util.UtilConfig;
Kweku Adams598e9a22017-11-02 17:12:20 -0700155import android.util.proto.ProtoOutputStream;
Jorim Jaggib29e3182018-04-30 18:51:56 +0200156import android.view.Choreographer;
Adam Lesinski3ad1b482016-04-01 16:41:41 -0700157import android.view.ContextThemeWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158import android.view.Display;
Riddle Hsud490c572020-04-17 01:39:27 +0800159import android.view.DisplayAdjustments;
160import android.view.DisplayAdjustments.FixedRotationAdjustments;
John Reck51aaf902015-12-02 15:08:07 -0800161import android.view.ThreadedRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162import android.view.View;
163import android.view.ViewDebug;
164import android.view.ViewManager;
Dianne Hackborn6dd005b2011-07-18 13:22:50 -0700165import android.view.ViewRootImpl;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166import android.view.Window;
167import android.view.WindowManager;
Jeff Brown98365d72012-08-19 20:30:52 -0700168import android.view.WindowManagerGlobal;
Richard Uhler2c036192016-09-14 09:48:31 +0100169import android.webkit.WebView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700171import com.android.internal.annotations.GuardedBy;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800172import com.android.internal.annotations.VisibleForTesting;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700173import com.android.internal.app.IVoiceInteractor;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800174import com.android.internal.content.ReferrerIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175import com.android.internal.os.BinderInternal;
176import com.android.internal.os.RuntimeInit;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700177import com.android.internal.os.SomeArgs;
Jeff Sharkey3e195892016-03-05 19:48:59 -0700178import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -0700179import com.android.internal.util.FastPrintWriter;
Sunny Goyald40c3452019-03-20 12:46:55 -0700180import com.android.internal.util.Preconditions;
Jorim Jaggib29e3182018-04-30 18:51:56 +0200181import com.android.internal.util.function.pooled.PooledLambda;
Kenny Root12e75222013-04-23 22:34:24 -0700182import com.android.org.conscrypt.OpenSSLSocketImpl;
Robin Lee3d076af2014-04-25 14:57:49 +0100183import com.android.org.conscrypt.TrustedCertificateStore;
Yi Jin6c6e9ca2018-03-20 16:53:35 -0700184import com.android.server.am.MemInfoDumpProto;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700185
Jesse Hall317fa5a2017-05-23 15:46:55 -0700186import dalvik.system.CloseGuard;
187import dalvik.system.VMDebug;
188import dalvik.system.VMRuntime;
189
Jeff Sharkeybc2ae002018-07-31 10:45:37 -0600190import libcore.io.ForwardingOs;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700191import libcore.io.IoUtils;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -0600192import libcore.io.Os;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700193import libcore.net.event.NetworkEventDispatcher;
194
195import org.apache.harmony.dalvik.ddmc.DdmVmInternal;
196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197import java.io.File;
198import java.io.FileDescriptor;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -0600199import java.io.FileNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700201import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202import java.io.PrintWriter;
203import java.lang.ref.WeakReference;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -0400204import java.lang.reflect.Method;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700205import java.net.InetAddress;
Alex Light330e8be2019-08-12 10:58:29 -0700206import java.nio.file.Files;
207import java.nio.file.Path;
Martijn Coenen13885b72020-03-11 13:38:19 +0100208import java.nio.file.StandardCopyOption;
Narayan Kamathccb2a0862013-12-19 14:49:36 +0000209import java.text.DateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210import java.util.ArrayList;
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -0600211import java.util.Arrays;
Riddle Hsud3062cb2018-06-30 02:06:42 +0800212import java.util.Collections;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213import java.util.List;
Adam Lesinskib61e4052016-05-19 18:23:05 -0700214import java.util.Locale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215import java.util.Map;
Kenny Roote6585b32013-12-13 12:00:26 -0800216import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217import java.util.TimeZone;
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700218import java.util.concurrent.Executor;
Riddle Hsu50e34002019-04-12 20:42:05 +0800219import java.util.concurrent.atomic.AtomicInteger;
Riddle Hsud490c572020-04-17 01:39:27 +0800220import java.util.function.Consumer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700222final class RemoteServiceException extends AndroidRuntimeException {
223 public RemoteServiceException(String msg) {
224 super(msg);
225 }
226}
227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228/**
229 * This manages the execution of the main thread in an
230 * application process, scheduling and executing activities,
231 * broadcasts, and other operations on it as the activity
232 * manager requests.
233 *
234 * {@hide}
235 */
Andrii Kulian446e8242017-10-26 15:17:29 -0700236public final class ActivityThread extends ClientTransactionHandler {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700237 /** @hide */
238 public static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700239 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
Joe Onorato43a17652011-04-06 19:22:23 -0700240 static final boolean localLOGV = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700241 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborne829fef2010-10-26 17:44:01 -0700242 /** @hide */
243 public static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700244 private static final boolean DEBUG_RESULTS = false;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700245 private static final boolean DEBUG_BACKUP = false;
Craig Mautner88c05892013-06-28 09:47:45 -0700246 public static final boolean DEBUG_CONFIGURATION = false;
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800247 private static final boolean DEBUG_SERVICE = false;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800248 public static final boolean DEBUG_MEMORY_TRIM = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700249 private static final boolean DEBUG_PROVIDER = false;
Andrii Kulianb372da62018-01-18 10:46:24 -0800250 public static final boolean DEBUG_ORDER = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
Riddle Hsu4e8e3b02019-04-12 17:37:10 +0800252 /**
Riddle Hsu50e34002019-04-12 20:42:05 +0800253 * If the activity doesn't become idle in time, the timeout will ensure to apply the pending top
254 * process state.
255 */
256 private static final long PENDING_TOP_PROCESS_STATE_TIMEOUT = 1000;
257 /**
Riddle Hsu4e8e3b02019-04-12 17:37:10 +0800258 * The delay to release the provider when it has no more references. It reduces the number of
259 * transactions for acquiring and releasing provider if the client accesses the provider
260 * frequently in a short time.
261 */
262 private static final long CONTENT_PROVIDER_RETAIN_TIME = 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264
Dianne Hackborn455625e2015-01-21 09:55:13 -0800265 /** Type for IActivityManager.serviceDoneExecuting: anonymous operation */
266 public static final int SERVICE_DONE_EXECUTING_ANON = 0;
267 /** Type for IActivityManager.serviceDoneExecuting: done with an onStart call */
268 public static final int SERVICE_DONE_EXECUTING_START = 1;
269 /** Type for IActivityManager.serviceDoneExecuting: done stopping (destroying) service */
270 public static final int SERVICE_DONE_EXECUTING_STOP = 2;
271
Filip Gruszczynskica664812015-12-04 12:43:36 -0800272 // Whether to invoke an activity callback after delivering new configuration.
273 private static final boolean REPORT_TO_ACTIVITY = true;
274
Riddle Hsu50e34002019-04-12 20:42:05 +0800275 /** Use foreground GC policy (less pause time) and higher JIT weight. */
276 private static final int VM_PROCESS_STATE_JANK_PERCEPTIBLE = 0;
277 /** Use background GC policy and default JIT threshold. */
278 private static final int VM_PROCESS_STATE_JANK_IMPERCEPTIBLE = 1;
279
Sudheer Shanka84a48952017-03-08 18:19:01 -0800280 /**
281 * Denotes an invalid sequence number corresponding to a process state change.
282 */
283 public static final long INVALID_PROC_STATE_SEQ = -1;
284
Sudheer Shankaf6690102017-10-16 10:20:32 -0700285 /**
286 * Identifier for the sequence no. associated with this process start. It will be provided
287 * as one of the arguments when the process starts.
288 */
289 public static final String PROC_START_SEQ_IDENT = "seq=";
290
Sudheer Shanka84a48952017-03-08 18:19:01 -0800291 private final Object mNetworkPolicyLock = new Object();
292
293 /**
294 * Denotes the sequence number of the process state change for which the main thread needs
295 * to block until the network rules are updated for it.
296 *
297 * Value of {@link #INVALID_PROC_STATE_SEQ} indicates there is no need for blocking.
298 */
299 @GuardedBy("mNetworkPolicyLock")
300 private long mNetworkBlockSeq = INVALID_PROC_STATE_SEQ;
301
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100302 @UnsupportedAppUsage
Jeff Browndefd4a62014-03-10 21:24:37 -0700303 private ContextImpl mSystemContext;
Adam Lesinskia82b6262017-03-21 16:56:17 -0700304 private ContextImpl mSystemUiContext;
Bob Leee5408332009-09-04 18:31:17 -0700305
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100306 @UnsupportedAppUsage
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700307 static volatile IPackageManager sPackageManager;
Todd Kennedy8f135982019-07-02 07:35:15 -0700308 private static volatile IPermissionManager sPermissionManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800309
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100310 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700311 final ApplicationThread mAppThread = new ApplicationThread();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100312 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700313 final Looper mLooper = Looper.myLooper();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100314 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700315 final H mH = new H();
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700316 final Executor mExecutor = new HandlerExecutor(mH);
Garfield Tan0443b372019-01-04 15:00:13 -0800317 /**
318 * Maps from activity token to local record of running activities in this process.
319 *
320 * This variable is readable if the code is running in activity thread or holding {@link
321 * #mResourcesManager}. It's only writable if the code is running in activity thread and holding
322 * {@link #mResourcesManager}.
323 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100324 @UnsupportedAppUsage
Dianne Hackborn782d4982015-07-08 17:36:37 -0700325 final ArrayMap<IBinder, ActivityClientRecord> mActivities = new ArrayMap<>();
Riddle Hsu66b74a82018-07-26 00:20:12 +0800326 /** The activities to be truly destroyed (not include relaunch). */
Riddle Hsud3062cb2018-06-30 02:06:42 +0800327 final Map<IBinder, ClientTransactionItem> mActivitiesToBeDestroyed =
328 Collections.synchronizedMap(new ArrayMap<IBinder, ClientTransactionItem>());
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700329 // List of new activities (via ActivityRecord.nextIdle) that should
330 // be reported when next we idle.
331 ActivityClientRecord mNewActivities = null;
332 // Number of activities that are currently visible on-screen.
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100333 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700334 int mNumVisibleActivities = 0;
Riddle Hsu50e34002019-04-12 20:42:05 +0800335 private final AtomicInteger mNumLaunchingActivities = new AtomicInteger();
336 @GuardedBy("mAppThread")
337 private int mLastProcessState = PROCESS_STATE_UNKNOWN;
338 @GuardedBy("mAppThread")
339 private int mPendingProcessState = PROCESS_STATE_UNKNOWN;
Amith Yamasani4f128e42016-05-10 11:44:12 -0700340 ArrayList<WeakReference<AssistStructure>> mLastAssistStructures = new ArrayList<>();
341 private int mLastSessionId;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100342 @UnsupportedAppUsage
Dianne Hackborn782d4982015-07-08 17:36:37 -0700343 final ArrayMap<IBinder, Service> mServices = new ArrayMap<>();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100344 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700345 AppBindData mBoundApplication;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700346 Profiler mProfiler;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100347 @UnsupportedAppUsage
Dianne Hackborn908aecc2012-07-31 16:37:34 -0700348 int mCurDefaultDisplayDpi;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100349 @UnsupportedAppUsage
Dianne Hackborndde331c2012-08-03 14:01:57 -0700350 boolean mDensityCompatMode;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100351 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700352 Configuration mConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700353 Configuration mCompatConfiguration;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100354 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700355 Application mInitialApplication;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100356 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700357 final ArrayList<Application> mAllApplications
358 = new ArrayList<Application>();
Annie Mengd5827872019-01-30 20:28:57 +0000359 /**
360 * Bookkeeping of instantiated backup agents indexed first by user id, then by package name.
361 * Indexing by user id supports parallel backups across users on system packages as they run in
362 * the same process with the same package name. Indexing by package name supports multiple
363 * distinct applications running in the same process.
364 */
365 private final SparseArray<ArrayMap<String, BackupAgent>> mBackupAgentsByUser =
366 new SparseArray<>();
Jeff Sharkey66a017b2013-01-17 18:18:22 -0800367 /** Reference to singleton {@link ActivityThread} */
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100368 @UnsupportedAppUsage
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700369 private static volatile ActivityThread sCurrentActivityThread;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100370 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700371 Instrumentation mInstrumentation;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700372 String mInstrumentationPackageName = null;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100373 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700374 String mInstrumentationAppDir = null;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700375 String[] mInstrumentationSplitAppDirs = null;
376 String mInstrumentationLibDir = null;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100377 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700378 String mInstrumentedAppDir = null;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700379 String[] mInstrumentedSplitAppDirs = null;
380 String mInstrumentedLibDir = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700381 boolean mSystemThread = false;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700382 boolean mSomeActivitiesChanged = false;
David Brazdild960cc42018-01-31 07:59:17 +0000383 /* package */ boolean mHiddenApiWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100385 // These can be accessed by multiple threads; mResourcesManager is the lock.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700386 // XXX For now we keep around information about all packages we have
387 // seen, not removing entries from this map.
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800388 // NOTE: The activity and window managers need to call in to
Dianne Hackborn2f0b1752011-05-31 17:59:49 -0700389 // ActivityThread to do things like update resource configurations,
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800390 // which means this lock gets held while the activity and window managers
391 // holds their own lock. Thus you MUST NEVER call back into the activity manager
392 // or window manager or anything that depends on them while holding this lock.
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700393 // These LoadedApk are only valid for the userId that we're running as.
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100394 @GuardedBy("mResourcesManager")
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100395 @UnsupportedAppUsage
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100396 final ArrayMap<String, WeakReference<LoadedApk>> mPackages = new ArrayMap<>();
397 @GuardedBy("mResourcesManager")
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100398 @UnsupportedAppUsage
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100399 final ArrayMap<String, WeakReference<LoadedApk>> mResourcePackages = new ArrayMap<>();
400 @GuardedBy("mResourcesManager")
401 final ArrayList<ActivityClientRecord> mRelaunchingActivities = new ArrayList<>();
402 @GuardedBy("mResourcesManager")
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100403 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700404 Configuration mPendingConfiguration = null;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800405 // An executor that performs multi-step transactions.
406 private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407
Mathew Inwood8c854f82018-09-14 12:35:36 +0100408 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Craig Mautner88c05892013-06-28 09:47:45 -0700409 private final ResourcesManager mResourcesManager;
410
Riddle Hsud490c572020-04-17 01:39:27 +0800411 /** The active adjustments that override the {@link DisplayAdjustments} in resources. */
412 private ArrayList<Pair<IBinder, Consumer<DisplayAdjustments>>> mActiveRotationAdjustments;
413
Svet Ganov3b6be082019-04-28 10:21:01 -0700414 // Registry of remote cancellation transports pending a reply with reply handles.
415 @GuardedBy("this")
416 private @Nullable Map<SafeCancellationTransport, CancellationSignal> mRemoteCancellations;
417
Hongwei Wang5711b8f2019-11-15 15:44:12 -0800418 private final Map<IBinder, Integer> mLastReportedWindowingMode = Collections.synchronizedMap(
419 new ArrayMap<>());
420
Jeff Sharkey6d515712012-09-20 16:06:08 -0700421 private static final class ProviderKey {
422 final String authority;
423 final int userId;
424
425 public ProviderKey(String authority, int userId) {
426 this.authority = authority;
427 this.userId = userId;
428 }
429
430 @Override
431 public boolean equals(Object o) {
432 if (o instanceof ProviderKey) {
433 final ProviderKey other = (ProviderKey) o;
Kenny Roote6585b32013-12-13 12:00:26 -0800434 return Objects.equals(authority, other.authority) && userId == other.userId;
Jeff Sharkey6d515712012-09-20 16:06:08 -0700435 }
436 return false;
437 }
438
439 @Override
440 public int hashCode() {
441 return ((authority != null) ? authority.hashCode() : 0) ^ userId;
442 }
443 }
444
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700445 // The lock of mProviderMap protects the following variables.
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100446 @UnsupportedAppUsage
Wale Ogunwale1d646122015-04-24 14:45:14 -0700447 final ArrayMap<ProviderKey, ProviderClientRecord> mProviderMap
448 = new ArrayMap<ProviderKey, ProviderClientRecord>();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100449 @UnsupportedAppUsage
Wale Ogunwale1d646122015-04-24 14:45:14 -0700450 final ArrayMap<IBinder, ProviderRefCount> mProviderRefCountMap
451 = new ArrayMap<IBinder, ProviderRefCount>();
Mathew Inwood8c854f82018-09-14 12:35:36 +0100452 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Wale Ogunwale1d646122015-04-24 14:45:14 -0700453 final ArrayMap<IBinder, ProviderClientRecord> mLocalProviders
454 = new ArrayMap<IBinder, ProviderClientRecord>();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100455 @UnsupportedAppUsage
Wale Ogunwale1d646122015-04-24 14:45:14 -0700456 final ArrayMap<ComponentName, ProviderClientRecord> mLocalProvidersByName
457 = new ArrayMap<ComponentName, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458
Makoto Onukib6c79ea2018-05-31 11:03:56 -0700459 // Mitigation for b/74523247: Used to serialize calls to AM.getContentProvider().
460 // Note we never removes items from this map but that's okay because there are only so many
461 // users and so many authorities.
462 // TODO Remove it once we move CPR.wait() from AMS to the client side.
463 @GuardedBy("mGetProviderLocks")
464 final ArrayMap<ProviderKey, Object> mGetProviderLocks = new ArrayMap<>();
465
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700466 final ArrayMap<Activity, ArrayList<OnActivityPausedListener>> mOnPauseListeners
Wale Ogunwale1d646122015-04-24 14:45:14 -0700467 = new ArrayMap<Activity, ArrayList<OnActivityPausedListener>>();
Jeff Hamilton52d32032011-01-08 15:31:26 -0600468
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700469 final GcIdler mGcIdler = new GcIdler();
Tim Murray59f3dc12018-10-22 15:26:08 -0700470 final PurgeIdler mPurgeIdler = new PurgeIdler();
471
472 boolean mPurgeIdlerScheduled = false;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700473 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800474
Mathew Inwood8c854f82018-09-14 12:35:36 +0100475 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700476 static volatile Handler sMainThreadHandler; // set once in main()
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700477
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800478 Bundle mCoreSettings = null;
479
lumarkddc77fb2019-06-27 22:22:23 +0800480 boolean mHasImeComponent = false;
481
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800482 /** Activity client record, used for bookkeeping for the real {@link Activity} instance. */
483 public static final class ActivityClientRecord {
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100484 @UnsupportedAppUsage
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800485 public IBinder token;
Sunny Goyald40c3452019-03-20 12:46:55 -0700486 public IBinder assistToken;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700487 int ident;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100488 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 Intent intent;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800490 String referrer;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700491 IVoiceInteractor voiceInteractor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 Bundle state;
Craig Mautnera0026042014-04-23 11:45:37 -0700493 PersistableBundle persistentState;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100494 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 Activity activity;
496 Window window;
497 Activity parent;
498 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700499 Activity.NonConfigurationInstances lastNonConfigurationInstances;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800500 // TODO(lifecycler): Use mLifecycleState instead.
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100501 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502 boolean paused;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100503 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 boolean stopped;
505 boolean hideForNow;
506 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700507 Configuration createdConfig;
Wale Ogunwale60454db2015-01-23 16:05:07 -0800508 Configuration overrideConfig;
Garfield Tan0443b372019-01-04 15:00:13 -0800509 // Used to save the last reported configuration from server side so that activity
510 // configuration transactions can always use the latest configuration.
511 @GuardedBy("this")
512 private Configuration mPendingOverrideConfig;
Wale Ogunwalec2607b42015-02-07 16:16:59 -0800513 // Used for consolidating configs before sending on to Activity.
514 private Configuration tmpConfig = new Configuration();
Andrii Kulian44607962017-03-16 11:06:24 -0700515 // Callback used for updating activity override config.
516 ViewRootImpl.ActivityConfigCallback configCallback;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700517 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518
Andrii Kuliand70cdb92019-01-08 15:03:50 -0800519 // Indicates whether this activity is currently the topmost resumed one in the system.
520 // This holds the last reported value from server.
521 boolean isTopResumedActivity;
522 // This holds the value last sent to the activity. This is needed, because an update from
523 // server may come at random time, but we always need to report changes between ON_RESUME
524 // and ON_PAUSE to the app.
525 boolean lastReportedTopResumedState;
526
Jeff Hao1b012d32014-08-20 10:35:34 -0700527 ProfilerInfo profilerInfo;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700528
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100529 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 ActivityInfo activityInfo;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100531 @UnsupportedAppUsage
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400532 CompatibilityInfo compatInfo;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100533 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +0000534 public LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535
536 List<ResultInfo> pendingResults;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800537 List<ReferrerIntent> pendingIntents;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538
539 boolean startsNotResumed;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800540 public final boolean isForward;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800541 int pendingConfigChanges;
jorgegil@google.com06bc3232019-10-31 14:51:22 -0700542 // Whether we are in the process of performing on user leaving.
543 boolean mIsUserLeaving;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800544
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700545 Window mPendingRemoveWindow;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800546 WindowManager mPendingRemoveWindowManager;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100547 @UnsupportedAppUsage
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700548 boolean mPreserveWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549
Riddle Hsud490c572020-04-17 01:39:27 +0800550 /**
551 * If non-null, the activity is launching with a specified rotation, the adjustments should
552 * be consumed before activity creation.
553 */
554 FixedRotationAdjustments mPendingFixedRotationAdjustments;
555
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800556 @LifecycleState
557 private int mLifecycleState = PRE_ON_CREATE;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700558
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800559 @VisibleForTesting
Mathew Inwood8c854f82018-09-14 12:35:36 +0100560 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800561 public ActivityClientRecord() {
562 this.isForward = false;
563 init();
564 }
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700565
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800566 public ActivityClientRecord(IBinder token, Intent intent, int ident,
567 ActivityInfo info, Configuration overrideConfig, CompatibilityInfo compatInfo,
568 String referrer, IVoiceInteractor voiceInteractor, Bundle state,
569 PersistableBundle persistentState, List<ResultInfo> pendingResults,
570 List<ReferrerIntent> pendingNewIntents, boolean isForward,
Sunny Goyald40c3452019-03-20 12:46:55 -0700571 ProfilerInfo profilerInfo, ClientTransactionHandler client,
Riddle Hsud490c572020-04-17 01:39:27 +0800572 IBinder assistToken, FixedRotationAdjustments fixedRotationAdjustments) {
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800573 this.token = token;
Sunny Goyald40c3452019-03-20 12:46:55 -0700574 this.assistToken = assistToken;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800575 this.ident = ident;
576 this.intent = intent;
577 this.referrer = referrer;
578 this.voiceInteractor = voiceInteractor;
579 this.activityInfo = info;
580 this.compatInfo = compatInfo;
581 this.state = state;
582 this.persistentState = persistentState;
583 this.pendingResults = pendingResults;
584 this.pendingIntents = pendingNewIntents;
585 this.isForward = isForward;
586 this.profilerInfo = profilerInfo;
587 this.overrideConfig = overrideConfig;
Todd Kennedy233a0b12018-01-29 20:30:24 +0000588 this.packageInfo = client.getPackageInfoNoCheck(activityInfo.applicationInfo,
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800589 compatInfo);
Riddle Hsud490c572020-04-17 01:39:27 +0800590 mPendingFixedRotationAdjustments = fixedRotationAdjustments;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800591 init();
592 }
593
594 /** Common initializer for all constructors. */
595 private void init() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 parent = null;
597 embeddedID = null;
598 paused = false;
599 stopped = false;
600 hideForNow = false;
601 nextIdle = null;
Andrii Kulian44607962017-03-16 11:06:24 -0700602 configCallback = (Configuration overrideConfig, int newDisplayId) -> {
603 if (activity == null) {
604 throw new IllegalStateException(
605 "Received config update for non-existing activity");
606 }
Riddle Hsue553a892020-04-14 17:19:46 +0800607 // Given alwaysReportChange=false because the configuration is from view root, the
608 // activity may not be able to handle the changes. In that case the activity will be
609 // relaunched immediately, then Activity#onConfigurationChanged shouldn't be called.
Andrii Kulian446e8242017-10-26 15:17:29 -0700610 activity.mMainThread.handleActivityConfigurationChanged(token, overrideConfig,
Riddle Hsue553a892020-04-14 17:19:46 +0800611 newDisplayId, false /* alwaysReportChange */);
Andrii Kulian44607962017-03-16 11:06:24 -0700612 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 }
614
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800615 /** Get the current lifecycle state. */
616 public int getLifecycleState() {
617 return mLifecycleState;
618 }
619
620 /** Update the current lifecycle state for internal bookkeeping. */
621 public void setState(@LifecycleState int newLifecycleState) {
622 mLifecycleState = newLifecycleState;
623 switch (mLifecycleState) {
624 case ON_CREATE:
625 paused = true;
626 stopped = true;
627 break;
628 case ON_START:
629 paused = true;
630 stopped = false;
631 break;
632 case ON_RESUME:
633 paused = false;
634 stopped = false;
635 break;
636 case ON_PAUSE:
637 paused = true;
638 stopped = false;
639 break;
640 case ON_STOP:
641 paused = true;
642 stopped = true;
643 break;
644 }
645 }
646
Andrii Kulian391161f2018-01-29 10:50:02 -0800647 private boolean isPreHoneycomb() {
648 return activity != null && activity.getApplicationInfo().targetSdkVersion
649 < android.os.Build.VERSION_CODES.HONEYCOMB;
650 }
651
652 private boolean isPreP() {
653 return activity != null && activity.getApplicationInfo().targetSdkVersion
654 < android.os.Build.VERSION_CODES.P;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800655 }
656
Craig Mautnera0026042014-04-23 11:45:37 -0700657 public boolean isPersistable() {
Craig Mautner43e52ed2014-06-16 17:18:52 -0700658 return activityInfo.persistableMode == ActivityInfo.PERSIST_ACROSS_REBOOTS;
Craig Mautnera0026042014-04-23 11:45:37 -0700659 }
660
Andrii Kulian914aa7d2018-03-19 21:51:53 -0700661 public boolean isVisibleFromServer() {
662 return activity != null && activity.mVisibleFromServer;
663 }
664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 public String toString() {
Dianne Hackbornb61a0262012-05-14 17:19:18 -0700666 ComponentName componentName = intent != null ? intent.getComponent() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 return "ActivityRecord{"
668 + Integer.toHexString(System.identityHashCode(this))
669 + " token=" + token + " " + (componentName == null
670 ? "no component name" : componentName.toShortString())
671 + "}";
672 }
Andrii Kulian58178f22016-03-16 13:44:56 -0700673
674 public String getStateString() {
675 StringBuilder sb = new StringBuilder();
676 sb.append("ActivityClientRecord{");
677 sb.append("paused=").append(paused);
678 sb.append(", stopped=").append(stopped);
679 sb.append(", hideForNow=").append(hideForNow);
680 sb.append(", startsNotResumed=").append(startsNotResumed);
681 sb.append(", isForward=").append(isForward);
682 sb.append(", pendingConfigChanges=").append(pendingConfigChanges);
Andrii Kulian58178f22016-03-16 13:44:56 -0700683 sb.append(", preserveWindow=").append(mPreserveWindow);
684 if (activity != null) {
685 sb.append(", Activity{");
686 sb.append("resumed=").append(activity.mResumed);
687 sb.append(", stopped=").append(activity.mStopped);
688 sb.append(", finished=").append(activity.isFinishing());
689 sb.append(", destroyed=").append(activity.isDestroyed());
690 sb.append(", startedActivity=").append(activity.mStartedActivity);
Andrii Kulian58178f22016-03-16 13:44:56 -0700691 sb.append(", changingConfigurations=").append(activity.mChangingConfigurations);
Andrii Kulian58178f22016-03-16 13:44:56 -0700692 sb.append("}");
693 }
694 sb.append("}");
695 return sb.toString();
696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 }
698
Wale Ogunwale1d646122015-04-24 14:45:14 -0700699 final class ProviderClientRecord {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700700 final String[] mNames;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100701 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 final IContentProvider mProvider;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100703 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 final ContentProvider mLocalProvider;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100705 @UnsupportedAppUsage
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700706 final ContentProviderHolder mHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700708 ProviderClientRecord(String[] names, IContentProvider provider,
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700709 ContentProvider localProvider, ContentProviderHolder holder) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700710 mNames = names;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 mProvider = provider;
712 mLocalProvider = localProvider;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700713 mHolder = holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 }
715 }
716
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400717 static final class ReceiverData extends BroadcastReceiver.PendingResult {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700718 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700719 boolean ordered, boolean sticky, IBinder token, int sendingUser) {
720 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky,
riddle_hsu1f5ac4d2015-01-03 15:38:21 +0800721 token, sendingUser, intent.getFlags());
Dianne Hackborne829fef2010-10-26 17:44:01 -0700722 this.intent = intent;
723 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700724
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100725 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 Intent intent;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100727 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 ActivityInfo info;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100729 @UnsupportedAppUsage
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400730 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 public String toString() {
732 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700733 info.packageName + " resultCode=" + getResultCode()
734 + " resultData=" + getResultData() + " resultExtras="
735 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 }
737 }
738
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400739 static final class CreateBackupAgentData {
Christopher Tate181fafa2009-05-14 11:12:14 -0700740 ApplicationInfo appInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400741 CompatibilityInfo compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700742 int backupMode;
Ruslan Tkhakokhov063180f2019-01-28 20:29:46 +0000743 int userId;
Christopher Tate181fafa2009-05-14 11:12:14 -0700744 public String toString() {
745 return "CreateBackupAgentData{appInfo=" + appInfo
746 + " backupAgent=" + appInfo.backupAgentName
Ruslan Tkhakokhov063180f2019-01-28 20:29:46 +0000747 + " mode=" + backupMode + " userId=" + userId + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700748 }
749 }
Bob Leee5408332009-09-04 18:31:17 -0700750
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400751 static final class CreateServiceData {
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100752 @UnsupportedAppUsage
Artur Satayev751e5512019-11-15 19:12:49 +0000753 CreateServiceData() {
754 }
755 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 IBinder token;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100757 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 ServiceInfo info;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100759 @UnsupportedAppUsage
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400760 CompatibilityInfo compatInfo;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100761 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 Intent intent;
763 public String toString() {
764 return "CreateServiceData{token=" + token + " className="
765 + info.name + " packageName=" + info.packageName
766 + " intent=" + intent + "}";
767 }
768 }
769
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400770 static final class BindServiceData {
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100771 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 IBinder token;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100773 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 Intent intent;
775 boolean rebind;
776 public String toString() {
777 return "BindServiceData{token=" + token + " intent=" + intent + "}";
778 }
779 }
780
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400781 static final class ServiceArgsData {
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100782 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 IBinder token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700784 boolean taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700786 int flags;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100787 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 Intent args;
789 public String toString() {
790 return "ServiceArgsData{token=" + token + " startId=" + startId
791 + " args=" + args + "}";
792 }
793 }
794
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400795 static final class AppBindData {
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100796 @UnsupportedAppUsage
Artur Satayev751e5512019-11-15 19:12:49 +0000797 AppBindData() {
798 }
799 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +0000800 LoadedApk info;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100801 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 String processName;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100803 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 ApplicationInfo appInfo;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100805 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 List<ProviderInfo> providers;
807 ComponentName instrumentationName;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100808 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 Bundle instrumentationArgs;
810 IInstrumentationWatcher instrumentationWatcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800811 IUiAutomationConnection instrumentationUiAutomationConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 int debugMode;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400813 boolean enableBinderTracking;
Man Caocfa78b22015-06-11 20:14:34 -0700814 boolean trackAllocation;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100815 @UnsupportedAppUsage
Christopher Tate181fafa2009-05-14 11:12:14 -0700816 boolean restrictedBackupMode;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100817 @UnsupportedAppUsage
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700818 boolean persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 Configuration config;
Mathew Inwood8c854f82018-09-14 12:35:36 +0100820 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400821 CompatibilityInfo compatInfo;
Svet Ganov37e43272016-09-09 16:01:32 -0700822 String buildSerial;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700823
824 /** Initial values for {@link Profiler}. */
Jeff Hao1b012d32014-08-20 10:35:34 -0700825 ProfilerInfo initProfilerInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700826
Felipe Lemea4f39cd2019-02-19 15:08:59 -0800827 AutofillOptions autofillOptions;
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800828
Felipe Leme326f15a2019-02-19 09:42:24 -0800829 /**
830 * Content capture options for the application - when null, it means ContentCapture is not
831 * enabled for the package.
832 */
833 @Nullable
834 ContentCaptureOptions contentCaptureOptions;
835
Mathew Inwood80652db2019-06-24 12:07:22 +0100836 long[] disabledCompatChanges;
837
Felipe Leme326f15a2019-02-19 09:42:24 -0800838 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 public String toString() {
840 return "AppBindData{appInfo=" + appInfo + "}";
841 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700842 }
843
844 static final class Profiler {
845 String profileFile;
846 ParcelFileDescriptor profileFd;
Jeff Hao1b012d32014-08-20 10:35:34 -0700847 int samplingInterval;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700848 boolean autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800849 boolean streamingOutput;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700850 boolean profiling;
851 boolean handlingProfiling;
Jeff Hao1b012d32014-08-20 10:35:34 -0700852 public void setProfiler(ProfilerInfo profilerInfo) {
853 ParcelFileDescriptor fd = profilerInfo.profileFd;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700854 if (profiling) {
855 if (fd != null) {
856 try {
857 fd.close();
858 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700859 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700860 }
861 }
862 return;
863 }
864 if (profileFd != null) {
865 try {
866 profileFd.close();
867 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700868 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700869 }
870 }
Jeff Hao1b012d32014-08-20 10:35:34 -0700871 profileFile = profilerInfo.profileFile;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700872 profileFd = fd;
Jeff Hao1b012d32014-08-20 10:35:34 -0700873 samplingInterval = profilerInfo.samplingInterval;
874 autoStopProfiler = profilerInfo.autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800875 streamingOutput = profilerInfo.streamingOutput;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700876 }
877 public void startProfiling() {
878 if (profileFd == null || profiling) {
879 return;
880 }
881 try {
Andreas Gampeeff06392016-05-10 12:51:45 -0700882 int bufferSize = SystemProperties.getInt("debug.traceview-buffer-size-mb", 8);
Jeff Hao1b012d32014-08-20 10:35:34 -0700883 VMDebug.startMethodTracing(profileFile, profileFd.getFileDescriptor(),
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800884 bufferSize * 1024 * 1024, 0, samplingInterval != 0, samplingInterval,
885 streamingOutput);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700886 profiling = true;
887 } catch (RuntimeException e) {
Andreas Gampe4f689242018-03-14 23:13:28 -0700888 Slog.w(TAG, "Profiling failed on path " + profileFile, e);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700889 try {
890 profileFd.close();
891 profileFd = null;
892 } catch (IOException e2) {
893 Slog.w(TAG, "Failure closing profile fd", e2);
894 }
895 }
896 }
897 public void stopProfiling() {
898 if (profiling) {
899 profiling = false;
900 Debug.stopMethodTracing();
901 if (profileFd != null) {
902 try {
903 profileFd.close();
904 } catch (IOException e) {
905 }
906 }
907 profileFd = null;
908 profileFile = null;
909 }
910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 }
912
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400913 static final class DumpComponentInfo {
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700914 ParcelFileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700915 IBinder token;
Dianne Hackborn30d71892010-12-11 10:37:55 -0800916 String prefix;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 String[] args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 }
919
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400920 static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800921 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 String what;
923 String who;
924 }
925
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400926 static final class DumpHeapData {
Kweku Adams4af1b502019-05-23 16:23:48 -0700927 // Whether to dump the native or managed heap.
Christopher Ferris8d652f82017-04-11 16:29:18 -0700928 public boolean managed;
929 public boolean mallocInfo;
Makoto Onuki4556b7b2017-07-07 14:58:58 -0700930 public boolean runGc;
Andy McFadden824c5102010-07-09 16:26:57 -0700931 String path;
932 ParcelFileDescriptor fd;
Makoto Onuki2c6657f2018-06-06 15:24:02 -0700933 RemoteCallback finishCallback;
Andy McFadden824c5102010-07-09 16:26:57 -0700934 }
935
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400936 static final class UpdateCompatibilityData {
937 String pkg;
938 CompatibilityInfo info;
939 }
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800940
Adam Skorydfc7fd72013-08-05 19:23:41 -0700941 static final class RequestAssistContextExtras {
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800942 IBinder activityToken;
943 IBinder requestToken;
944 int requestType;
Amith Yamasani4f128e42016-05-10 11:44:12 -0700945 int sessionId;
Svet Ganovfd31f852017-04-26 15:54:27 -0700946 int flags;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800947 }
Anwar Ghuloum3a8ce1b2013-04-26 16:18:28 -0700948
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700949 private class ApplicationThread extends IApplicationThread.Stub {
Vasu Nori3c7131f2010-09-21 14:36:57 -0700950 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 public final void scheduleReceiver(Intent intent, ActivityInfo info,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400953 CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700954 boolean sync, int sendingUser, int processState) {
955 updateProcessState(processState, false);
Dianne Hackborne829fef2010-10-26 17:44:01 -0700956 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700957 sync, false, mAppThread.asBinder(), sendingUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 r.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400959 r.compatInfo = compatInfo;
Jeff Brown9ef09972013-10-15 20:49:59 -0700960 sendMessage(H.RECEIVER, r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 }
962
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400963 public final void scheduleCreateBackupAgent(ApplicationInfo app,
Ruslan Tkhakokhov063180f2019-01-28 20:29:46 +0000964 CompatibilityInfo compatInfo, int backupMode, int userId) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700965 CreateBackupAgentData d = new CreateBackupAgentData();
966 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400967 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700968 d.backupMode = backupMode;
Ruslan Tkhakokhov063180f2019-01-28 20:29:46 +0000969 d.userId = userId;
Christopher Tate181fafa2009-05-14 11:12:14 -0700970
Jeff Brown9ef09972013-10-15 20:49:59 -0700971 sendMessage(H.CREATE_BACKUP_AGENT, d);
Christopher Tate181fafa2009-05-14 11:12:14 -0700972 }
973
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400974 public final void scheduleDestroyBackupAgent(ApplicationInfo app,
Annie Mengd5827872019-01-30 20:28:57 +0000975 CompatibilityInfo compatInfo, int userId) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700976 CreateBackupAgentData d = new CreateBackupAgentData();
977 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400978 d.compatInfo = compatInfo;
Annie Mengd5827872019-01-30 20:28:57 +0000979 d.userId = userId;
Christopher Tate181fafa2009-05-14 11:12:14 -0700980
Jeff Brown9ef09972013-10-15 20:49:59 -0700981 sendMessage(H.DESTROY_BACKUP_AGENT, d);
Christopher Tate181fafa2009-05-14 11:12:14 -0700982 }
983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 public final void scheduleCreateService(IBinder token,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700985 ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
986 updateProcessState(processState, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 CreateServiceData s = new CreateServiceData();
988 s.token = token;
989 s.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400990 s.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991
Jeff Brown9ef09972013-10-15 20:49:59 -0700992 sendMessage(H.CREATE_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 }
994
995 public final void scheduleBindService(IBinder token, Intent intent,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700996 boolean rebind, int processState) {
997 updateProcessState(processState, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 BindServiceData s = new BindServiceData();
999 s.token = token;
1000 s.intent = intent;
1001 s.rebind = rebind;
1002
Amith Yamasani742a6712011-05-04 14:49:28 -07001003 if (DEBUG_SERVICE)
1004 Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
1005 + Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
Jeff Brown9ef09972013-10-15 20:49:59 -07001006 sendMessage(H.BIND_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 }
1008
1009 public final void scheduleUnbindService(IBinder token, Intent intent) {
1010 BindServiceData s = new BindServiceData();
1011 s.token = token;
1012 s.intent = intent;
1013
Jeff Brown9ef09972013-10-15 20:49:59 -07001014 sendMessage(H.UNBIND_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 }
1016
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07001017 public final void scheduleServiceArgs(IBinder token, ParceledListSlice args) {
1018 List<ServiceStartArgs> list = args.getList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -07001020 for (int i = 0; i < list.size(); i++) {
1021 ServiceStartArgs ssa = list.get(i);
1022 ServiceArgsData s = new ServiceArgsData();
1023 s.token = token;
1024 s.taskRemoved = ssa.taskRemoved;
1025 s.startId = ssa.startId;
1026 s.flags = ssa.flags;
1027 s.args = ssa.args;
1028
1029 sendMessage(H.SERVICE_ARGS, s);
1030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 }
1032
1033 public final void scheduleStopService(IBinder token) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001034 sendMessage(H.STOP_SERVICE, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 }
1036
Makoto Onuki2d80ca02020-02-12 14:20:36 -08001037 @Override
Jeff Hao1b012d32014-08-20 10:35:34 -07001038 public final void bindApplication(String processName, ApplicationInfo appInfo,
Makoto Onuki2d80ca02020-02-12 14:20:36 -08001039 ProviderInfoList providerList, ComponentName instrumentationName,
Jeff Hao1b012d32014-08-20 10:35:34 -07001040 ProfilerInfo profilerInfo, Bundle instrumentationArgs,
1041 IInstrumentationWatcher instrumentationWatcher,
Svetoslav Ganov80943d82013-01-02 10:25:37 -08001042 IUiAutomationConnection instrumentationUiConnection, int debugMode,
Pablo Ceballosa4d4e822015-10-05 10:27:52 -07001043 boolean enableBinderTracking, boolean trackAllocation,
1044 boolean isRestrictedBackupMode, boolean persistent, Configuration config,
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001045 CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
Felipe Lemea4f39cd2019-02-19 15:08:59 -08001046 String buildSerial, AutofillOptions autofillOptions,
Mathew Inwood80652db2019-06-24 12:07:22 +01001047 ContentCaptureOptions contentCaptureOptions, long[] disabledCompatChanges) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 if (services != null) {
Makoto Onuki45895652018-05-07 14:43:05 -07001049 if (false) {
1050 // Test code to make sure the app could see the passed-in services.
1051 for (Object oname : services.keySet()) {
1052 if (services.get(oname) == null) {
1053 continue; // AM just passed in a null service.
1054 }
1055 String name = (String) oname;
1056
1057 // See b/79378449 about the following exemption.
1058 switch (name) {
1059 case "package":
1060 case Context.WINDOW_SERVICE:
1061 continue;
1062 }
1063
1064 if (ServiceManager.getService(name) == null) {
1065 Log.wtf(TAG, "Service " + name + " should be accessible by this app");
1066 }
1067 }
1068 }
1069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 // Setup the service cache in the ServiceManager
1071 ServiceManager.initServiceCache(services);
1072 }
1073
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08001074 setCoreSettings(coreSettings);
1075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 AppBindData data = new AppBindData();
1077 data.processName = processName;
1078 data.appInfo = appInfo;
Makoto Onuki2d80ca02020-02-12 14:20:36 -08001079 data.providers = providerList.getList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 data.instrumentationName = instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 data.instrumentationArgs = instrumentationArgs;
1082 data.instrumentationWatcher = instrumentationWatcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -08001083 data.instrumentationUiAutomationConnection = instrumentationUiConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 data.debugMode = debugMode;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001085 data.enableBinderTracking = enableBinderTracking;
Man Caocfa78b22015-06-11 20:14:34 -07001086 data.trackAllocation = trackAllocation;
Christopher Tate181fafa2009-05-14 11:12:14 -07001087 data.restrictedBackupMode = isRestrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -07001088 data.persistent = persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 data.config = config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001090 data.compatInfo = compatInfo;
Jeff Hao1b012d32014-08-20 10:35:34 -07001091 data.initProfilerInfo = profilerInfo;
Svet Ganov37e43272016-09-09 16:01:32 -07001092 data.buildSerial = buildSerial;
Felipe Lemea4f39cd2019-02-19 15:08:59 -08001093 data.autofillOptions = autofillOptions;
Felipe Leme326f15a2019-02-19 09:42:24 -08001094 data.contentCaptureOptions = contentCaptureOptions;
Mathew Inwood80652db2019-06-24 12:07:22 +01001095 data.disabledCompatChanges = disabledCompatChanges;
Jeff Brown9ef09972013-10-15 20:49:59 -07001096 sendMessage(H.BIND_APPLICATION, data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 }
1098
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001099 public final void runIsolatedEntryPoint(String entryPoint, String[] entryPointArgs) {
1100 SomeArgs args = SomeArgs.obtain();
1101 args.arg1 = entryPoint;
1102 args.arg2 = entryPointArgs;
1103 sendMessage(H.RUN_ISOLATED_ENTRY_POINT, args);
1104 }
1105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 public final void scheduleExit() {
Jeff Brown9ef09972013-10-15 20:49:59 -07001107 sendMessage(H.EXIT_APPLICATION, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 }
1109
Christopher Tate5e1ab332009-09-01 20:32:49 -07001110 public final void scheduleSuicide() {
Jeff Brown9ef09972013-10-15 20:49:59 -07001111 sendMessage(H.SUICIDE, null);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001112 }
1113
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001114 public void scheduleApplicationInfoChanged(ApplicationInfo ai) {
Winson Chung6ee17422019-05-07 13:22:15 -07001115 mH.removeMessages(H.APPLICATION_INFO_CHANGED, ai);
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001116 sendMessage(H.APPLICATION_INFO_CHANGED, ai);
1117 }
1118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 public void updateTimeZone() {
1120 TimeZone.setDefault(null);
1121 }
1122
Robert Greenwalt03595d02010-11-02 14:08:23 -07001123 public void clearDnsCache() {
1124 // a non-standard API to get this to libcore
1125 InetAddress.clearDnsCache();
Paul Jensene401d172014-09-12 10:47:39 -04001126 // Allow libcore to perform the necessary actions as it sees fit upon a network
1127 // configuration change.
1128 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Robert Greenwalt03595d02010-11-02 14:08:23 -07001129 }
1130
Irina Dumitrescu18622d32018-12-05 16:19:47 +00001131 public void updateHttpProxy() {
Irina Dumitrescu34a27c42019-04-15 19:20:38 +01001132 ActivityThread.updateHttpProxy(
Chalard Jean100df0a2018-05-15 23:11:45 +09001133 getApplication() != null ? getApplication() : getSystemContext());
Robert Greenwalt434203a2010-10-11 16:00:27 -07001134 }
1135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 public void processInBackground() {
1137 mH.removeMessages(H.GC_WHEN_IDLE);
1138 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
1139 }
1140
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001141 public void dumpService(ParcelFileDescriptor pfd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07001142 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001143 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001144 data.fd = pfd.dup();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001145 data.token = servicetoken;
1146 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001147 sendMessage(H.DUMP_SERVICE, data, 0, 0, true /*async*/);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001148 } catch (IOException e) {
1149 Slog.w(TAG, "dumpService failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001150 } finally {
1151 IoUtils.closeQuietly(pfd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 }
1153 }
1154
1155 // This function exists to make sure all receiver dispatching is
1156 // correctly ordered, since these are one-way calls and the binder driver
1157 // applies transaction ordering per object for such calls.
1158 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07001159 int resultCode, String dataStr, Bundle extras, boolean ordered,
Dianne Hackborna413dc02013-07-12 12:02:55 -07001160 boolean sticky, int sendingUser, int processState) throws RemoteException {
1161 updateProcessState(processState, false);
Dianne Hackborn20e80982012-08-31 19:00:44 -07001162 receiver.performReceive(intent, resultCode, dataStr, extras, ordered,
1163 sticky, sendingUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 }
Bob Leee5408332009-09-04 18:31:17 -07001165
Wale Ogunwalec2607b42015-02-07 16:16:59 -08001166 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 public void scheduleLowMemory() {
Jeff Brown9ef09972013-10-15 20:49:59 -07001168 sendMessage(H.LOW_MEMORY, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 }
1170
Wale Ogunwale60454db2015-01-23 16:05:07 -08001171 @Override
Jeff Hao1b012d32014-08-20 10:35:34 -07001172 public void profilerControl(boolean start, ProfilerInfo profilerInfo, int profileType) {
1173 sendMessage(H.PROFILER_CONTROL, profilerInfo, start ? 1 : 0, profileType);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001174 }
1175
Makoto Onuki4556b7b2017-07-07 14:58:58 -07001176 @Override
Christopher Ferris8d652f82017-04-11 16:29:18 -07001177 public void dumpHeap(boolean managed, boolean mallocInfo, boolean runGc, String path,
Makoto Onuki2c6657f2018-06-06 15:24:02 -07001178 ParcelFileDescriptor fd, RemoteCallback finishCallback) {
Andy McFadden824c5102010-07-09 16:26:57 -07001179 DumpHeapData dhd = new DumpHeapData();
Christopher Ferris8d652f82017-04-11 16:29:18 -07001180 dhd.managed = managed;
1181 dhd.mallocInfo = mallocInfo;
Makoto Onuki4556b7b2017-07-07 14:58:58 -07001182 dhd.runGc = runGc;
Andy McFadden824c5102010-07-09 16:26:57 -07001183 dhd.path = path;
Kweku Adams4af1b502019-05-23 16:23:48 -07001184 try {
1185 // Since we're going to dump the heap asynchronously, dup the file descriptor before
1186 // it's closed on returning from the IPC call.
1187 dhd.fd = fd.dup();
1188 } catch (IOException e) {
1189 Slog.e(TAG, "Failed to duplicate heap dump file descriptor", e);
1190 return;
Kweku Adamsf1ddecc2020-04-23 12:34:20 -07001191 } finally {
1192 IoUtils.closeQuietly(fd);
Kweku Adams4af1b502019-05-23 16:23:48 -07001193 }
Makoto Onuki2c6657f2018-06-06 15:24:02 -07001194 dhd.finishCallback = finishCallback;
Christopher Ferris8d652f82017-04-11 16:29:18 -07001195 sendMessage(H.DUMP_HEAP, dhd, 0, 0, true /*async*/);
Andy McFadden824c5102010-07-09 16:26:57 -07001196 }
1197
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001198 public void attachAgent(String agent) {
1199 sendMessage(H.ATTACH_AGENT, agent);
1200 }
1201
Alex Light2d0691c2019-10-03 14:36:57 -07001202 public void attachStartupAgents(String dataDir) {
1203 sendMessage(H.ATTACH_STARTUP_AGENTS, dataDir);
1204 }
1205
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001206 public void setSchedulingGroup(int group) {
1207 // Note: do this immediately, since going into the foreground
1208 // should happen regardless of what pending work we have to do
1209 // and the activity manager will wait for us to report back that
1210 // we are done before sending us to the background.
1211 try {
1212 Process.setProcessGroup(Process.myPid(), group);
1213 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001214 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001215 }
1216 }
Bob Leee5408332009-09-04 18:31:17 -07001217
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001218 public void dispatchPackageBroadcast(int cmd, String[] packages) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001219 sendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001220 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001221
1222 public void scheduleCrash(String msg) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001223 sendMessage(H.SCHEDULE_CRASH, msg);
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001224 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07001225
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001226 public void dumpActivity(ParcelFileDescriptor pfd, IBinder activitytoken,
Dianne Hackborn30d71892010-12-11 10:37:55 -08001227 String prefix, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07001228 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001229 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001230 data.fd = pfd.dup();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001231 data.token = activitytoken;
1232 data.prefix = prefix;
1233 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001234 sendMessage(H.DUMP_ACTIVITY, data, 0, 0, true /*async*/);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001235 } catch (IOException e) {
1236 Slog.w(TAG, "dumpActivity failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001237 } finally {
1238 IoUtils.closeQuietly(pfd);
Dianne Hackborn625ac272010-09-17 18:29:22 -07001239 }
1240 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07001241
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001242 public void dumpProvider(ParcelFileDescriptor pfd, IBinder providertoken,
Marco Nelissen18cb2872011-11-15 11:19:53 -08001243 String[] args) {
1244 DumpComponentInfo data = new DumpComponentInfo();
1245 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001246 data.fd = pfd.dup();
Marco Nelissen18cb2872011-11-15 11:19:53 -08001247 data.token = providertoken;
1248 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001249 sendMessage(H.DUMP_PROVIDER, data, 0, 0, true /*async*/);
Marco Nelissen18cb2872011-11-15 11:19:53 -08001250 } catch (IOException e) {
1251 Slog.w(TAG, "dumpProvider failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001252 } finally {
1253 IoUtils.closeQuietly(pfd);
Marco Nelissen18cb2872011-11-15 11:19:53 -08001254 }
1255 }
1256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001258 public void dumpMemInfo(ParcelFileDescriptor pfd, Debug.MemoryInfo mem, boolean checkin,
Colin Crossc4fb5f92016-02-02 16:51:15 -08001259 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
1260 boolean dumpUnreachable, String[] args) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001261 FileOutputStream fout = new FileOutputStream(pfd.getFileDescriptor());
Dianne Hackborn8c841092013-06-24 13:46:13 -07001262 PrintWriter pw = new FastPrintWriter(fout);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001263 try {
Colin Crossc4fb5f92016-02-02 16:51:15 -08001264 dumpMemInfo(pw, mem, checkin, dumpFullInfo, dumpDalvik, dumpSummaryOnly, dumpUnreachable);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001265 } finally {
Chet Haase9c1e23b2011-03-24 10:51:31 -07001266 pw.flush();
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001267 IoUtils.closeQuietly(pfd);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001268 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001269 }
1270
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001271 private void dumpMemInfo(PrintWriter pw, Debug.MemoryInfo memInfo, boolean checkin,
Colin Crossc4fb5f92016-02-02 16:51:15 -08001272 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly, boolean dumpUnreachable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 long nativeMax = Debug.getNativeHeapSize() / 1024;
1274 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1275 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 Runtime runtime = Runtime.getRuntime();
Mathieu Chartierd288a262015-07-10 13:44:42 -07001278 runtime.gc(); // Do GC since countInstancesOfClass counts unreachable objects.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 long dalvikMax = runtime.totalMemory() / 1024;
1280 long dalvikFree = runtime.freeMemory() / 1024;
1281 long dalvikAllocated = dalvikMax - dalvikFree;
Richard Uhler2c036192016-09-14 09:48:31 +01001282
1283 Class[] classesToCount = new Class[] {
1284 ContextImpl.class,
1285 Activity.class,
1286 WebView.class,
1287 OpenSSLSocketImpl.class
1288 };
1289 long[] instanceCounts = VMDebug.countInstancesOfClasses(classesToCount, true);
1290 long appContextInstanceCount = instanceCounts[0];
1291 long activityInstanceCount = instanceCounts[1];
1292 long webviewInstanceCount = instanceCounts[2];
1293 long openSslSocketCount = instanceCounts[3];
1294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 long viewInstanceCount = ViewDebug.getViewInstanceCount();
Romain Guy65b345f2011-07-27 18:51:50 -07001296 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 int globalAssetCount = AssetManager.getGlobalAssetCount();
1298 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1299 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1300 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1301 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Dianne Hackbornfabb70b2014-11-11 12:22:36 -08001302 long parcelSize = Parcel.getGlobalAllocSize();
1303 long parcelCount = Parcel.getGlobalAllocCount();
Vasu Noric3849202010-03-09 10:47:25 -08001304 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -07001305
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07001306 dumpMemInfoTable(pw, memInfo, checkin, dumpFullInfo, dumpDalvik, dumpSummaryOnly,
1307 Process.myPid(),
Dianne Hackborne77187d2013-10-25 16:32:41 -07001308 (mBoundApplication != null) ? mBoundApplication.processName : "unknown",
1309 nativeMax, nativeAllocated, nativeFree,
1310 dalvikMax, dalvikAllocated, dalvikFree);
1311
Dianne Hackbornb437e092011-08-05 17:50:29 -07001312 if (checkin) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 // NOTE: if you change anything significant below, also consider changing
1314 // ACTIVITY_THREAD_CHECKIN_VERSION.
Anwar Ghuloum3c615062013-05-13 14:18:02 -07001315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 // Object counts
1317 pw.print(viewInstanceCount); pw.print(',');
1318 pw.print(viewRootInstanceCount); pw.print(',');
1319 pw.print(appContextInstanceCount); pw.print(',');
1320 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 pw.print(globalAssetCount); pw.print(',');
1323 pw.print(globalAssetManagerCount); pw.print(',');
1324 pw.print(binderLocalObjectCount); pw.print(',');
1325 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 pw.print(binderDeathObjectCount); pw.print(',');
1328 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 // SQL
Vasu Noric3849202010-03-09 10:47:25 -08001331 pw.print(stats.memoryUsed / 1024); pw.print(',');
Jeff Brown2a293b62012-01-19 14:02:22 -08001332 pw.print(stats.memoryUsed / 1024); pw.print(',');
1333 pw.print(stats.pageCacheOverflow / 1024); pw.print(',');
Dianne Hackbornb437e092011-08-05 17:50:29 -07001334 pw.print(stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001335 for (int i = 0; i < stats.dbStats.size(); i++) {
1336 DbStats dbStats = stats.dbStats.get(i);
Dianne Hackbornb437e092011-08-05 17:50:29 -07001337 pw.print(','); pw.print(dbStats.dbName);
1338 pw.print(','); pw.print(dbStats.pageSize);
1339 pw.print(','); pw.print(dbStats.dbSize);
1340 pw.print(','); pw.print(dbStats.lookaside);
1341 pw.print(','); pw.print(dbStats.cache);
1342 pw.print(','); pw.print(dbStats.cache);
Vasu Noric3849202010-03-09 10:47:25 -08001343 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07001344 pw.println();
Bob Leee5408332009-09-04 18:31:17 -07001345
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001346 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 }
Bob Leee5408332009-09-04 18:31:17 -07001348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 pw.println(" ");
1350 pw.println(" Objects");
Romain Guy65b345f2011-07-27 18:51:50 -07001351 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRootImpl:",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 viewRootInstanceCount);
1353
1354 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
1355 "Activities:", activityInstanceCount);
1356
1357 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
1358 "AssetManagers:", globalAssetManagerCount);
1359
1360 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
1361 "Proxy Binders:", binderProxyObjectCount);
Dianne Hackbornfabb70b2014-11-11 12:22:36 -08001362 printRow(pw, TWO_COUNT_COLUMNS, "Parcel memory:", parcelSize/1024,
1363 "Parcel count:", parcelCount);
1364 printRow(pw, TWO_COUNT_COLUMNS, "Death Recipients:", binderDeathObjectCount,
1365 "OpenSSL Sockets:", openSslSocketCount);
Richard Uhler2c036192016-09-14 09:48:31 +01001366 printRow(pw, ONE_COUNT_COLUMN, "WebViews:", webviewInstanceCount);
Bob Leee5408332009-09-04 18:31:17 -07001367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 // SQLite mem info
1369 pw.println(" ");
1370 pw.println(" SQL");
Jeff Brown2a293b62012-01-19 14:02:22 -08001371 printRow(pw, ONE_COUNT_COLUMN, "MEMORY_USED:", stats.memoryUsed / 1024);
1372 printRow(pw, TWO_COUNT_COLUMNS, "PAGECACHE_OVERFLOW:",
1373 stats.pageCacheOverflow / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001374 pw.println(" ");
1375 int N = stats.dbStats.size();
1376 if (N > 0) {
1377 pw.println(" DATABASES");
Kweku Adams983829f2017-12-06 14:53:50 -08001378 printRow(pw, DB_INFO_FORMAT, "pgsz", "dbsz", "Lookaside(b)", "cache",
Vasu Nori3c7131f2010-09-21 14:36:57 -07001379 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -08001380 for (int i = 0; i < N; i++) {
1381 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -07001382 printRow(pw, DB_INFO_FORMAT,
1383 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
1384 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
1385 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
1386 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -08001387 }
1388 }
Bob Leee5408332009-09-04 18:31:17 -07001389
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001390 // Asset details.
1391 String assetAlloc = AssetManager.getAssetAllocations();
1392 if (assetAlloc != null) {
1393 pw.println(" ");
1394 pw.println(" Asset Allocations");
1395 pw.print(assetAlloc);
1396 }
Colin Crossc4fb5f92016-02-02 16:51:15 -08001397
1398 // Unreachable native memory
1399 if (dumpUnreachable) {
1400 boolean showContents = ((mBoundApplication != null)
1401 && ((mBoundApplication.appInfo.flags&ApplicationInfo.FLAG_DEBUGGABLE) != 0))
1402 || android.os.Build.IS_DEBUGGABLE;
1403 pw.println(" ");
1404 pw.println(" Unreachable memory");
1405 pw.print(Debug.getUnreachableMemory(100, showContents));
1406 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001407 }
1408
1409 @Override
Kweku Adams983829f2017-12-06 14:53:50 -08001410 public void dumpMemInfoProto(ParcelFileDescriptor pfd, Debug.MemoryInfo mem,
1411 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
1412 boolean dumpUnreachable, String[] args) {
1413 ProtoOutputStream proto = new ProtoOutputStream(pfd.getFileDescriptor());
1414 try {
1415 dumpMemInfo(proto, mem, dumpFullInfo, dumpDalvik, dumpSummaryOnly, dumpUnreachable);
1416 } finally {
1417 proto.flush();
1418 IoUtils.closeQuietly(pfd);
1419 }
1420 }
1421
1422 private void dumpMemInfo(ProtoOutputStream proto, Debug.MemoryInfo memInfo,
1423 boolean dumpFullInfo, boolean dumpDalvik,
1424 boolean dumpSummaryOnly, boolean dumpUnreachable) {
1425 long nativeMax = Debug.getNativeHeapSize() / 1024;
1426 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1427 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1428
1429 Runtime runtime = Runtime.getRuntime();
1430 runtime.gc(); // Do GC since countInstancesOfClass counts unreachable objects.
1431 long dalvikMax = runtime.totalMemory() / 1024;
1432 long dalvikFree = runtime.freeMemory() / 1024;
1433 long dalvikAllocated = dalvikMax - dalvikFree;
1434
1435 Class[] classesToCount = new Class[] {
1436 ContextImpl.class,
1437 Activity.class,
1438 WebView.class,
1439 OpenSSLSocketImpl.class
1440 };
1441 long[] instanceCounts = VMDebug.countInstancesOfClasses(classesToCount, true);
1442 long appContextInstanceCount = instanceCounts[0];
1443 long activityInstanceCount = instanceCounts[1];
1444 long webviewInstanceCount = instanceCounts[2];
1445 long openSslSocketCount = instanceCounts[3];
1446
1447 long viewInstanceCount = ViewDebug.getViewInstanceCount();
1448 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
1449 int globalAssetCount = AssetManager.getGlobalAssetCount();
1450 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1451 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1452 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1453 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
1454 long parcelSize = Parcel.getGlobalAllocSize();
1455 long parcelCount = Parcel.getGlobalAllocCount();
1456 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
1457
Yi Jin2b30f322018-02-20 15:41:47 -08001458 final long mToken = proto.start(MemInfoDumpProto.AppData.PROCESS_MEMORY);
1459 proto.write(MemInfoDumpProto.ProcessMemory.PID, Process.myPid());
1460 proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME,
Kweku Adams983829f2017-12-06 14:53:50 -08001461 (mBoundApplication != null) ? mBoundApplication.processName : "unknown");
1462 dumpMemInfoTable(proto, memInfo, dumpDalvik, dumpSummaryOnly,
1463 nativeMax, nativeAllocated, nativeFree,
1464 dalvikMax, dalvikAllocated, dalvikFree);
1465 proto.end(mToken);
1466
Yi Jin2b30f322018-02-20 15:41:47 -08001467 final long oToken = proto.start(MemInfoDumpProto.AppData.OBJECTS);
1468 proto.write(MemInfoDumpProto.AppData.ObjectStats.VIEW_INSTANCE_COUNT,
1469 viewInstanceCount);
1470 proto.write(MemInfoDumpProto.AppData.ObjectStats.VIEW_ROOT_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001471 viewRootInstanceCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001472 proto.write(MemInfoDumpProto.AppData.ObjectStats.APP_CONTEXT_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001473 appContextInstanceCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001474 proto.write(MemInfoDumpProto.AppData.ObjectStats.ACTIVITY_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001475 activityInstanceCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001476 proto.write(MemInfoDumpProto.AppData.ObjectStats.GLOBAL_ASSET_COUNT,
1477 globalAssetCount);
1478 proto.write(MemInfoDumpProto.AppData.ObjectStats.GLOBAL_ASSET_MANAGER_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001479 globalAssetManagerCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001480 proto.write(MemInfoDumpProto.AppData.ObjectStats.LOCAL_BINDER_OBJECT_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001481 binderLocalObjectCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001482 proto.write(MemInfoDumpProto.AppData.ObjectStats.PROXY_BINDER_OBJECT_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001483 binderProxyObjectCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001484 proto.write(MemInfoDumpProto.AppData.ObjectStats.PARCEL_MEMORY_KB,
1485 parcelSize / 1024);
1486 proto.write(MemInfoDumpProto.AppData.ObjectStats.PARCEL_COUNT, parcelCount);
1487 proto.write(MemInfoDumpProto.AppData.ObjectStats.BINDER_OBJECT_DEATH_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001488 binderDeathObjectCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001489 proto.write(MemInfoDumpProto.AppData.ObjectStats.OPEN_SSL_SOCKET_COUNT,
1490 openSslSocketCount);
1491 proto.write(MemInfoDumpProto.AppData.ObjectStats.WEBVIEW_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001492 webviewInstanceCount);
1493 proto.end(oToken);
1494
1495 // SQLite mem info
Yi Jin2b30f322018-02-20 15:41:47 -08001496 final long sToken = proto.start(MemInfoDumpProto.AppData.SQL);
1497 proto.write(MemInfoDumpProto.AppData.SqlStats.MEMORY_USED_KB,
1498 stats.memoryUsed / 1024);
1499 proto.write(MemInfoDumpProto.AppData.SqlStats.PAGECACHE_OVERFLOW_KB,
Kweku Adams983829f2017-12-06 14:53:50 -08001500 stats.pageCacheOverflow / 1024);
Yi Jin2b30f322018-02-20 15:41:47 -08001501 proto.write(MemInfoDumpProto.AppData.SqlStats.MALLOC_SIZE_KB,
1502 stats.largestMemAlloc / 1024);
Kweku Adams983829f2017-12-06 14:53:50 -08001503 int n = stats.dbStats.size();
1504 for (int i = 0; i < n; i++) {
1505 DbStats dbStats = stats.dbStats.get(i);
1506
Yi Jin2b30f322018-02-20 15:41:47 -08001507 final long dToken = proto.start(MemInfoDumpProto.AppData.SqlStats.DATABASES);
1508 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.NAME, dbStats.dbName);
1509 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.PAGE_SIZE, dbStats.pageSize);
1510 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.DB_SIZE, dbStats.dbSize);
1511 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.LOOKASIDE_B,
1512 dbStats.lookaside);
1513 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.CACHE, dbStats.cache);
Kweku Adams983829f2017-12-06 14:53:50 -08001514 proto.end(dToken);
1515 }
1516 proto.end(sToken);
1517
1518 // Asset details.
1519 String assetAlloc = AssetManager.getAssetAllocations();
1520 if (assetAlloc != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08001521 proto.write(MemInfoDumpProto.AppData.ASSET_ALLOCATIONS, assetAlloc);
Kweku Adams983829f2017-12-06 14:53:50 -08001522 }
1523
1524 // Unreachable native memory
1525 if (dumpUnreachable) {
1526 int flags = mBoundApplication == null ? 0 : mBoundApplication.appInfo.flags;
1527 boolean showContents = (flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0
1528 || android.os.Build.IS_DEBUGGABLE;
Yi Jin2b30f322018-02-20 15:41:47 -08001529 proto.write(MemInfoDumpProto.AppData.UNREACHABLE_MEMORY,
Kweku Adams983829f2017-12-06 14:53:50 -08001530 Debug.getUnreachableMemory(100, showContents));
1531 }
1532 }
1533
1534 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001535 public void dumpGfxInfo(ParcelFileDescriptor pfd, String[] args) {
Chris Craikfc294242016-12-13 18:10:46 -08001536 nDumpGraphicsInfo(pfd.getFileDescriptor());
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001537 WindowManagerGlobal.getInstance().dumpGfxInfo(pfd.getFileDescriptor(), args);
1538 IoUtils.closeQuietly(pfd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
1540
Makoto Onuki016dc592018-08-14 12:26:45 -07001541 private File getDatabasesDir(Context context) {
1542 // There's no simple way to get the databases/ path, so do it this way.
1543 return context.getDatabasePath("a").getParentFile();
1544 }
1545
1546 private void dumpDatabaseInfo(ParcelFileDescriptor pfd, String[] args, boolean isSystem) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001547 PrintWriter pw = new FastPrintWriter(
1548 new FileOutputStream(pfd.getFileDescriptor()));
Jeff Brown6754ba22011-12-14 20:20:01 -08001549 PrintWriterPrinter printer = new PrintWriterPrinter(pw);
Makoto Onukiee93ad22018-10-18 16:24:13 -07001550 SQLiteDebug.dump(printer, args, isSystem);
Jeff Brown6754ba22011-12-14 20:20:01 -08001551 pw.flush();
1552 }
1553
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001554 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001555 public void dumpDbInfo(final ParcelFileDescriptor pfd, final String[] args) {
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001556 if (mSystemThread) {
Felipe Leme29de4922016-06-07 16:14:07 -07001557 // Ensure this invocation is asynchronous to prevent writer waiting if buffer cannot
1558 // be consumed. But it must duplicate the file descriptor first, since caller might
1559 // be closing it.
1560 final ParcelFileDescriptor dup;
1561 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001562 dup = pfd.dup();
Felipe Leme29de4922016-06-07 16:14:07 -07001563 } catch (IOException e) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001564 Log.w(TAG, "Could not dup FD " + pfd.getFileDescriptor().getInt$());
Felipe Leme29de4922016-06-07 16:14:07 -07001565 return;
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001566 } finally {
1567 IoUtils.closeQuietly(pfd);
Felipe Leme29de4922016-06-07 16:14:07 -07001568 }
1569
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001570 AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
1571 @Override
1572 public void run() {
Felipe Lemec74972f2016-06-08 09:12:37 -07001573 try {
Makoto Onuki016dc592018-08-14 12:26:45 -07001574 dumpDatabaseInfo(dup, args, true);
Felipe Lemec74972f2016-06-08 09:12:37 -07001575 } finally {
1576 IoUtils.closeQuietly(dup);
1577 }
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001578 }
1579 });
1580 } else {
Makoto Onuki016dc592018-08-14 12:26:45 -07001581 dumpDatabaseInfo(pfd, args, false);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001582 IoUtils.closeQuietly(pfd);
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001583 }
1584 }
1585
1586 @Override
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001587 public void unstableProviderDied(IBinder provider) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001588 sendMessage(H.UNSTABLE_PROVIDER_DIED, provider);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001589 }
1590
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001591 @Override
Adam Skorydfc7fd72013-08-05 19:23:41 -07001592 public void requestAssistContextExtras(IBinder activityToken, IBinder requestToken,
Svet Ganovfd31f852017-04-26 15:54:27 -07001593 int requestType, int sessionId, int flags) {
Adam Skorydfc7fd72013-08-05 19:23:41 -07001594 RequestAssistContextExtras cmd = new RequestAssistContextExtras();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001595 cmd.activityToken = activityToken;
1596 cmd.requestToken = requestToken;
1597 cmd.requestType = requestType;
Amith Yamasani4f128e42016-05-10 11:44:12 -07001598 cmd.sessionId = sessionId;
Svet Ganovfd31f852017-04-26 15:54:27 -07001599 cmd.flags = flags;
Jeff Brown9ef09972013-10-15 20:49:59 -07001600 sendMessage(H.REQUEST_ASSIST_CONTEXT_EXTRAS, cmd);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001601 }
1602
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08001603 public void setCoreSettings(Bundle coreSettings) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001604 sendMessage(H.SET_CORE_SETTINGS, coreSettings);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001605 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001606
1607 public void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) {
1608 UpdateCompatibilityData ucd = new UpdateCompatibilityData();
1609 ucd.pkg = pkg;
1610 ucd.info = info;
Jeff Brown9ef09972013-10-15 20:49:59 -07001611 sendMessage(H.UPDATE_PACKAGE_COMPATIBILITY_INFO, ucd);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001612 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001613
1614 public void scheduleTrimMemory(int level) {
Jorim Jaggib29e3182018-04-30 18:51:56 +02001615 final Runnable r = PooledLambda.obtainRunnable(ActivityThread::handleTrimMemory,
Yohei Yukawae2fa39e2018-09-22 13:13:10 -07001616 ActivityThread.this, level).recycleOnUse();
Jorim Jaggib29e3182018-04-30 18:51:56 +02001617 // Schedule trimming memory after drawing the frame to minimize jank-risk.
1618 Choreographer choreographer = Choreographer.getMainThreadInstance();
1619 if (choreographer != null) {
1620 choreographer.postCallback(Choreographer.CALLBACK_COMMIT, r, null);
1621 } else {
1622 mH.post(r);
1623 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001624 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001625
Craig Mautner5eda9b32013-07-02 11:58:16 -07001626 public void scheduleTranslucentConversionComplete(IBinder token, boolean drawComplete) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001627 sendMessage(H.TRANSLUCENT_CONVERSION_COMPLETE, token, drawComplete ? 1 : 0);
Craig Mautner5eda9b32013-07-02 11:58:16 -07001628 }
Dianne Hackborna413dc02013-07-12 12:02:55 -07001629
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001630 public void scheduleOnNewActivityOptions(IBinder token, Bundle options) {
Craig Mautnereb8abf72014-07-02 15:04:09 -07001631 sendMessage(H.ON_NEW_ACTIVITY_OPTIONS,
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001632 new Pair<IBinder, ActivityOptions>(token, ActivityOptions.fromBundle(options)));
Craig Mautnereb8abf72014-07-02 15:04:09 -07001633 }
1634
Dianne Hackborna413dc02013-07-12 12:02:55 -07001635 public void setProcessState(int state) {
1636 updateProcessState(state, true);
1637 }
1638
Sudheer Shanka84a48952017-03-08 18:19:01 -08001639 /**
1640 * Updates {@link #mNetworkBlockSeq}. This is used by ActivityManagerService to inform
1641 * the main thread that it needs to wait for the network rules to get updated before
1642 * launching an activity.
1643 */
1644 @Override
1645 public void setNetworkBlockSeq(long procStateSeq) {
1646 synchronized (mNetworkPolicyLock) {
1647 mNetworkBlockSeq = procStateSeq;
1648 }
1649 }
1650
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001651 @Override
1652 public void scheduleInstallProvider(ProviderInfo provider) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001653 sendMessage(H.INSTALL_PROVIDER, provider);
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001654 }
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001655
1656 @Override
Neil Fullerb7146fe2016-11-15 16:52:15 +00001657 public final void updateTimePrefs(int timeFormatPreference) {
1658 final Boolean timeFormatPreferenceBool;
1659 // For convenience we are using the Intent extra values.
1660 if (timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_12_HOUR) {
1661 timeFormatPreferenceBool = Boolean.FALSE;
1662 } else if (timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_24_HOUR) {
1663 timeFormatPreferenceBool = Boolean.TRUE;
1664 } else {
1665 // timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_LOCALE_DEFAULT
1666 // (or unknown).
1667 timeFormatPreferenceBool = null;
1668 }
1669 DateFormat.set24HourTimePref(timeFormatPreferenceBool);
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001670 }
Craig Mautneree2e45a2014-06-27 12:10:03 -07001671
1672 @Override
Craig Mautner8746a472014-07-24 15:12:54 -07001673 public void scheduleEnterAnimationComplete(IBinder token) {
1674 sendMessage(H.ENTER_ANIMATION_COMPLETE, token);
1675 }
Jeff Sharkey605eb792014-11-04 13:34:06 -08001676
1677 @Override
1678 public void notifyCleartextNetwork(byte[] firstPacket) {
1679 if (StrictMode.vmCleartextNetworkEnabled()) {
1680 StrictMode.onCleartextNetworkDetected(firstPacket);
1681 }
1682 }
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001683
1684 @Override
1685 public void startBinderTracking() {
1686 sendMessage(H.START_BINDER_TRACKING, null);
1687 }
1688
1689 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001690 public void stopBinderTrackingAndDump(ParcelFileDescriptor pfd) {
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001691 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001692 sendMessage(H.STOP_BINDER_TRACKING_AND_DUMP, pfd.dup());
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001693 } catch (IOException e) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001694 } finally {
1695 IoUtils.closeQuietly(pfd);
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001696 }
1697 }
Wale Ogunwale5f986092015-12-04 15:35:38 -08001698
1699 @Override
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001700 public void scheduleLocalVoiceInteractionStarted(IBinder token,
1701 IVoiceInteractor voiceInteractor) throws RemoteException {
1702 SomeArgs args = SomeArgs.obtain();
1703 args.arg1 = token;
1704 args.arg2 = voiceInteractor;
1705 sendMessage(H.LOCAL_VOICE_INTERACTION_STARTED, args);
1706 }
Chad Brubakerc72875b2016-04-27 16:35:11 -07001707
1708 @Override
1709 public void handleTrustStorageUpdate() {
1710 NetworkSecurityPolicy.getInstance().handleTrustStorageUpdate();
1711 }
Andrii Kulian446e8242017-10-26 15:17:29 -07001712
1713 @Override
1714 public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
1715 ActivityThread.this.scheduleTransaction(transaction);
1716 }
Sunny Goyald40c3452019-03-20 12:46:55 -07001717
1718 @Override
1719 public void requestDirectActions(@NonNull IBinder activityToken,
Svet Ganov3b6be082019-04-28 10:21:01 -07001720 @NonNull IVoiceInteractor interactor, @Nullable RemoteCallback cancellationCallback,
1721 @NonNull RemoteCallback callback) {
1722 final CancellationSignal cancellationSignal = new CancellationSignal();
Sunny Goyald40c3452019-03-20 12:46:55 -07001723 if (cancellationCallback != null) {
Svet Ganov3b6be082019-04-28 10:21:01 -07001724 final ICancellationSignal transport = createSafeCancellationTransport(
1725 cancellationSignal);
Sunny Goyald40c3452019-03-20 12:46:55 -07001726 final Bundle cancellationResult = new Bundle();
1727 cancellationResult.putBinder(VoiceInteractor.KEY_CANCELLATION_SIGNAL,
1728 transport.asBinder());
1729 cancellationCallback.sendResult(cancellationResult);
Sunny Goyald40c3452019-03-20 12:46:55 -07001730 }
Svet Ganov3b6be082019-04-28 10:21:01 -07001731 mH.sendMessage(PooledLambda.obtainMessage(ActivityThread::handleRequestDirectActions,
1732 ActivityThread.this, activityToken, interactor, cancellationSignal, callback));
1733 }
Sunny Goyald40c3452019-03-20 12:46:55 -07001734
Svet Ganov3b6be082019-04-28 10:21:01 -07001735 @Override
1736 public void performDirectAction(@NonNull IBinder activityToken, @NonNull String actionId,
1737 @Nullable Bundle arguments, @Nullable RemoteCallback cancellationCallback,
1738 @NonNull RemoteCallback resultCallback) {
1739 final CancellationSignal cancellationSignal = new CancellationSignal();
1740 if (cancellationCallback != null) {
1741 final ICancellationSignal transport = createSafeCancellationTransport(
1742 cancellationSignal);
1743 final Bundle cancellationResult = new Bundle();
1744 cancellationResult.putBinder(VoiceInteractor.KEY_CANCELLATION_SIGNAL,
1745 transport.asBinder());
1746 cancellationCallback.sendResult(cancellationResult);
1747 }
Sunny Goyald40c3452019-03-20 12:46:55 -07001748 mH.sendMessage(PooledLambda.obtainMessage(ActivityThread::handlePerformDirectAction,
1749 ActivityThread.this, activityToken, actionId, arguments,
1750 cancellationSignal, resultCallback));
1751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 }
1753
Svet Ganov3b6be082019-04-28 10:21:01 -07001754 private @NonNull SafeCancellationTransport createSafeCancellationTransport(
1755 @NonNull CancellationSignal cancellationSignal) {
1756 synchronized (ActivityThread.this) {
1757 if (mRemoteCancellations == null) {
1758 mRemoteCancellations = new ArrayMap<>();
1759 }
1760 final SafeCancellationTransport transport = new SafeCancellationTransport(
1761 this, cancellationSignal);
1762 mRemoteCancellations.put(transport, cancellationSignal);
1763 return transport;
1764 }
1765 }
1766
1767 private @NonNull CancellationSignal removeSafeCancellationTransport(
1768 @NonNull SafeCancellationTransport transport) {
1769 synchronized (ActivityThread.this) {
1770 final CancellationSignal cancellation = mRemoteCancellations.remove(transport);
1771 if (mRemoteCancellations.isEmpty()) {
1772 mRemoteCancellations = null;
1773 }
1774 return cancellation;
1775 }
1776 }
1777
1778 private static final class SafeCancellationTransport extends ICancellationSignal.Stub {
1779 private final @NonNull WeakReference<ActivityThread> mWeakActivityThread;
1780
1781 SafeCancellationTransport(@NonNull ActivityThread activityThread,
1782 @NonNull CancellationSignal cancellation) {
1783 mWeakActivityThread = new WeakReference<>(activityThread);
1784 }
1785
1786 @Override
1787 public void cancel() {
1788 final ActivityThread activityThread = mWeakActivityThread.get();
1789 if (activityThread != null) {
1790 final CancellationSignal cancellation = activityThread
1791 .removeSafeCancellationTransport(this);
1792 if (cancellation != null) {
1793 cancellation.cancel();
1794 }
1795 }
1796 }
1797 }
1798
Andrii Kulian446e8242017-10-26 15:17:29 -07001799 class H extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 public static final int BIND_APPLICATION = 110;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001801 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 public static final int EXIT_APPLICATION = 111;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001803 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 public static final int RECEIVER = 113;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001805 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 public static final int CREATE_SERVICE = 114;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001807 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 public static final int SERVICE_ARGS = 115;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001809 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 public static final int STOP_SERVICE = 116;
Dianne Hackborn09233282014-04-30 11:33:59 -07001811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 public static final int CONFIGURATION_CHANGED = 118;
1813 public static final int CLEAN_UP_CONTEXT = 119;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001814 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 public static final int GC_WHEN_IDLE = 120;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001816 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 public static final int BIND_SERVICE = 121;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001818 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 public static final int UNBIND_SERVICE = 122;
1820 public static final int DUMP_SERVICE = 123;
1821 public static final int LOW_MEMORY = 124;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001822 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001823 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001824 public static final int DESTROY_BACKUP_AGENT = 129;
1825 public static final int SUICIDE = 130;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001826 @UnsupportedAppUsage
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001827 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001828 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001829 @UnsupportedAppUsage
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001830 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -07001831 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001832 public static final int DUMP_ACTIVITY = 136;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001833 public static final int SLEEPING = 137;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001834 public static final int SET_CORE_SETTINGS = 138;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001835 public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001836 @UnsupportedAppUsage
Marco Nelissen18cb2872011-11-15 11:19:53 -08001837 public static final int DUMP_PROVIDER = 141;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001838 public static final int UNSTABLE_PROVIDER_DIED = 142;
Adam Skorydfc7fd72013-08-05 19:23:41 -07001839 public static final int REQUEST_ASSIST_CONTEXT_EXTRAS = 143;
Craig Mautner5eda9b32013-07-02 11:58:16 -07001840 public static final int TRANSLUCENT_CONVERSION_COMPLETE = 144;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001841 @UnsupportedAppUsage
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001842 public static final int INSTALL_PROVIDER = 145;
Craig Mautnereb8abf72014-07-02 15:04:09 -07001843 public static final int ON_NEW_ACTIVITY_OPTIONS = 146;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001844 @UnsupportedAppUsage
Craig Mautner8746a472014-07-24 15:12:54 -07001845 public static final int ENTER_ANIMATION_COMPLETE = 149;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001846 public static final int START_BINDER_TRACKING = 150;
1847 public static final int STOP_BINDER_TRACKING_AND_DUMP = 151;
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001848 public static final int LOCAL_VOICE_INTERACTION_STARTED = 154;
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001849 public static final int ATTACH_AGENT = 155;
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001850 public static final int APPLICATION_INFO_CHANGED = 156;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001851 public static final int RUN_ISOLATED_ENTRY_POINT = 158;
Andrii Kulian446e8242017-10-26 15:17:29 -07001852 public static final int EXECUTE_TRANSACTION = 159;
Andrii Kulian320e3b52018-05-03 16:26:25 -07001853 public static final int RELAUNCH_ACTIVITY = 160;
Tim Murray59f3dc12018-10-22 15:26:08 -07001854 public static final int PURGE_RESOURCES = 161;
Alex Light2d0691c2019-10-03 14:36:57 -07001855 public static final int ATTACH_STARTUP_AGENTS = 162;
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001858 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 switch (code) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 case BIND_APPLICATION: return "BIND_APPLICATION";
1861 case EXIT_APPLICATION: return "EXIT_APPLICATION";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 case RECEIVER: return "RECEIVER";
1863 case CREATE_SERVICE: return "CREATE_SERVICE";
1864 case SERVICE_ARGS: return "SERVICE_ARGS";
1865 case STOP_SERVICE: return "STOP_SERVICE";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1867 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1868 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1869 case BIND_SERVICE: return "BIND_SERVICE";
1870 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1871 case DUMP_SERVICE: return "DUMP_SERVICE";
1872 case LOW_MEMORY: return "LOW_MEMORY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001873 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001874 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1875 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001876 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001877 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001878 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001879 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -07001880 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -07001881 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001882 case SET_CORE_SETTINGS: return "SET_CORE_SETTINGS";
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001883 case UPDATE_PACKAGE_COMPATIBILITY_INFO: return "UPDATE_PACKAGE_COMPATIBILITY_INFO";
Marco Nelissen18cb2872011-11-15 11:19:53 -08001884 case DUMP_PROVIDER: return "DUMP_PROVIDER";
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001885 case UNSTABLE_PROVIDER_DIED: return "UNSTABLE_PROVIDER_DIED";
Adam Skorydfc7fd72013-08-05 19:23:41 -07001886 case REQUEST_ASSIST_CONTEXT_EXTRAS: return "REQUEST_ASSIST_CONTEXT_EXTRAS";
Craig Mautner5eda9b32013-07-02 11:58:16 -07001887 case TRANSLUCENT_CONVERSION_COMPLETE: return "TRANSLUCENT_CONVERSION_COMPLETE";
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001888 case INSTALL_PROVIDER: return "INSTALL_PROVIDER";
Craig Mautnereb8abf72014-07-02 15:04:09 -07001889 case ON_NEW_ACTIVITY_OPTIONS: return "ON_NEW_ACTIVITY_OPTIONS";
Craig Mautner8746a472014-07-24 15:12:54 -07001890 case ENTER_ANIMATION_COMPLETE: return "ENTER_ANIMATION_COMPLETE";
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001891 case LOCAL_VOICE_INTERACTION_STARTED: return "LOCAL_VOICE_INTERACTION_STARTED";
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001892 case ATTACH_AGENT: return "ATTACH_AGENT";
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001893 case APPLICATION_INFO_CHANGED: return "APPLICATION_INFO_CHANGED";
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001894 case RUN_ISOLATED_ENTRY_POINT: return "RUN_ISOLATED_ENTRY_POINT";
Andrii Kulian446e8242017-10-26 15:17:29 -07001895 case EXECUTE_TRANSACTION: return "EXECUTE_TRANSACTION";
Andrii Kulian320e3b52018-05-03 16:26:25 -07001896 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
Tim Murray59f3dc12018-10-22 15:26:08 -07001897 case PURGE_RESOURCES: return "PURGE_RESOURCES";
Alex Light2d0691c2019-10-03 14:36:57 -07001898 case ATTACH_STARTUP_AGENTS: return "ATTACH_STARTUP_AGENTS";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 }
1900 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001901 return Integer.toString(code);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 }
1903 public void handleMessage(Message msg) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001904 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 switch (msg.what) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 case BIND_APPLICATION:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001907 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 AppBindData data = (AppBindData)msg.obj;
1909 handleBindApplication(data);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001910 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 break;
1912 case EXIT_APPLICATION:
1913 if (mInitialApplication != null) {
1914 mInitialApplication.onTerminate();
1915 }
1916 Looper.myLooper().quit();
1917 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001918 case RECEIVER:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001919 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveComp");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 handleReceiver((ReceiverData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001921 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001922 break;
1923 case CREATE_SERVICE:
John Recke48e6da2019-06-20 14:59:51 -07001924 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1925 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1926 ("serviceCreate: " + String.valueOf(msg.obj)));
1927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 handleCreateService((CreateServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001929 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 break;
1931 case BIND_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001932 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 handleBindService((BindServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001934 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 break;
1936 case UNBIND_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001937 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceUnbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 handleUnbindService((BindServiceData)msg.obj);
Tim Murray59f3dc12018-10-22 15:26:08 -07001939 schedulePurgeIdler();
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001940 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 break;
1942 case SERVICE_ARGS:
John Recke48e6da2019-06-20 14:59:51 -07001943 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1944 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1945 ("serviceStart: " + String.valueOf(msg.obj)));
1946 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 handleServiceArgs((ServiceArgsData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001948 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 break;
1950 case STOP_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001951 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 handleStopService((IBinder)msg.obj);
Tim Murray59f3dc12018-10-22 15:26:08 -07001953 schedulePurgeIdler();
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001954 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 case CONFIGURATION_CHANGED:
Andrii Kulian446e8242017-10-26 15:17:29 -07001957 handleConfigurationChanged((Configuration) msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 break;
1959 case CLEAN_UP_CONTEXT:
1960 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1961 cci.context.performFinalCleanup(cci.who, cci.what);
1962 break;
1963 case GC_WHEN_IDLE:
1964 scheduleGcIdler();
1965 break;
1966 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001967 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 break;
1969 case LOW_MEMORY:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001970 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "lowMemory");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 handleLowMemory();
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001972 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001974 case PROFILER_CONTROL:
Jeff Hao1b012d32014-08-20 10:35:34 -07001975 handleProfilerControl(msg.arg1 != 0, (ProfilerInfo)msg.obj, msg.arg2);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001976 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001977 case CREATE_BACKUP_AGENT:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001978 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupCreateAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001979 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001980 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate181fafa2009-05-14 11:12:14 -07001981 break;
1982 case DESTROY_BACKUP_AGENT:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001983 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupDestroyAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001984 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001985 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate181fafa2009-05-14 11:12:14 -07001986 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001987 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001988 Process.killProcess(Process.myPid());
1989 break;
1990 case REMOVE_PROVIDER:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001991 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "providerRemove");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001992 completeRemoveProvider((ProviderRefCount)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001993 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001994 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001995 case DISPATCH_PACKAGE_BROADCAST:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001996 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastPackage");
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001997 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001998 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001999 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002000 case SCHEDULE_CRASH:
2001 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07002002 case DUMP_HEAP:
Christopher Ferris8d652f82017-04-11 16:29:18 -07002003 handleDumpHeap((DumpHeapData) msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07002004 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07002005 case DUMP_ACTIVITY:
2006 handleDumpActivity((DumpComponentInfo)msg.obj);
2007 break;
Marco Nelissen18cb2872011-11-15 11:19:53 -08002008 case DUMP_PROVIDER:
2009 handleDumpProvider((DumpComponentInfo)msg.obj);
2010 break;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08002011 case SET_CORE_SETTINGS:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07002012 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setCoreSettings");
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08002013 handleSetCoreSettings((Bundle) msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07002014 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08002015 break;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002016 case UPDATE_PACKAGE_COMPATIBILITY_INFO:
2017 handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07002018 break;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07002019 case UNSTABLE_PROVIDER_DIED:
2020 handleUnstableProviderDied((IBinder)msg.obj, false);
2021 break;
Adam Skorydfc7fd72013-08-05 19:23:41 -07002022 case REQUEST_ASSIST_CONTEXT_EXTRAS:
2023 handleRequestAssistContextExtras((RequestAssistContextExtras)msg.obj);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08002024 break;
Craig Mautner5eda9b32013-07-02 11:58:16 -07002025 case TRANSLUCENT_CONVERSION_COMPLETE:
2026 handleTranslucentConversionComplete((IBinder)msg.obj, msg.arg1 == 1);
2027 break;
Jeff Sharkeydd97f422013-10-08 17:01:30 -07002028 case INSTALL_PROVIDER:
2029 handleInstallProvider((ProviderInfo) msg.obj);
2030 break;
Craig Mautnereb8abf72014-07-02 15:04:09 -07002031 case ON_NEW_ACTIVITY_OPTIONS:
2032 Pair<IBinder, ActivityOptions> pair = (Pair<IBinder, ActivityOptions>) msg.obj;
2033 onNewActivityOptions(pair.first, pair.second);
Dake Gu7ef70b02014-07-08 18:37:12 -07002034 break;
Craig Mautner8746a472014-07-24 15:12:54 -07002035 case ENTER_ANIMATION_COMPLETE:
2036 handleEnterAnimationComplete((IBinder) msg.obj);
2037 break;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04002038 case START_BINDER_TRACKING:
2039 handleStartBinderTracking();
2040 break;
2041 case STOP_BINDER_TRACKING_AND_DUMP:
2042 handleStopBinderTrackingAndDump((ParcelFileDescriptor) msg.obj);
2043 break;
Amith Yamasani0af6fa72016-01-17 15:36:19 -08002044 case LOCAL_VOICE_INTERACTION_STARTED:
2045 handleLocalVoiceInteractionStarted((IBinder) ((SomeArgs) msg.obj).arg1,
2046 (IVoiceInteractor) ((SomeArgs) msg.obj).arg2);
Amith Yamasani61019112017-01-10 15:05:00 -08002047 break;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08002048 case ATTACH_AGENT: {
2049 Application app = getApplication();
2050 handleAttachAgent((String) msg.obj, app != null ? app.mLoadedApk : null);
Amith Yamasani0af6fa72016-01-17 15:36:19 -08002051 break;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08002052 }
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01002053 case APPLICATION_INFO_CHANGED:
Riddle Hsue553a892020-04-14 17:19:46 +08002054 handleApplicationInfoChanged((ApplicationInfo) msg.obj);
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01002055 break;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04002056 case RUN_ISOLATED_ENTRY_POINT:
2057 handleRunIsolatedEntryPoint((String) ((SomeArgs) msg.obj).arg1,
2058 (String[]) ((SomeArgs) msg.obj).arg2);
2059 break;
Andrii Kulian446e8242017-10-26 15:17:29 -07002060 case EXECUTE_TRANSACTION:
Andrii Kulian04470682018-01-10 15:32:31 -08002061 final ClientTransaction transaction = (ClientTransaction) msg.obj;
2062 mTransactionExecutor.execute(transaction);
2063 if (isSystem()) {
2064 // Client transactions inside system process are recycled on the client side
2065 // instead of ClientLifecycleManager to avoid being cleared before this
2066 // message is handled.
2067 transaction.recycle();
2068 }
Andrii Kulian914aa7d2018-03-19 21:51:53 -07002069 // TODO(lifecycler): Recycle locally scheduled transactions.
Andrii Kulian446e8242017-10-26 15:17:29 -07002070 break;
Andrii Kulian320e3b52018-05-03 16:26:25 -07002071 case RELAUNCH_ACTIVITY:
2072 handleRelaunchActivityLocally((IBinder) msg.obj);
2073 break;
Tim Murray59f3dc12018-10-22 15:26:08 -07002074 case PURGE_RESOURCES:
2075 schedulePurgeIdler();
2076 break;
Alex Light2d0691c2019-10-03 14:36:57 -07002077 case ATTACH_STARTUP_AGENTS:
2078 handleAttachStartupAgents((String) msg.obj);
2079 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 }
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07002081 Object obj = msg.obj;
2082 if (obj instanceof SomeArgs) {
2083 ((SomeArgs) obj).recycle();
2084 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07002085 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 }
2087 }
2088
Romain Guy65b345f2011-07-27 18:51:50 -07002089 private class Idler implements MessageQueue.IdleHandler {
Craig Mautner48d0d182013-06-11 07:53:06 -07002090 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002092 ActivityClientRecord a = mNewActivities;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002093 boolean stopProfiling = false;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002094 if (mBoundApplication != null && mProfiler.profileFd != null
2095 && mProfiler.autoStopProfiler) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002096 stopProfiling = true;
2097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098 if (a != null) {
2099 mNewActivities = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002100 IActivityTaskManager am = ActivityTaskManager.getService();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002101 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002103 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 TAG, "Reporting idle of " + a +
2105 " finished=" +
Romain Guy65b345f2011-07-27 18:51:50 -07002106 (a.activity != null && a.activity.mFinished));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 if (a.activity != null && !a.activity.mFinished) {
2108 try {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002109 am.activityIdle(a.token, a.createdConfig, stopProfiling);
Dianne Hackborne88846e2009-09-30 21:34:25 -07002110 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002112 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 }
2114 }
2115 prev = a;
2116 a = a.nextIdle;
2117 prev.nextIdle = null;
2118 } while (a != null);
2119 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002120 if (stopProfiling) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002121 mProfiler.stopProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002122 }
Riddle Hsu50e34002019-04-12 20:42:05 +08002123 applyPendingProcessState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 return false;
2125 }
2126 }
2127
2128 final class GcIdler implements MessageQueue.IdleHandler {
Craig Mautner48d0d182013-06-11 07:53:06 -07002129 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 public final boolean queueIdle() {
2131 doGcIfNeeded();
Makoto Onuki0a9ee1a2019-06-19 08:58:02 -07002132 purgePendingResources();
Tim Murray59f3dc12018-10-22 15:26:08 -07002133 return false;
2134 }
2135 }
2136
2137 final class PurgeIdler implements MessageQueue.IdleHandler {
2138 @Override
2139 public boolean queueIdle() {
Makoto Onuki0a9ee1a2019-06-19 08:58:02 -07002140 purgePendingResources();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 return false;
2142 }
2143 }
2144
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002145 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07002146 public static ActivityThread currentActivityThread() {
Jeff Sharkey66a017b2013-01-17 18:18:22 -08002147 return sCurrentActivityThread;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149
Wale Ogunwale9a6ef1e2015-06-02 13:41:00 -07002150 public static boolean isSystem() {
2151 return (sCurrentActivityThread != null) ? sCurrentActivityThread.mSystemThread : false;
2152 }
2153
Svetoslavfbf0eca2015-05-01 16:52:41 -07002154 public static String currentOpPackageName() {
2155 ActivityThread am = currentActivityThread();
2156 return (am != null && am.getApplication() != null)
2157 ? am.getApplication().getOpPackageName() : null;
2158 }
2159
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002160 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07002161 public static String currentPackageName() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002162 ActivityThread am = currentActivityThread();
2163 return (am != null && am.mBoundApplication != null)
Dianne Hackbornb57a50b2013-04-11 17:29:32 -07002164 ? am.mBoundApplication.appInfo.packageName : null;
2165 }
2166
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002167 @UnsupportedAppUsage
Dianne Hackbornb57a50b2013-04-11 17:29:32 -07002168 public static String currentProcessName() {
2169 ActivityThread am = currentActivityThread();
2170 return (am != null && am.mBoundApplication != null)
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002171 ? am.mBoundApplication.processName : null;
2172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002174 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07002175 public static Application currentApplication() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002176 ActivityThread am = currentActivityThread();
2177 return am != null ? am.mInitialApplication : null;
2178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002180 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002181 public static IPackageManager getPackageManager() {
2182 if (sPackageManager != null) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002183 return sPackageManager;
2184 }
Todd Kennedy8f135982019-07-02 07:35:15 -07002185 final IBinder b = ServiceManager.getService("package");
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002186 sPackageManager = IPackageManager.Stub.asInterface(b);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002187 return sPackageManager;
2188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189
Todd Kennedy8f135982019-07-02 07:35:15 -07002190 /** Returns the permission manager */
2191 public static IPermissionManager getPermissionManager() {
2192 if (sPermissionManager != null) {
2193 return sPermissionManager;
2194 }
2195 final IBinder b = ServiceManager.getService("permissionmgr");
2196 sPermissionManager = IPermissionManager.Stub.asInterface(b);
2197 return sPermissionManager;
2198 }
2199
Romain Guy65b345f2011-07-27 18:51:50 -07002200 private Configuration mMainThreadConfig = new Configuration();
Amith Yamasani4f128e42016-05-10 11:44:12 -07002201
Dianne Hackborn908aecc2012-07-31 16:37:34 -07002202 Configuration applyConfigCompatMainThread(int displayDensity, Configuration config,
2203 CompatibilityInfo compat) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002204 if (config == null) {
2205 return null;
2206 }
Craig Mautner48d0d182013-06-11 07:53:06 -07002207 if (!compat.supportsScreen()) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002208 mMainThreadConfig.setTo(config);
2209 config = mMainThreadConfig;
Dianne Hackborn908aecc2012-07-31 16:37:34 -07002210 compat.applyToConfiguration(displayDensity, config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002211 }
2212 return config;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002215 /**
Todd Kennedy39bfee52016-02-24 10:28:21 -08002216 * Creates the top level resources for the given package. Will return an existing
2217 * Resources if one has already been created.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002218 */
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07002219 Resources getTopLevelResources(String resDir, String[] splitResDirs, String[] overlayDirs,
Adam Lesinski082614c2016-03-04 14:33:47 -08002220 String[] libDirs, int displayId, LoadedApk pkgInfo) {
2221 return mResourcesManager.getResources(null, resDir, splitResDirs, overlayDirs, libDirs,
Ryan Mitchell4579c0a2020-01-08 16:29:11 -08002222 displayId, null, pkgInfo.getCompatibilityInfo(), pkgInfo.getClassLoader(), null);
Todd Kennedy39bfee52016-02-24 10:28:21 -08002223 }
2224
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002225 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002226 final Handler getHandler() {
2227 return mH;
2228 }
2229
Mathew Inwood8c854f82018-09-14 12:35:36 +01002230 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Todd Kennedy233a0b12018-01-29 20:30:24 +00002231 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
2232 int flags) {
2233 return getPackageInfo(packageName, compatInfo, flags, UserHandle.myUserId());
Amith Yamasani98edc952012-09-25 14:09:27 -07002234 }
2235
Todd Kennedy233a0b12018-01-29 20:30:24 +00002236 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
2237 int flags, int userId) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002238 final boolean differentUser = (UserHandle.myUserId() != userId);
Daniel Colascionea46b7b32020-01-24 13:30:25 -08002239 ApplicationInfo ai = PackageManager.getApplicationInfoAsUserCached(
2240 packageName,
2241 PackageManager.GET_SHARED_LIBRARY_FILES
2242 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2243 (userId < 0) ? UserHandle.myUserId() : userId);
Craig Mautner88c05892013-06-28 09:47:45 -07002244 synchronized (mResourcesManager) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002245 WeakReference<LoadedApk> ref;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002246 if (differentUser) {
2247 // Caching not supported across users
2248 ref = null;
2249 } else if ((flags & Context.CONTEXT_INCLUDE_CODE) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 ref = mPackages.get(packageName);
2251 } else {
2252 ref = mResourcePackages.get(packageName);
2253 }
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002254
Todd Kennedy233a0b12018-01-29 20:30:24 +00002255 LoadedApk packageInfo = ref != null ? ref.get() : null;
Winson71cf3502019-04-09 18:00:08 -07002256 if (ai != null && packageInfo != null) {
2257 if (!isLoadedApkResourceDirsUpToDate(packageInfo, ai)) {
Winsonf8be8e52020-04-21 11:57:10 -07002258 List<String> oldPaths = new ArrayList<>();
2259 LoadedApk.makePaths(this, ai, oldPaths);
2260 packageInfo.updateApplicationInfo(ai, oldPaths);
Winson71cf3502019-04-09 18:00:08 -07002261 }
2262
Todd Kennedy233a0b12018-01-29 20:30:24 +00002263 if (packageInfo.isSecurityViolation()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002264 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
2265 throw new SecurityException(
2266 "Requesting code from " + packageName
2267 + " to be run in process "
2268 + mBoundApplication.processName
2269 + "/" + mBoundApplication.appInfo.uid);
2270 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00002271 return packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272 }
2273 }
2274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 if (ai != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002276 return getPackageInfo(ai, compatInfo, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002277 }
2278
2279 return null;
2280 }
2281
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002282 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +00002283 public final LoadedApk getPackageInfo(ApplicationInfo ai, CompatibilityInfo compatInfo,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002284 int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
2286 boolean securityViolation = includeCode && ai.uid != 0
2287 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002288 ? !UserHandle.isSameApp(ai.uid, mBoundApplication.appInfo.uid)
Amith Yamasani742a6712011-05-04 14:49:28 -07002289 : true);
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002290 boolean registerPackage = includeCode && (flags&Context.CONTEXT_REGISTER_PACKAGE) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291 if ((flags&(Context.CONTEXT_INCLUDE_CODE
2292 |Context.CONTEXT_IGNORE_SECURITY))
2293 == Context.CONTEXT_INCLUDE_CODE) {
2294 if (securityViolation) {
2295 String msg = "Requesting code from " + ai.packageName
2296 + " (with uid " + ai.uid + ")";
2297 if (mBoundApplication != null) {
2298 msg = msg + " to be run in process "
2299 + mBoundApplication.processName + " (with uid "
2300 + mBoundApplication.appInfo.uid + ")";
2301 }
2302 throw new SecurityException(msg);
2303 }
2304 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00002305 return getPackageInfo(ai, compatInfo, null, securityViolation, includeCode,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002306 registerPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002307 }
2308
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002309 @Override
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002310 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +00002311 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002312 CompatibilityInfo compatInfo) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002313 return getPackageInfo(ai, compatInfo, null, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314 }
2315
Mathew Inwood8c854f82018-09-14 12:35:36 +01002316 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Todd Kennedy233a0b12018-01-29 20:30:24 +00002317 public final LoadedApk peekPackageInfo(String packageName, boolean includeCode) {
Craig Mautner88c05892013-06-28 09:47:45 -07002318 synchronized (mResourcesManager) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002319 WeakReference<LoadedApk> ref;
2320 if (includeCode) {
2321 ref = mPackages.get(packageName);
2322 } else {
2323 ref = mResourcePackages.get(packageName);
2324 }
2325 return ref != null ? ref.get() : null;
2326 }
2327 }
2328
Todd Kennedy233a0b12018-01-29 20:30:24 +00002329 private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002330 ClassLoader baseLoader, boolean securityViolation, boolean includeCode,
2331 boolean registerPackage) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002332 final boolean differentUser = (UserHandle.myUserId() != UserHandle.getUserId(aInfo.uid));
Craig Mautner88c05892013-06-28 09:47:45 -07002333 synchronized (mResourcesManager) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002334 WeakReference<LoadedApk> ref;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002335 if (differentUser) {
2336 // Caching not supported across users
2337 ref = null;
2338 } else if (includeCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 ref = mPackages.get(aInfo.packageName);
2340 } else {
2341 ref = mResourcePackages.get(aInfo.packageName);
2342 }
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002343
Todd Kennedy233a0b12018-01-29 20:30:24 +00002344 LoadedApk packageInfo = ref != null ? ref.get() : null;
Winson83708c82019-02-19 12:34:17 -08002345
Winson71cf3502019-04-09 18:00:08 -07002346 if (packageInfo != null) {
2347 if (!isLoadedApkResourceDirsUpToDate(packageInfo, aInfo)) {
Winsonf8be8e52020-04-21 11:57:10 -07002348 List<String> oldPaths = new ArrayList<>();
2349 LoadedApk.makePaths(this, aInfo, oldPaths);
2350 packageInfo.updateApplicationInfo(aInfo, oldPaths);
Winson71cf3502019-04-09 18:00:08 -07002351 }
Winson83708c82019-02-19 12:34:17 -08002352
Winson83708c82019-02-19 12:34:17 -08002353 return packageInfo;
2354 }
2355
2356 if (localLOGV) {
2357 Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002358 : "Loading resource-only package ") + aInfo.packageName
2359 + " (in " + (mBoundApplication != null
Winson83708c82019-02-19 12:34:17 -08002360 ? mBoundApplication.processName : null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002362 }
Winson83708c82019-02-19 12:34:17 -08002363
2364 packageInfo =
2365 new LoadedApk(this, aInfo, compatInfo, baseLoader,
2366 securityViolation, includeCode
2367 && (aInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0, registerPackage);
2368
2369 if (mSystemThread && "android".equals(aInfo.packageName)) {
2370 packageInfo.installSystemApplicationInfo(aInfo,
2371 getSystemContext().mPackageInfo.getClassLoader());
2372 }
2373
2374 if (differentUser) {
2375 // Caching not supported across users
2376 } else if (includeCode) {
2377 mPackages.put(aInfo.packageName,
2378 new WeakReference<LoadedApk>(packageInfo));
2379 } else {
2380 mResourcePackages.put(aInfo.packageName,
2381 new WeakReference<LoadedApk>(packageInfo));
2382 }
2383
Todd Kennedy233a0b12018-01-29 20:30:24 +00002384 return packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 }
2386 }
2387
Winson71cf3502019-04-09 18:00:08 -07002388 private static boolean isLoadedApkResourceDirsUpToDate(LoadedApk loadedApk,
2389 ApplicationInfo appInfo) {
Winson83708c82019-02-19 12:34:17 -08002390 Resources packageResources = loadedApk.mResources;
2391 String[] overlayDirs = ArrayUtils.defeatNullable(loadedApk.getOverlayDirs());
2392 String[] resourceDirs = ArrayUtils.defeatNullable(appInfo.resourceDirs);
2393
2394 return (packageResources == null || packageResources.getAssets().isUpToDate())
2395 && overlayDirs.length == resourceDirs.length
2396 && ArrayUtils.containsAll(overlayDirs, resourceDirs);
2397 }
2398
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002399 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002400 ActivityThread() {
Craig Mautner88c05892013-06-28 09:47:45 -07002401 mResourcesManager = ResourcesManager.getInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402 }
2403
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002404 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002405 public ApplicationThread getApplicationThread()
2406 {
2407 return mAppThread;
2408 }
2409
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002410 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 public Instrumentation getInstrumentation()
2412 {
2413 return mInstrumentation;
2414 }
2415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002416 public boolean isProfiling() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002417 return mProfiler != null && mProfiler.profileFile != null
2418 && mProfiler.profileFd == null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002419 }
2420
2421 public String getProfileFilePath() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002422 return mProfiler.profileFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002423 }
2424
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002425 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002426 public Looper getLooper() {
2427 return mLooper;
2428 }
2429
Jeff Sharkey8439ac02017-12-12 17:26:23 -07002430 public Executor getExecutor() {
2431 return mExecutor;
2432 }
2433
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002434 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 public Application getApplication() {
2436 return mInitialApplication;
2437 }
Bob Leee5408332009-09-04 18:31:17 -07002438
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002439 @UnsupportedAppUsage
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07002440 public String getProcessName() {
2441 return mBoundApplication.processName;
2442 }
Bob Leee5408332009-09-04 18:31:17 -07002443
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002444 @UnsupportedAppUsage
Dianne Hackborn21556372010-02-04 16:34:40 -08002445 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 synchronized (this) {
2447 if (mSystemContext == null) {
Jeff Browndefd4a62014-03-10 21:24:37 -07002448 mSystemContext = ContextImpl.createSystemContext(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 }
Jeff Browndefd4a62014-03-10 21:24:37 -07002450 return mSystemContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002452 }
2453
Adam Lesinskia82b6262017-03-21 16:56:17 -07002454 public ContextImpl getSystemUiContext() {
2455 synchronized (this) {
2456 if (mSystemUiContext == null) {
Adam Lesinski6f1a9172017-04-10 16:35:19 -07002457 mSystemUiContext = ContextImpl.createSystemUiContext(getSystemContext());
Adam Lesinskia82b6262017-03-21 16:56:17 -07002458 }
2459 return mSystemUiContext;
2460 }
2461 }
2462
lumark0b05f9e2018-11-26 15:09:06 +08002463 /**
2464 * Create the context instance base on system resources & display information which used for UI.
2465 * @param displayId The ID of the display where the UI is shown.
2466 * @see ContextImpl#createSystemUiContext(ContextImpl, int)
2467 */
2468 public ContextImpl createSystemUiContext(int displayId) {
2469 return ContextImpl.createSystemUiContext(getSystemUiContext(), displayId);
2470 }
2471
Narayan Kamath29564cd2014-08-07 10:57:40 +01002472 public void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
Mike Cleron432b7132009-09-24 15:28:29 -07002473 synchronized (this) {
Narayan Kamath29564cd2014-08-07 10:57:40 +01002474 getSystemContext().installSystemApplicationInfo(info, classLoader);
Adam Lesinskia82b6262017-03-21 16:56:17 -07002475 getSystemUiContext().installSystemApplicationInfo(info, classLoader);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002476
2477 // give ourselves a default profiler
2478 mProfiler = new Profiler();
Mike Cleron432b7132009-09-24 15:28:29 -07002479 }
2480 }
2481
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002482 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002483 void scheduleGcIdler() {
2484 if (!mGcIdlerScheduled) {
2485 mGcIdlerScheduled = true;
2486 Looper.myQueue().addIdleHandler(mGcIdler);
2487 }
2488 mH.removeMessages(H.GC_WHEN_IDLE);
2489 }
2490
2491 void unscheduleGcIdler() {
2492 if (mGcIdlerScheduled) {
2493 mGcIdlerScheduled = false;
2494 Looper.myQueue().removeIdleHandler(mGcIdler);
2495 }
2496 mH.removeMessages(H.GC_WHEN_IDLE);
2497 }
2498
Tim Murray59f3dc12018-10-22 15:26:08 -07002499 void schedulePurgeIdler() {
2500 if (!mPurgeIdlerScheduled) {
2501 mPurgeIdlerScheduled = true;
2502 Looper.myQueue().addIdleHandler(mPurgeIdler);
2503 }
2504 mH.removeMessages(H.PURGE_RESOURCES);
2505 }
2506
2507 void unschedulePurgeIdler() {
2508 if (mPurgeIdlerScheduled) {
2509 mPurgeIdlerScheduled = false;
2510 Looper.myQueue().removeIdleHandler(mPurgeIdler);
2511 }
2512 mH.removeMessages(H.PURGE_RESOURCES);
2513 }
2514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 void doGcIfNeeded() {
Makoto Onuki0a9ee1a2019-06-19 08:58:02 -07002516 doGcIfNeeded("bg");
2517 }
2518
2519 void doGcIfNeeded(String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 mGcIdlerScheduled = false;
2521 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002522 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 // + "m now=" + now);
2524 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002525 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
Makoto Onuki0a9ee1a2019-06-19 08:58:02 -07002526 BinderInternal.forceGc(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 }
2528 }
2529
Jing Jia736da82019-08-06 15:08:02 -07002530 private static final String HEAP_FULL_COLUMN =
2531 "%13s %8s %8s %8s %8s %8s %8s %8s %8s %8s %8s %8s";
2532 private static final String HEAP_COLUMN =
2533 "%13s %8s %8s %8s %8s %8s %8s %8s %8s";
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002534 private static final String ONE_COUNT_COLUMN = "%21s %8d";
2535 private static final String TWO_COUNT_COLUMNS = "%21s %8d %21s %8d";
Jing Jia736da82019-08-06 15:08:02 -07002536 private static final String THREE_COUNT_COLUMNS = "%21s %8d %21s %8s %21s %8d";
2537 private static final String TWO_COUNT_COLUMN_HEADER = "%21s %8s %21s %8s";
2538 private static final String ONE_ALT_COUNT_COLUMN = "%21s %8s %21s %8d";
Dianne Hackborne77187d2013-10-25 16:32:41 -07002539
2540 // Formatting for checkin service - update version if row format changes
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002541 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 4;
Dianne Hackborne77187d2013-10-25 16:32:41 -07002542
2543 static void printRow(PrintWriter pw, String format, Object...objs) {
2544 pw.println(String.format(format, objs));
2545 }
2546
2547 public static void dumpMemInfoTable(PrintWriter pw, Debug.MemoryInfo memInfo, boolean checkin,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002548 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
2549 int pid, String processName,
Dianne Hackborne77187d2013-10-25 16:32:41 -07002550 long nativeMax, long nativeAllocated, long nativeFree,
2551 long dalvikMax, long dalvikAllocated, long dalvikFree) {
2552
2553 // For checkin, we print one long comma-separated list of values
2554 if (checkin) {
2555 // NOTE: if you change anything significant below, also consider changing
2556 // ACTIVITY_THREAD_CHECKIN_VERSION.
2557
2558 // Header
2559 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
2560 pw.print(pid); pw.print(',');
2561 pw.print(processName); pw.print(',');
2562
2563 // Heap info - max
2564 pw.print(nativeMax); pw.print(',');
2565 pw.print(dalvikMax); pw.print(',');
2566 pw.print("N/A,");
2567 pw.print(nativeMax + dalvikMax); pw.print(',');
2568
2569 // Heap info - allocated
2570 pw.print(nativeAllocated); pw.print(',');
2571 pw.print(dalvikAllocated); pw.print(',');
2572 pw.print("N/A,");
2573 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
2574
2575 // Heap info - free
2576 pw.print(nativeFree); pw.print(',');
2577 pw.print(dalvikFree); pw.print(',');
2578 pw.print("N/A,");
2579 pw.print(nativeFree + dalvikFree); pw.print(',');
2580
2581 // Heap info - proportional set size
2582 pw.print(memInfo.nativePss); pw.print(',');
2583 pw.print(memInfo.dalvikPss); pw.print(',');
2584 pw.print(memInfo.otherPss); pw.print(',');
2585 pw.print(memInfo.getTotalPss()); pw.print(',');
2586
2587 // Heap info - swappable set size
2588 pw.print(memInfo.nativeSwappablePss); pw.print(',');
2589 pw.print(memInfo.dalvikSwappablePss); pw.print(',');
2590 pw.print(memInfo.otherSwappablePss); pw.print(',');
2591 pw.print(memInfo.getTotalSwappablePss()); pw.print(',');
2592
2593 // Heap info - shared dirty
2594 pw.print(memInfo.nativeSharedDirty); pw.print(',');
2595 pw.print(memInfo.dalvikSharedDirty); pw.print(',');
2596 pw.print(memInfo.otherSharedDirty); pw.print(',');
2597 pw.print(memInfo.getTotalSharedDirty()); pw.print(',');
2598
2599 // Heap info - shared clean
2600 pw.print(memInfo.nativeSharedClean); pw.print(',');
2601 pw.print(memInfo.dalvikSharedClean); pw.print(',');
2602 pw.print(memInfo.otherSharedClean); pw.print(',');
2603 pw.print(memInfo.getTotalSharedClean()); pw.print(',');
2604
2605 // Heap info - private Dirty
2606 pw.print(memInfo.nativePrivateDirty); pw.print(',');
2607 pw.print(memInfo.dalvikPrivateDirty); pw.print(',');
2608 pw.print(memInfo.otherPrivateDirty); pw.print(',');
2609 pw.print(memInfo.getTotalPrivateDirty()); pw.print(',');
2610
2611 // Heap info - private Clean
2612 pw.print(memInfo.nativePrivateClean); pw.print(',');
2613 pw.print(memInfo.dalvikPrivateClean); pw.print(',');
2614 pw.print(memInfo.otherPrivateClean); pw.print(',');
2615 pw.print(memInfo.getTotalPrivateClean()); pw.print(',');
2616
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002617 // Heap info - swapped out
2618 pw.print(memInfo.nativeSwappedOut); pw.print(',');
2619 pw.print(memInfo.dalvikSwappedOut); pw.print(',');
2620 pw.print(memInfo.otherSwappedOut); pw.print(',');
2621 pw.print(memInfo.getTotalSwappedOut()); pw.print(',');
2622
2623 // Heap info - swapped out pss
2624 if (memInfo.hasSwappedOutPss) {
2625 pw.print(memInfo.nativeSwappedOutPss); pw.print(',');
2626 pw.print(memInfo.dalvikSwappedOutPss); pw.print(',');
2627 pw.print(memInfo.otherSwappedOutPss); pw.print(',');
2628 pw.print(memInfo.getTotalSwappedOutPss()); pw.print(',');
2629 } else {
2630 pw.print("N/A,");
2631 pw.print("N/A,");
2632 pw.print("N/A,");
2633 pw.print("N/A,");
2634 }
2635
Dianne Hackborne77187d2013-10-25 16:32:41 -07002636 // Heap info - other areas
2637 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
2638 pw.print(Debug.MemoryInfo.getOtherLabel(i)); pw.print(',');
2639 pw.print(memInfo.getOtherPss(i)); pw.print(',');
2640 pw.print(memInfo.getOtherSwappablePss(i)); pw.print(',');
2641 pw.print(memInfo.getOtherSharedDirty(i)); pw.print(',');
2642 pw.print(memInfo.getOtherSharedClean(i)); pw.print(',');
2643 pw.print(memInfo.getOtherPrivateDirty(i)); pw.print(',');
2644 pw.print(memInfo.getOtherPrivateClean(i)); pw.print(',');
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002645 pw.print(memInfo.getOtherSwappedOut(i)); pw.print(',');
2646 if (memInfo.hasSwappedOutPss) {
2647 pw.print(memInfo.getOtherSwappedOutPss(i)); pw.print(',');
2648 } else {
2649 pw.print("N/A,");
2650 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002651 }
2652 return;
2653 }
2654
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002655 if (!dumpSummaryOnly) {
2656 if (dumpFullInfo) {
2657 printRow(pw, HEAP_FULL_COLUMN, "", "Pss", "Pss", "Shared", "Private",
Martijn Coenene0764852016-01-07 17:04:22 -08002658 "Shared", "Private", memInfo.hasSwappedOutPss ? "SwapPss" : "Swap",
Jing Jia736da82019-08-06 15:08:02 -07002659 "Rss", "Heap", "Heap", "Heap");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002660 printRow(pw, HEAP_FULL_COLUMN, "", "Total", "Clean", "Dirty", "Dirty",
Jing Jia736da82019-08-06 15:08:02 -07002661 "Clean", "Clean", "Dirty", "Total",
Martijn Coenene0764852016-01-07 17:04:22 -08002662 "Size", "Alloc", "Free");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002663 printRow(pw, HEAP_FULL_COLUMN, "", "------", "------", "------", "------",
Jing Jia736da82019-08-06 15:08:02 -07002664 "------", "------", "------", "------", "------", "------", "------");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002665 printRow(pw, HEAP_FULL_COLUMN, "Native Heap", memInfo.nativePss,
2666 memInfo.nativeSwappablePss, memInfo.nativeSharedDirty,
2667 memInfo.nativePrivateDirty, memInfo.nativeSharedClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002668 memInfo.nativePrivateClean, memInfo.hasSwappedOutPss ?
Richard Uhler91702eb32017-06-23 16:54:25 +01002669 memInfo.nativeSwappedOutPss : memInfo.nativeSwappedOut,
Jing Jia736da82019-08-06 15:08:02 -07002670 memInfo.nativeRss, nativeMax, nativeAllocated, nativeFree);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002671 printRow(pw, HEAP_FULL_COLUMN, "Dalvik Heap", memInfo.dalvikPss,
2672 memInfo.dalvikSwappablePss, memInfo.dalvikSharedDirty,
2673 memInfo.dalvikPrivateDirty, memInfo.dalvikSharedClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002674 memInfo.dalvikPrivateClean, memInfo.hasSwappedOutPss ?
Richard Uhler91702eb32017-06-23 16:54:25 +01002675 memInfo.dalvikSwappedOutPss : memInfo.dalvikSwappedOut,
Jing Jia736da82019-08-06 15:08:02 -07002676 memInfo.dalvikRss, dalvikMax, dalvikAllocated, dalvikFree);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002677 } else {
2678 printRow(pw, HEAP_COLUMN, "", "Pss", "Private",
Martijn Coenene0764852016-01-07 17:04:22 -08002679 "Private", memInfo.hasSwappedOutPss ? "SwapPss" : "Swap",
Jing Jia736da82019-08-06 15:08:02 -07002680 "Rss", "Heap", "Heap", "Heap");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002681 printRow(pw, HEAP_COLUMN, "", "Total", "Dirty",
Jing Jia736da82019-08-06 15:08:02 -07002682 "Clean", "Dirty", "Total", "Size", "Alloc", "Free");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002683 printRow(pw, HEAP_COLUMN, "", "------", "------", "------",
Jing Jia736da82019-08-06 15:08:02 -07002684 "------", "------", "------", "------", "------", "------");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002685 printRow(pw, HEAP_COLUMN, "Native Heap", memInfo.nativePss,
2686 memInfo.nativePrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002687 memInfo.nativePrivateClean,
2688 memInfo.hasSwappedOutPss ? memInfo.nativeSwappedOutPss :
Jing Jia736da82019-08-06 15:08:02 -07002689 memInfo.nativeSwappedOut, memInfo.nativeRss,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002690 nativeMax, nativeAllocated, nativeFree);
2691 printRow(pw, HEAP_COLUMN, "Dalvik Heap", memInfo.dalvikPss,
2692 memInfo.dalvikPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002693 memInfo.dalvikPrivateClean,
2694 memInfo.hasSwappedOutPss ? memInfo.dalvikSwappedOutPss :
Jing Jia736da82019-08-06 15:08:02 -07002695 memInfo.dalvikSwappedOut, memInfo.dalvikRss,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002696 dalvikMax, dalvikAllocated, dalvikFree);
Dianne Hackborne77187d2013-10-25 16:32:41 -07002697 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002698
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002699 int otherPss = memInfo.otherPss;
2700 int otherSwappablePss = memInfo.otherSwappablePss;
2701 int otherSharedDirty = memInfo.otherSharedDirty;
2702 int otherPrivateDirty = memInfo.otherPrivateDirty;
2703 int otherSharedClean = memInfo.otherSharedClean;
2704 int otherPrivateClean = memInfo.otherPrivateClean;
2705 int otherSwappedOut = memInfo.otherSwappedOut;
Martijn Coenene0764852016-01-07 17:04:22 -08002706 int otherSwappedOutPss = memInfo.otherSwappedOutPss;
Jing Jia736da82019-08-06 15:08:02 -07002707 int otherRss = memInfo.otherRss;
Dianne Hackborne77187d2013-10-25 16:32:41 -07002708
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002709 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
Dianne Hackborne77187d2013-10-25 16:32:41 -07002710 final int myPss = memInfo.getOtherPss(i);
2711 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2712 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2713 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2714 final int mySharedClean = memInfo.getOtherSharedClean(i);
2715 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2716 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
Martijn Coenene0764852016-01-07 17:04:22 -08002717 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Jing Jia736da82019-08-06 15:08:02 -07002718 final int myRss = memInfo.getOtherRss(i);
Dianne Hackborne77187d2013-10-25 16:32:41 -07002719 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
Jing Jia736da82019-08-06 15:08:02 -07002720 || mySharedClean != 0 || myPrivateClean != 0 || myRss != 0
Martijn Coenene0764852016-01-07 17:04:22 -08002721 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Dianne Hackborne77187d2013-10-25 16:32:41 -07002722 if (dumpFullInfo) {
2723 printRow(pw, HEAP_FULL_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2724 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002725 mySharedClean, myPrivateClean,
2726 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
Jing Jia736da82019-08-06 15:08:02 -07002727 myRss, "", "", "");
Dianne Hackborne77187d2013-10-25 16:32:41 -07002728 } else {
2729 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2730 myPss, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002731 myPrivateClean,
2732 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
Jing Jia736da82019-08-06 15:08:02 -07002733 myRss, "", "", "");
Dianne Hackborne77187d2013-10-25 16:32:41 -07002734 }
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002735 otherPss -= myPss;
2736 otherSwappablePss -= mySwappablePss;
2737 otherSharedDirty -= mySharedDirty;
2738 otherPrivateDirty -= myPrivateDirty;
2739 otherSharedClean -= mySharedClean;
2740 otherPrivateClean -= myPrivateClean;
2741 otherSwappedOut -= mySwappedOut;
Martijn Coenene0764852016-01-07 17:04:22 -08002742 otherSwappedOutPss -= mySwappedOutPss;
Jing Jia736da82019-08-06 15:08:02 -07002743 otherRss -= myRss;
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002744 }
2745 }
2746
2747 if (dumpFullInfo) {
2748 printRow(pw, HEAP_FULL_COLUMN, "Unknown", otherPss, otherSwappablePss,
2749 otherSharedDirty, otherPrivateDirty, otherSharedClean, otherPrivateClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002750 memInfo.hasSwappedOutPss ? otherSwappedOutPss : otherSwappedOut,
Jing Jia736da82019-08-06 15:08:02 -07002751 otherRss, "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002752 printRow(pw, HEAP_FULL_COLUMN, "TOTAL", memInfo.getTotalPss(),
2753 memInfo.getTotalSwappablePss(),
2754 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
2755 memInfo.getTotalSharedClean(), memInfo.getTotalPrivateClean(),
Thierry Strudel9b511602016-02-25 17:46:38 -08002756 memInfo.hasSwappedOutPss ? memInfo.getTotalSwappedOutPss() :
Jing Jia736da82019-08-06 15:08:02 -07002757 memInfo.getTotalSwappedOut(), memInfo.getTotalRss(),
Martijn Coenene0764852016-01-07 17:04:22 -08002758 nativeMax+dalvikMax, nativeAllocated+dalvikAllocated,
2759 nativeFree+dalvikFree);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002760 } else {
2761 printRow(pw, HEAP_COLUMN, "Unknown", otherPss,
Martijn Coenene0764852016-01-07 17:04:22 -08002762 otherPrivateDirty, otherPrivateClean,
2763 memInfo.hasSwappedOutPss ? otherSwappedOutPss : otherSwappedOut,
Jing Jia736da82019-08-06 15:08:02 -07002764 otherRss, "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002765 printRow(pw, HEAP_COLUMN, "TOTAL", memInfo.getTotalPss(),
2766 memInfo.getTotalPrivateDirty(),
2767 memInfo.getTotalPrivateClean(),
Martijn Coenene0764852016-01-07 17:04:22 -08002768 memInfo.hasSwappedOutPss ? memInfo.getTotalSwappedOutPss() :
Jing Jia736da82019-08-06 15:08:02 -07002769 memInfo.getTotalSwappedOut(), memInfo.getTotalPss(),
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002770 nativeMax+dalvikMax,
2771 nativeAllocated+dalvikAllocated, nativeFree+dalvikFree);
2772 }
2773
2774 if (dumpDalvik) {
2775 pw.println(" ");
2776 pw.println(" Dalvik Details");
2777
2778 for (int i=Debug.MemoryInfo.NUM_OTHER_STATS;
2779 i<Debug.MemoryInfo.NUM_OTHER_STATS + Debug.MemoryInfo.NUM_DVK_STATS; i++) {
2780 final int myPss = memInfo.getOtherPss(i);
2781 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2782 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2783 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2784 final int mySharedClean = memInfo.getOtherSharedClean(i);
2785 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2786 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
Martijn Coenene0764852016-01-07 17:04:22 -08002787 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Jing Jia736da82019-08-06 15:08:02 -07002788 final int myRss = memInfo.getOtherRss(i);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002789 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
Martijn Coenene0764852016-01-07 17:04:22 -08002790 || mySharedClean != 0 || myPrivateClean != 0
2791 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002792 if (dumpFullInfo) {
2793 printRow(pw, HEAP_FULL_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2794 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002795 mySharedClean, myPrivateClean,
2796 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
Jing Jia736da82019-08-06 15:08:02 -07002797 myRss, "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002798 } else {
2799 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2800 myPss, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002801 myPrivateClean,
2802 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
Jing Jia736da82019-08-06 15:08:02 -07002803 myRss, "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002804 }
2805 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002806 }
2807 }
2808 }
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002809
2810 pw.println(" ");
2811 pw.println(" App Summary");
Jing Jia736da82019-08-06 15:08:02 -07002812 printRow(pw, TWO_COUNT_COLUMN_HEADER, "", "Pss(KB)", "", "Rss(KB)");
2813 printRow(pw, TWO_COUNT_COLUMN_HEADER, "", "------", "", "------");
2814 printRow(pw, TWO_COUNT_COLUMNS,
2815 "Java Heap:", memInfo.getSummaryJavaHeap(), "", memInfo.getSummaryJavaHeapRss());
2816 printRow(pw, TWO_COUNT_COLUMNS,
2817 "Native Heap:", memInfo.getSummaryNativeHeap(), "",
2818 memInfo.getSummaryNativeHeapRss());
2819 printRow(pw, TWO_COUNT_COLUMNS,
2820 "Code:", memInfo.getSummaryCode(), "", memInfo.getSummaryCodeRss());
2821 printRow(pw, TWO_COUNT_COLUMNS,
2822 "Stack:", memInfo.getSummaryStack(), "", memInfo.getSummaryStackRss());
2823 printRow(pw, TWO_COUNT_COLUMNS,
2824 "Graphics:", memInfo.getSummaryGraphics(), "", memInfo.getSummaryGraphicsRss());
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002825 printRow(pw, ONE_COUNT_COLUMN,
Jing Jia736da82019-08-06 15:08:02 -07002826 "Private Other:", memInfo.getSummaryPrivateOther());
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002827 printRow(pw, ONE_COUNT_COLUMN,
Jing Jia736da82019-08-06 15:08:02 -07002828 "System:", memInfo.getSummarySystem());
2829 printRow(pw, ONE_ALT_COUNT_COLUMN,
2830 "Unknown:", "", "", memInfo.getSummaryUnknownRss());
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002831 pw.println(" ");
Martijn Coenene0764852016-01-07 17:04:22 -08002832 if (memInfo.hasSwappedOutPss) {
Jing Jia736da82019-08-06 15:08:02 -07002833 printRow(pw, THREE_COUNT_COLUMNS,
2834 "TOTAL PSS:", memInfo.getSummaryTotalPss(),
2835 "TOTAL RSS:", memInfo.getTotalRss(),
2836 "TOTAL SWAP PSS:", memInfo.getSummaryTotalSwapPss());
Martijn Coenene0764852016-01-07 17:04:22 -08002837 } else {
Jing Jia736da82019-08-06 15:08:02 -07002838 printRow(pw, THREE_COUNT_COLUMNS,
2839 "TOTAL PSS:", memInfo.getSummaryTotalPss(),
2840 "TOTAL RSS:", memInfo.getTotalRss(),
2841 "TOTAL SWAP (KB):", memInfo.getSummaryTotalSwap());
Martijn Coenene0764852016-01-07 17:04:22 -08002842 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002843 }
2844
Kweku Adams598e9a22017-11-02 17:12:20 -07002845 /**
2846 * Dump heap info to proto.
2847 *
2848 * @param hasSwappedOutPss determines whether to use dirtySwap or dirtySwapPss
2849 */
Kweku Adams983829f2017-12-06 14:53:50 -08002850 private static void dumpMemoryInfo(ProtoOutputStream proto, long fieldId, String name,
Kweku Adams598e9a22017-11-02 17:12:20 -07002851 int pss, int cleanPss, int sharedDirty, int privateDirty,
2852 int sharedClean, int privateClean,
Jing Jia736da82019-08-06 15:08:02 -07002853 boolean hasSwappedOutPss, int dirtySwap, int dirtySwapPss, int rss) {
Kweku Adams598e9a22017-11-02 17:12:20 -07002854 final long token = proto.start(fieldId);
2855
Yi Jin2b30f322018-02-20 15:41:47 -08002856 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.NAME, name);
2857 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.TOTAL_PSS_KB, pss);
2858 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.CLEAN_PSS_KB, cleanPss);
2859 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.SHARED_DIRTY_KB, sharedDirty);
2860 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.PRIVATE_DIRTY_KB, privateDirty);
2861 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.SHARED_CLEAN_KB, sharedClean);
2862 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.PRIVATE_CLEAN_KB, privateClean);
Kweku Adams598e9a22017-11-02 17:12:20 -07002863 if (hasSwappedOutPss) {
Yi Jin2b30f322018-02-20 15:41:47 -08002864 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.DIRTY_SWAP_PSS_KB, dirtySwapPss);
Kweku Adams598e9a22017-11-02 17:12:20 -07002865 } else {
Yi Jin2b30f322018-02-20 15:41:47 -08002866 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.DIRTY_SWAP_KB, dirtySwap);
Kweku Adams598e9a22017-11-02 17:12:20 -07002867 }
Jing Jia736da82019-08-06 15:08:02 -07002868 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.TOTAL_RSS_KB, rss);
Kweku Adams598e9a22017-11-02 17:12:20 -07002869
2870 proto.end(token);
2871 }
2872
2873 /**
2874 * Dump mem info data to proto.
2875 */
2876 public static void dumpMemInfoTable(ProtoOutputStream proto, Debug.MemoryInfo memInfo,
2877 boolean dumpDalvik, boolean dumpSummaryOnly,
2878 long nativeMax, long nativeAllocated, long nativeFree,
2879 long dalvikMax, long dalvikAllocated, long dalvikFree) {
2880
2881 if (!dumpSummaryOnly) {
Yi Jin2b30f322018-02-20 15:41:47 -08002882 final long nhToken = proto.start(MemInfoDumpProto.ProcessMemory.NATIVE_HEAP);
2883 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "Native Heap",
Kweku Adams598e9a22017-11-02 17:12:20 -07002884 memInfo.nativePss, memInfo.nativeSwappablePss, memInfo.nativeSharedDirty,
2885 memInfo.nativePrivateDirty, memInfo.nativeSharedClean,
2886 memInfo.nativePrivateClean, memInfo.hasSwappedOutPss,
Jing Jia736da82019-08-06 15:08:02 -07002887 memInfo.nativeSwappedOut, memInfo.nativeSwappedOutPss,
2888 memInfo.nativeRss);
Yi Jin2b30f322018-02-20 15:41:47 -08002889 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB, nativeMax);
2890 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB, nativeAllocated);
2891 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB, nativeFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002892 proto.end(nhToken);
2893
Yi Jin2b30f322018-02-20 15:41:47 -08002894 final long dvToken = proto.start(MemInfoDumpProto.ProcessMemory.DALVIK_HEAP);
2895 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "Dalvik Heap",
Kweku Adams598e9a22017-11-02 17:12:20 -07002896 memInfo.dalvikPss, memInfo.dalvikSwappablePss, memInfo.dalvikSharedDirty,
2897 memInfo.dalvikPrivateDirty, memInfo.dalvikSharedClean,
2898 memInfo.dalvikPrivateClean, memInfo.hasSwappedOutPss,
Jing Jia736da82019-08-06 15:08:02 -07002899 memInfo.dalvikSwappedOut, memInfo.dalvikSwappedOutPss,
2900 memInfo.dalvikRss);
Yi Jin2b30f322018-02-20 15:41:47 -08002901 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB, dalvikMax);
2902 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB, dalvikAllocated);
2903 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB, dalvikFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002904 proto.end(dvToken);
2905
2906 int otherPss = memInfo.otherPss;
2907 int otherSwappablePss = memInfo.otherSwappablePss;
2908 int otherSharedDirty = memInfo.otherSharedDirty;
2909 int otherPrivateDirty = memInfo.otherPrivateDirty;
2910 int otherSharedClean = memInfo.otherSharedClean;
2911 int otherPrivateClean = memInfo.otherPrivateClean;
2912 int otherSwappedOut = memInfo.otherSwappedOut;
2913 int otherSwappedOutPss = memInfo.otherSwappedOutPss;
Jing Jia736da82019-08-06 15:08:02 -07002914 int otherRss = memInfo.otherRss;
Kweku Adams598e9a22017-11-02 17:12:20 -07002915
2916 for (int i = 0; i < Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
2917 final int myPss = memInfo.getOtherPss(i);
2918 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2919 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2920 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2921 final int mySharedClean = memInfo.getOtherSharedClean(i);
2922 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2923 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
2924 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Jing Jia736da82019-08-06 15:08:02 -07002925 final int myRss = memInfo.getOtherRss(i);
Kweku Adams598e9a22017-11-02 17:12:20 -07002926 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
Jing Jia736da82019-08-06 15:08:02 -07002927 || mySharedClean != 0 || myPrivateClean != 0 || myRss != 0
Kweku Adams598e9a22017-11-02 17:12:20 -07002928 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Yi Jin2b30f322018-02-20 15:41:47 -08002929 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.OTHER_HEAPS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002930 Debug.MemoryInfo.getOtherLabel(i),
2931 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
2932 mySharedClean, myPrivateClean,
Jing Jia736da82019-08-06 15:08:02 -07002933 memInfo.hasSwappedOutPss, mySwappedOut, mySwappedOutPss, myRss);
Kweku Adams598e9a22017-11-02 17:12:20 -07002934
2935 otherPss -= myPss;
2936 otherSwappablePss -= mySwappablePss;
2937 otherSharedDirty -= mySharedDirty;
2938 otherPrivateDirty -= myPrivateDirty;
2939 otherSharedClean -= mySharedClean;
2940 otherPrivateClean -= myPrivateClean;
2941 otherSwappedOut -= mySwappedOut;
2942 otherSwappedOutPss -= mySwappedOutPss;
Jing Jia736da82019-08-06 15:08:02 -07002943 otherRss -= myRss;
Kweku Adams598e9a22017-11-02 17:12:20 -07002944 }
2945 }
2946
Yi Jin2b30f322018-02-20 15:41:47 -08002947 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.UNKNOWN_HEAP, "Unknown",
Kweku Adams598e9a22017-11-02 17:12:20 -07002948 otherPss, otherSwappablePss,
2949 otherSharedDirty, otherPrivateDirty, otherSharedClean, otherPrivateClean,
Jing Jia736da82019-08-06 15:08:02 -07002950 memInfo.hasSwappedOutPss, otherSwappedOut, otherSwappedOutPss, otherRss);
Yi Jin2b30f322018-02-20 15:41:47 -08002951 final long tToken = proto.start(MemInfoDumpProto.ProcessMemory.TOTAL_HEAP);
2952 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "TOTAL",
Kweku Adams598e9a22017-11-02 17:12:20 -07002953 memInfo.getTotalPss(), memInfo.getTotalSwappablePss(),
2954 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
2955 memInfo.getTotalSharedClean(), memInfo.getTotalPrivateClean(),
2956 memInfo.hasSwappedOutPss, memInfo.getTotalSwappedOut(),
Jing Jia736da82019-08-06 15:08:02 -07002957 memInfo.getTotalSwappedOutPss(), memInfo.getTotalRss());
Yi Jin2b30f322018-02-20 15:41:47 -08002958 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB,
2959 nativeMax + dalvikMax);
2960 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002961 nativeAllocated + dalvikAllocated);
Yi Jin2b30f322018-02-20 15:41:47 -08002962 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB,
2963 nativeFree + dalvikFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002964 proto.end(tToken);
2965
2966 if (dumpDalvik) {
2967 for (int i = Debug.MemoryInfo.NUM_OTHER_STATS;
2968 i < Debug.MemoryInfo.NUM_OTHER_STATS + Debug.MemoryInfo.NUM_DVK_STATS;
2969 i++) {
2970 final int myPss = memInfo.getOtherPss(i);
2971 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2972 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2973 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2974 final int mySharedClean = memInfo.getOtherSharedClean(i);
2975 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2976 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
2977 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Jing Jia736da82019-08-06 15:08:02 -07002978 final int myRss = memInfo.getOtherRss(i);
Kweku Adams598e9a22017-11-02 17:12:20 -07002979 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
2980 || mySharedClean != 0 || myPrivateClean != 0
2981 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Yi Jin2b30f322018-02-20 15:41:47 -08002982 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.DALVIK_DETAILS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002983 Debug.MemoryInfo.getOtherLabel(i),
2984 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
2985 mySharedClean, myPrivateClean,
Jing Jia736da82019-08-06 15:08:02 -07002986 memInfo.hasSwappedOutPss, mySwappedOut, mySwappedOutPss, myRss);
Kweku Adams598e9a22017-11-02 17:12:20 -07002987 }
2988 }
2989 }
2990 }
2991
Yi Jin2b30f322018-02-20 15:41:47 -08002992 final long asToken = proto.start(MemInfoDumpProto.ProcessMemory.APP_SUMMARY);
2993 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.JAVA_HEAP_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002994 memInfo.getSummaryJavaHeap());
Yi Jin2b30f322018-02-20 15:41:47 -08002995 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.NATIVE_HEAP_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002996 memInfo.getSummaryNativeHeap());
Yi Jin2b30f322018-02-20 15:41:47 -08002997 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.CODE_PSS_KB,
2998 memInfo.getSummaryCode());
2999 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.STACK_PSS_KB,
3000 memInfo.getSummaryStack());
3001 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.GRAPHICS_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07003002 memInfo.getSummaryGraphics());
Yi Jin2b30f322018-02-20 15:41:47 -08003003 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.PRIVATE_OTHER_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07003004 memInfo.getSummaryPrivateOther());
Yi Jin2b30f322018-02-20 15:41:47 -08003005 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.SYSTEM_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07003006 memInfo.getSummarySystem());
3007 if (memInfo.hasSwappedOutPss) {
Yi Jin2b30f322018-02-20 15:41:47 -08003008 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.TOTAL_SWAP_PSS,
Kweku Adams598e9a22017-11-02 17:12:20 -07003009 memInfo.getSummaryTotalSwapPss());
3010 } else {
Yi Jin2b30f322018-02-20 15:41:47 -08003011 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.TOTAL_SWAP_PSS,
Kweku Adams598e9a22017-11-02 17:12:20 -07003012 memInfo.getSummaryTotalSwap());
3013 }
Jing Jia736da82019-08-06 15:08:02 -07003014 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.JAVA_HEAP_RSS_KB,
3015 memInfo.getSummaryJavaHeapRss());
3016 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.NATIVE_HEAP_RSS_KB,
3017 memInfo.getSummaryNativeHeapRss());
3018 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.CODE_RSS_KB,
3019 memInfo.getSummaryCodeRss());
3020 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.STACK_RSS_KB,
3021 memInfo.getSummaryStackRss());
3022 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.GRAPHICS_RSS_KB,
3023 memInfo.getSummaryGraphicsRss());
3024 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.UNKNOWN_RSS_KB,
3025 memInfo.getSummaryUnknownRss());
3026
Kweku Adams598e9a22017-11-02 17:12:20 -07003027 proto.end(asToken);
3028 }
3029
Mathew Inwood61e8ae62018-08-14 14:17:44 +01003030 @UnsupportedAppUsage
Jeff Hamilton52d32032011-01-08 15:31:26 -06003031 public void registerOnActivityPausedListener(Activity activity,
3032 OnActivityPausedListener listener) {
3033 synchronized (mOnPauseListeners) {
3034 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
3035 if (list == null) {
3036 list = new ArrayList<OnActivityPausedListener>();
3037 mOnPauseListeners.put(activity, list);
3038 }
3039 list.add(listener);
3040 }
3041 }
3042
Mathew Inwood61e8ae62018-08-14 14:17:44 +01003043 @UnsupportedAppUsage
Jeff Hamiltonce3224c2011-01-17 11:05:03 -08003044 public void unregisterOnActivityPausedListener(Activity activity,
3045 OnActivityPausedListener listener) {
3046 synchronized (mOnPauseListeners) {
3047 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
3048 if (list != null) {
3049 list.remove(listener);
3050 }
3051 }
3052 }
3053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 public final ActivityInfo resolveActivityInfo(Intent intent) {
3055 ActivityInfo aInfo = intent.resolveActivityInfo(
3056 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
3057 if (aInfo == null) {
3058 // Throw an exception.
3059 Instrumentation.checkStartActivityResult(
Dianne Hackborna4972e92012-03-14 10:38:05 -07003060 ActivityManager.START_CLASS_NOT_FOUND, intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003061 }
3062 return aInfo;
3063 }
Bob Leee5408332009-09-04 18:31:17 -07003064
Mathew Inwood8c854f82018-09-14 12:35:36 +01003065 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003066 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003067 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Sunny Goyald40c3452019-03-20 12:46:55 -07003068 Activity.NonConfigurationInstances lastNonConfigurationInstances, IBinder assistToken) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003069 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 r.token = token;
Sunny Goyald40c3452019-03-20 12:46:55 -07003071 r.assistToken = assistToken;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003072 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 r.intent = intent;
3074 r.state = state;
3075 r.parent = parent;
3076 r.embeddedID = id;
3077 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003078 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003079 if (localLOGV) {
3080 ComponentName compname = intent.getComponent();
3081 String name;
3082 if (compname != null) {
3083 name = compname.toShortString();
3084 } else {
3085 name = "(Intent " + intent + ").getComponent() returned null";
3086 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003087 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 + ", comp=" + name
3089 + ", token=" + token);
3090 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003091 // TODO(lifecycler): Can't switch to use #handleLaunchActivity() because it will try to
3092 // call #reportSizeConfigurations(), but the server might not know anything about the
3093 // activity if it was launched from LocalAcvitivyManager.
Andrii Kulian770c4032018-05-02 18:40:59 -07003094 return performLaunchActivity(r, null /* customIntent */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003095 }
3096
Mathew Inwood61e8ae62018-08-14 14:17:44 +01003097 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 public final Activity getActivity(IBinder token) {
Andrii Kuliand56ed0c2018-06-14 12:22:18 -07003099 final ActivityClientRecord activityRecord = mActivities.get(token);
3100 return activityRecord != null ? activityRecord.activity : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003101 }
3102
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003103 @Override
3104 public ActivityClientRecord getActivityClient(IBinder token) {
3105 return mActivities.get(token);
3106 }
3107
Darryl L Johnson78d4e6d2020-04-24 16:37:28 -07003108 @VisibleForTesting(visibility = PACKAGE)
3109 public Configuration getConfiguration() {
3110 return mConfiguration;
3111 }
3112
Riddle Hsu50e34002019-04-12 20:42:05 +08003113 @Override
3114 public void updatePendingConfiguration(Configuration config) {
3115 synchronized (mResourcesManager) {
3116 if (mPendingConfiguration == null || mPendingConfiguration.isOtherSeqNewer(config)) {
3117 mPendingConfiguration = config;
3118 }
3119 }
3120 }
3121
3122 @Override
3123 public void updateProcessState(int processState, boolean fromIpc) {
3124 synchronized (mAppThread) {
3125 if (mLastProcessState == processState) {
3126 return;
3127 }
3128 mLastProcessState = processState;
3129 // Defer the top state for VM to avoid aggressive JIT compilation affecting activity
3130 // launch time.
3131 if (processState == ActivityManager.PROCESS_STATE_TOP
3132 && mNumLaunchingActivities.get() > 0) {
3133 mPendingProcessState = processState;
3134 mH.postDelayed(this::applyPendingProcessState, PENDING_TOP_PROCESS_STATE_TIMEOUT);
3135 } else {
3136 mPendingProcessState = PROCESS_STATE_UNKNOWN;
3137 updateVmProcessState(processState);
3138 }
3139 if (localLOGV) {
3140 Slog.i(TAG, "******************* PROCESS STATE CHANGED TO: " + processState
3141 + (fromIpc ? " (from ipc" : ""));
3142 }
3143 }
3144 }
3145
3146 /** Update VM state based on ActivityManager.PROCESS_STATE_* constants. */
3147 private void updateVmProcessState(int processState) {
3148 // TODO: Tune this since things like gmail sync are important background but not jank
3149 // perceptible.
3150 final int state = processState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
3151 ? VM_PROCESS_STATE_JANK_PERCEPTIBLE
3152 : VM_PROCESS_STATE_JANK_IMPERCEPTIBLE;
3153 VMRuntime.getRuntime().updateProcessState(state);
3154 }
3155
3156 private void applyPendingProcessState() {
3157 synchronized (mAppThread) {
3158 if (mPendingProcessState == PROCESS_STATE_UNKNOWN) {
3159 return;
3160 }
3161 final int pendingState = mPendingProcessState;
3162 mPendingProcessState = PROCESS_STATE_UNKNOWN;
3163 // Only apply the pending state if the last state doesn't change.
3164 if (pendingState == mLastProcessState) {
3165 updateVmProcessState(pendingState);
3166 }
3167 }
3168 }
3169
3170 @Override
3171 public void countLaunchingActivities(int num) {
3172 mNumLaunchingActivities.getAndAdd(num);
3173 }
3174
Mathew Inwood61e8ae62018-08-14 14:17:44 +01003175 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003176 public final void sendActivityResult(
3177 IBinder token, String id, int requestCode,
3178 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003179 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07003180 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003181 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3182 list.add(new ResultInfo(id, requestCode, resultCode, data));
Andrii Kulian9c5ea9c2017-12-07 09:31:01 -08003183 final ClientTransaction clientTransaction = ClientTransaction.obtain(mAppThread, token);
3184 clientTransaction.addCallback(ActivityResultItem.obtain(list));
Andrii Kulian446e8242017-10-26 15:17:29 -07003185 try {
3186 mAppThread.scheduleTransaction(clientTransaction);
3187 } catch (RemoteException e) {
3188 // Local scheduling
3189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 }
3191
Andrii Kulian914aa7d2018-03-19 21:51:53 -07003192 @Override
3193 TransactionExecutor getTransactionExecutor() {
3194 return mTransactionExecutor;
3195 }
3196
Andrii Kulian446e8242017-10-26 15:17:29 -07003197 void sendMessage(int what, Object obj) {
Jeff Brown9ef09972013-10-15 20:49:59 -07003198 sendMessage(what, obj, 0, 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 }
3200
Jeff Brown9ef09972013-10-15 20:49:59 -07003201 private void sendMessage(int what, Object obj, int arg1) {
3202 sendMessage(what, obj, arg1, 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003203 }
3204
Jeff Brown9ef09972013-10-15 20:49:59 -07003205 private void sendMessage(int what, Object obj, int arg1, int arg2) {
3206 sendMessage(what, obj, arg1, arg2, false);
3207 }
3208
3209 private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
Kweku Adams4af1b502019-05-23 16:23:48 -07003210 if (DEBUG_MESSAGES) {
3211 Slog.v(TAG,
3212 "SCHEDULE " + what + " " + mH.codeToString(what) + ": " + arg1 + " / " + obj);
3213 }
Jeff Brown9ef09972013-10-15 20:49:59 -07003214 Message msg = Message.obtain();
3215 msg.what = what;
3216 msg.obj = obj;
3217 msg.arg1 = arg1;
3218 msg.arg2 = arg2;
3219 if (async) {
3220 msg.setAsynchronous(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 }
Jeff Brown9ef09972013-10-15 20:49:59 -07003222 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 }
3224
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07003225 private void sendMessage(int what, Object obj, int arg1, int arg2, int seq) {
3226 if (DEBUG_MESSAGES) Slog.v(
3227 TAG, "SCHEDULE " + mH.codeToString(what) + " arg1=" + arg1 + " arg2=" + arg2 +
3228 "seq= " + seq);
3229 Message msg = Message.obtain();
3230 msg.what = what;
3231 SomeArgs args = SomeArgs.obtain();
3232 args.arg1 = obj;
3233 args.argi1 = arg1;
3234 args.argi2 = arg2;
3235 args.argi3 = seq;
3236 msg.obj = args;
3237 mH.sendMessage(msg);
3238 }
3239
Dianne Hackborn21556372010-02-04 16:34:40 -08003240 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003241 String what) {
3242 ContextCleanupInfo cci = new ContextCleanupInfo();
3243 cci.context = context;
3244 cci.who = who;
3245 cci.what = what;
Jeff Brown9ef09972013-10-15 20:49:59 -07003246 sendMessage(H.CLEAN_UP_CONTEXT, cci);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247 }
3248
Riddle Hsud490c572020-04-17 01:39:27 +08003249 @Override
3250 public void handleFixedRotationAdjustments(@NonNull IBinder token,
3251 @Nullable FixedRotationAdjustments fixedRotationAdjustments) {
3252 final Consumer<DisplayAdjustments> override = fixedRotationAdjustments != null
3253 ? displayAdjustments -> displayAdjustments.setFixedRotationAdjustments(
3254 fixedRotationAdjustments)
3255 : null;
3256 if (!mResourcesManager.overrideTokenDisplayAdjustments(token, override)) {
3257 // No resources are associated with the token.
3258 return;
3259 }
3260 if (mActivities.get(token) == null) {
3261 // Only apply the override to application for activity token because the appearance of
3262 // activity is usually more sensitive to the application resources.
3263 return;
3264 }
3265
3266 // Apply the last override to application resources for compatibility. Because the Resources
3267 // of Display can be from application, e.g.
3268 // applicationContext.getSystemService(DisplayManager.class).getDisplay(displayId)
3269 // and the deprecated usage:
3270 // applicationContext.getSystemService(WindowManager.class).getDefaultDisplay();
3271 final Consumer<DisplayAdjustments> appOverride;
3272 if (mActiveRotationAdjustments == null) {
3273 mActiveRotationAdjustments = new ArrayList<>(2);
3274 }
3275 if (override != null) {
3276 mActiveRotationAdjustments.add(Pair.create(token, override));
3277 appOverride = override;
3278 } else {
3279 mActiveRotationAdjustments.removeIf(adjustmentsPair -> adjustmentsPair.first == token);
3280 appOverride = mActiveRotationAdjustments.isEmpty()
3281 ? null
3282 : mActiveRotationAdjustments.get(mActiveRotationAdjustments.size() - 1).second;
3283 }
3284 mInitialApplication.getResources().overrideDisplayAdjustments(appOverride);
3285 }
3286
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003287 /** Core implementation of activity launch. */
Andrii Kulian770c4032018-05-02 18:40:59 -07003288 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 ActivityInfo aInfo = r.activityInfo;
Todd Kennedy233a0b12018-01-29 20:30:24 +00003290 if (r.packageInfo == null) {
3291 r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292 Context.CONTEXT_INCLUDE_CODE);
3293 }
Bob Leee5408332009-09-04 18:31:17 -07003294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295 ComponentName component = r.intent.getComponent();
3296 if (component == null) {
3297 component = r.intent.resolveActivity(
3298 mInitialApplication.getPackageManager());
3299 r.intent.setComponent(component);
3300 }
3301
3302 if (r.activityInfo.targetActivity != null) {
3303 component = new ComponentName(r.activityInfo.packageName,
3304 r.activityInfo.targetActivity);
3305 }
3306
Adam Lesinski4e862812016-11-21 16:02:24 -08003307 ContextImpl appContext = createBaseContextForActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 Activity activity = null;
3309 try {
Adam Lesinski4e862812016-11-21 16:02:24 -08003310 java.lang.ClassLoader cl = appContext.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04003311 activity = mInstrumentation.newActivity(
3312 cl, component.getClassName(), r.intent);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003313 StrictMode.incrementExpectedActivityCount(activity.getClass());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 r.intent.setExtrasClassLoader(cl);
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003315 r.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 if (r.state != null) {
3317 r.state.setClassLoader(cl);
3318 }
3319 } catch (Exception e) {
3320 if (!mInstrumentation.onException(activity, e)) {
3321 throw new RuntimeException(
3322 "Unable to instantiate activity " + component
3323 + ": " + e.toString(), e);
3324 }
3325 }
3326
3327 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00003328 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07003329
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003330 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
3331 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003332 TAG, r + ": app=" + app
3333 + ", appName=" + app.getPackageName()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003334 + ", pkg=" + r.packageInfo.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 + ", comp=" + r.intent.getComponent().toShortString()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003336 + ", dir=" + r.packageInfo.getAppDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337
3338 if (activity != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003339 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003340 Configuration config = new Configuration(mCompatConfiguration);
Andrii Kuliand0ad9382016-04-18 20:54:20 -07003341 if (r.overrideConfig != null) {
3342 config.updateFrom(r.overrideConfig);
3343 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003344 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003345 + r.activityInfo.name + " with config " + config);
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003346 Window window = null;
3347 if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
3348 window = r.mPendingRemoveWindow;
3349 r.mPendingRemoveWindow = null;
3350 r.mPendingRemoveWindowManager = null;
3351 }
Ryan Mitchell0cbfd2b2020-02-07 11:19:16 -08003352
3353 // Activity resources must be initialized with the same loaders as the
3354 // application context.
3355 appContext.getResources().addLoaders(
3356 app.getResources().getLoaders().toArray(new ResourcesLoader[0]));
3357
Adam Lesinski4e862812016-11-21 16:02:24 -08003358 appContext.setOuterContext(activity);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003359 activity.attach(appContext, this, getInstrumentation(), r.token,
3360 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Craig Mautner233ceee2014-05-09 17:05:11 -07003361 r.embeddedID, r.lastNonConfigurationInstances, config,
Sunny Goyald40c3452019-03-20 12:46:55 -07003362 r.referrer, r.voiceInteractor, window, r.configCallback,
3363 r.assistToken);
Bob Leee5408332009-09-04 18:31:17 -07003364
Andrii Kulian770c4032018-05-02 18:40:59 -07003365 if (customIntent != null) {
3366 activity.mIntent = customIntent;
3367 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003368 r.lastNonConfigurationInstances = null;
Sudheer Shanka84a48952017-03-08 18:19:01 -08003369 checkAndBlockForNetworkAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 activity.mStartedActivity = false;
3371 int theme = r.activityInfo.getThemeResource();
3372 if (theme != 0) {
3373 activity.setTheme(theme);
3374 }
3375
3376 activity.mCalled = false;
Craig Mautnera0026042014-04-23 11:45:37 -07003377 if (r.isPersistable()) {
3378 mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
3379 } else {
3380 mInstrumentation.callActivityOnCreate(activity, r.state);
3381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003382 if (!activity.mCalled) {
3383 throw new SuperNotCalledException(
3384 "Activity " + r.intent.getComponent().toShortString() +
3385 " did not call through to super.onCreate()");
3386 }
3387 r.activity = activity;
Hongwei Wang5711b8f2019-11-15 15:44:12 -08003388 mLastReportedWindowingMode.put(activity.getActivityToken(),
3389 config.windowConfiguration.getWindowingMode());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003390 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003391 r.setState(ON_CREATE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003392
Garfield Tan0443b372019-01-04 15:00:13 -08003393 // updatePendingActivityConfiguration() reads from mActivities to update
3394 // ActivityClientRecord which runs in a different thread. Protect modifications to
3395 // mActivities to avoid race.
3396 synchronized (mResourcesManager) {
3397 mActivities.put(r.token, r);
3398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003399
3400 } catch (SuperNotCalledException e) {
3401 throw e;
3402
3403 } catch (Exception e) {
3404 if (!mInstrumentation.onException(activity, e)) {
3405 throw new RuntimeException(
3406 "Unable to start activity " + component
3407 + ": " + e.toString(), e);
3408 }
3409 }
3410
3411 return activity;
3412 }
3413
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003414 @Override
Andrii Kulianb9faa032019-10-17 23:11:54 -07003415 public void handleStartActivity(IBinder token, PendingTransactionActions pendingActions) {
3416 final ActivityClientRecord r = mActivities.get(token);
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003417 final Activity activity = r.activity;
3418 if (r.activity == null) {
3419 // TODO(lifecycler): What do we do in this case?
3420 return;
3421 }
3422 if (!r.stopped) {
3423 throw new IllegalStateException("Can't start activity that is not stopped.");
3424 }
Andrii Kulian0f3356c2019-03-18 21:34:40 +00003425 if (r.activity.mFinished) {
3426 // TODO(lifecycler): How can this happen?
3427 return;
3428 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003429
Andrii Kulianb9faa032019-10-17 23:11:54 -07003430 unscheduleGcIdler();
3431
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003432 // Start
Andrii Kuliand25680c2018-02-21 15:16:58 -08003433 activity.performStart("handleStartActivity");
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003434 r.setState(ON_START);
3435
3436 if (pendingActions == null) {
3437 // No more work to do.
3438 return;
3439 }
3440
3441 // Restore instance state
3442 if (pendingActions.shouldRestoreInstanceState()) {
3443 if (r.isPersistable()) {
3444 if (r.state != null || r.persistentState != null) {
3445 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
3446 r.persistentState);
3447 }
3448 } else if (r.state != null) {
3449 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
3450 }
3451 }
3452
3453 // Call postOnCreate()
3454 if (pendingActions.shouldCallOnPostCreate()) {
3455 activity.mCalled = false;
3456 if (r.isPersistable()) {
3457 mInstrumentation.callActivityOnPostCreate(activity, r.state,
3458 r.persistentState);
3459 } else {
3460 mInstrumentation.callActivityOnPostCreate(activity, r.state);
3461 }
3462 if (!activity.mCalled) {
3463 throw new SuperNotCalledException(
3464 "Activity " + r.intent.getComponent().toShortString()
3465 + " did not call through to super.onPostCreate()");
3466 }
3467 }
Andrii Kulianb9faa032019-10-17 23:11:54 -07003468
3469 updateVisibility(r, true /* show */);
3470 mSomeActivitiesChanged = true;
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003471 }
3472
Sudheer Shanka84a48952017-03-08 18:19:01 -08003473 /**
3474 * Checks if {@link #mNetworkBlockSeq} is {@link #INVALID_PROC_STATE_SEQ} and if so, returns
3475 * immediately. Otherwise, makes a blocking call to ActivityManagerService to wait for the
3476 * network rules to get updated.
3477 */
3478 private void checkAndBlockForNetworkAccess() {
3479 synchronized (mNetworkPolicyLock) {
3480 if (mNetworkBlockSeq != INVALID_PROC_STATE_SEQ) {
3481 try {
3482 ActivityManager.getService().waitForNetworkStateUpdate(mNetworkBlockSeq);
3483 mNetworkBlockSeq = INVALID_PROC_STATE_SEQ;
3484 } catch (RemoteException ignored) {}
3485 }
3486 }
3487 }
3488
Adam Lesinski4e862812016-11-21 16:02:24 -08003489 private ContextImpl createBaseContextForActivity(ActivityClientRecord r) {
3490 final int displayId;
Craig Mautnere0a38842013-12-16 16:14:02 -08003491 try {
Louis Chang677921f2019-12-06 16:44:24 +08003492 displayId = ActivityTaskManager.getService().getDisplayId(r.token);
Craig Mautnere0a38842013-12-16 16:14:02 -08003493 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003494 throw e.rethrowFromSystemServer();
Craig Mautnere0a38842013-12-16 16:14:02 -08003495 }
Jeff Brownefd43bd2012-09-21 17:02:35 -07003496
Wale Ogunwale7c726682015-02-06 17:34:28 -08003497 ContextImpl appContext = ContextImpl.createActivityContext(
Todd Kennedy233a0b12018-01-29 20:30:24 +00003498 this, r.packageInfo, r.activityInfo, r.token, displayId, r.overrideConfig);
Wale Ogunwale7c726682015-02-06 17:34:28 -08003499
Riddle Hsud490c572020-04-17 01:39:27 +08003500 // The rotation adjustments must be applied before creating the activity, so the activity
3501 // can get the adjusted display info during creation.
3502 if (r.mPendingFixedRotationAdjustments != null) {
3503 handleFixedRotationAdjustments(r.token, r.mPendingFixedRotationAdjustments);
3504 r.mPendingFixedRotationAdjustments = null;
3505 }
3506
Wale Ogunwale7c726682015-02-06 17:34:28 -08003507 final DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance();
Jeff Brownefd43bd2012-09-21 17:02:35 -07003508 // For debugging purposes, if the activity's package name contains the value of
3509 // the "debug.use-second-display" system property as a substring, then show
3510 // its content on a secondary display if there is one.
Jeff Brownefd43bd2012-09-21 17:02:35 -07003511 String pkgName = SystemProperties.get("debug.second-display.pkg");
3512 if (pkgName != null && !pkgName.isEmpty()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003513 && r.packageInfo.mPackageName.contains(pkgName)) {
Wale Ogunwale7c726682015-02-06 17:34:28 -08003514 for (int id : dm.getDisplayIds()) {
3515 if (id != Display.DEFAULT_DISPLAY) {
Wale Ogunwale26698512015-06-05 16:55:33 -07003516 Display display =
Bryce Lee609bf652017-02-09 16:50:13 -08003517 dm.getCompatibleDisplay(id, appContext.getResources());
Adam Lesinski4e862812016-11-21 16:02:24 -08003518 appContext = (ContextImpl) appContext.createDisplayContext(display);
Jeff Brownefd43bd2012-09-21 17:02:35 -07003519 break;
3520 }
3521 }
3522 }
Adam Lesinski4e862812016-11-21 16:02:24 -08003523 return appContext;
Jeff Brownefd43bd2012-09-21 17:02:35 -07003524 }
3525
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003526 /**
3527 * Extended implementation of activity launch. Used when server requests a launch or relaunch.
3528 */
Andrii Kulian446e8242017-10-26 15:17:29 -07003529 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003530 public Activity handleLaunchActivity(ActivityClientRecord r,
Andrii Kulian770c4032018-05-02 18:40:59 -07003531 PendingTransactionActions pendingActions, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532 // If we are getting ready to gc after going to the background, well
3533 // we are back active so skip it.
3534 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003535 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003536
Jeff Hao1b012d32014-08-20 10:35:34 -07003537 if (r.profilerInfo != null) {
3538 mProfiler.setProfiler(r.profilerInfo);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003539 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003540 }
3541
Dianne Hackborn58f42a52011-10-10 13:46:34 -07003542 // Make sure we are running with the most recent config.
3543 handleConfigurationChanged(null, null);
3544
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003545 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003546 TAG, "Handling launch of " + r);
Adam Powellcfbe9be2013-11-06 14:58:58 -08003547
Chet Haase0d1c27a2014-11-03 18:35:16 +00003548 // Initialize before creating the activity
Stan Iliev898123b2019-02-14 14:57:44 -05003549 if (!ThreadedRenderer.sRendererDisabled
3550 && (r.activityInfo.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
3551 HardwareRenderer.preload();
Jesse Hallc37984f2017-05-23 16:55:08 -07003552 }
Chet Haase0d1c27a2014-11-03 18:35:16 +00003553 WindowManagerGlobal.initialize();
3554
Yiwei Zhange54faf52019-05-08 18:43:11 -07003555 // Hint the GraphicsEnvironment that an activity is launching on the process.
3556 GraphicsEnvironment.hintActivityLaunch();
3557
Andrii Kulian770c4032018-05-02 18:40:59 -07003558 final Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003559
3560 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003561 r.createdConfig = new Configuration(mConfiguration);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003562 reportSizeConfigurations(r);
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003563 if (!r.activity.mFinished && pendingActions != null) {
3564 pendingActions.setOldState(r.state);
3565 pendingActions.setRestoreInstanceState(true);
3566 pendingActions.setCallOnPostCreate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 }
3568 } else {
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07003569 // 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 -08003570 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003571 ActivityTaskManager.getService()
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003572 .finishActivity(r.token, Activity.RESULT_CANCELED, null,
3573 Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003575 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003576 }
3577 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003578
3579 return a;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003580 }
3581
Filip Gruszczynski23493322015-07-29 17:02:59 -07003582 private void reportSizeConfigurations(ActivityClientRecord r) {
Riddle Hsu66b74a82018-07-26 00:20:12 +08003583 if (mActivitiesToBeDestroyed.containsKey(r.token)) {
3584 // Size configurations of a destroyed activity is meaningless.
3585 return;
3586 }
Filip Gruszczynski23493322015-07-29 17:02:59 -07003587 Configuration[] configurations = r.activity.getResources().getSizeConfigurations();
3588 if (configurations == null) {
3589 return;
3590 }
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003591 SparseIntArray horizontal = new SparseIntArray();
3592 SparseIntArray vertical = new SparseIntArray();
3593 SparseIntArray smallest = new SparseIntArray();
Filip Gruszczynski23493322015-07-29 17:02:59 -07003594 for (int i = configurations.length - 1; i >= 0; i--) {
3595 Configuration config = configurations[i];
3596 if (config.screenHeightDp != Configuration.SCREEN_HEIGHT_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003597 vertical.put(config.screenHeightDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003598 }
3599 if (config.screenWidthDp != Configuration.SCREEN_WIDTH_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003600 horizontal.put(config.screenWidthDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003601 }
3602 if (config.smallestScreenWidthDp != Configuration.SMALLEST_SCREEN_WIDTH_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003603 smallest.put(config.smallestScreenWidthDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003604 }
3605 }
Filip Gruszczynski23493322015-07-29 17:02:59 -07003606 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003607 ActivityTaskManager.getService().reportSizeConfigurations(r.token,
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003608 horizontal.copyKeys(), vertical.copyKeys(), smallest.copyKeys());
Filip Gruszczynski23493322015-07-29 17:02:59 -07003609 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003610 throw ex.rethrowFromSystemServer();
Filip Gruszczynski23493322015-07-29 17:02:59 -07003611 }
Filip Gruszczynski23493322015-07-29 17:02:59 -07003612 }
3613
Dianne Hackborn85d558c2014-11-04 10:31:54 -08003614 private void deliverNewIntents(ActivityClientRecord r, List<ReferrerIntent> intents) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003615 final int N = intents.size();
3616 for (int i=0; i<N; i++) {
Dianne Hackborna01a0fa2014-12-02 10:33:14 -08003617 ReferrerIntent intent = intents.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003618 intent.setExtrasClassLoader(r.activity.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003619 intent.prepareToEnterProcess();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003620 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003621 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
3622 }
3623 }
3624
Louis Chang92d16522019-02-27 12:56:18 +08003625 @Override
3626 public void handleNewIntent(IBinder token, List<ReferrerIntent> intents) {
Wale Ogunwale826c7062016-09-13 08:25:54 -07003627 final ActivityClientRecord r = mActivities.get(token);
3628 if (r == null) {
3629 return;
3630 }
3631
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07003632 checkAndBlockForNetworkAccess();
Wale Ogunwale826c7062016-09-13 08:25:54 -07003633 deliverNewIntents(r, intents);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003634 }
3635
Adam Skorydfc7fd72013-08-05 19:23:41 -07003636 public void handleRequestAssistContextExtras(RequestAssistContextExtras cmd) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003637 // Filling for autofill has a few differences:
Felipe Leme1ca634a2016-11-28 17:21:21 -08003638 // - it does not need an AssistContent
3639 // - it does not call onProvideAssistData()
3640 // - it needs an IAutoFillCallback
Felipe Leme640f30a2017-03-06 15:44:06 -08003641 boolean forAutofill = cmd.requestType == ActivityManager.ASSIST_CONTEXT_AUTOFILL;
Felipe Leme1ca634a2016-11-28 17:21:21 -08003642
Felipe Leme85d1c2d2017-04-21 08:56:04 -07003643 // TODO: decide if lastSessionId logic applies to autofill sessions
Amith Yamasani4f128e42016-05-10 11:44:12 -07003644 if (mLastSessionId != cmd.sessionId) {
3645 // Clear the existing structures
3646 mLastSessionId = cmd.sessionId;
3647 for (int i = mLastAssistStructures.size() - 1; i >= 0; i--) {
3648 AssistStructure structure = mLastAssistStructures.get(i).get();
3649 if (structure != null) {
3650 structure.clearSendChannel();
3651 }
3652 mLastAssistStructures.remove(i);
Dianne Hackborn782d4982015-07-08 17:36:37 -07003653 }
3654 }
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003655
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003656 Bundle data = new Bundle();
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003657 AssistStructure structure = null;
Felipe Leme640f30a2017-03-06 15:44:06 -08003658 AssistContent content = forAutofill ? null : new AssistContent();
Amith Yamasani858f98d2017-02-22 12:59:53 -08003659 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003660 ActivityClientRecord r = mActivities.get(cmd.activityToken);
Dianne Hackborna3acdb32015-06-08 17:07:40 -07003661 Uri referrer = null;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003662 if (r != null) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003663 if (!forAutofill) {
Felipe Leme1ca634a2016-11-28 17:21:21 -08003664 r.activity.getApplication().dispatchOnProvideAssistData(r.activity, data);
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003665 r.activity.onProvideAssistData(data);
Felipe Leme6d553872016-12-08 17:13:25 -08003666 referrer = r.activity.onProvideReferrer();
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003667 }
Felipe Leme640f30a2017-03-06 15:44:06 -08003668 if (cmd.requestType == ActivityManager.ASSIST_CONTEXT_FULL || forAutofill) {
Svet Ganovfd31f852017-04-26 15:54:27 -07003669 structure = new AssistStructure(r.activity, forAutofill, cmd.flags);
Adam Skory4aaed142015-04-22 11:29:31 -06003670 Intent activityIntent = r.activity.getIntent();
Felipe Leme6d553872016-12-08 17:13:25 -08003671 boolean notSecure = r.window == null ||
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003672 (r.window.getAttributes().flags
Felipe Leme6d553872016-12-08 17:13:25 -08003673 & WindowManager.LayoutParams.FLAG_SECURE) == 0;
3674 if (activityIntent != null && notSecure) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003675 if (!forAutofill) {
Felipe Leme1ca634a2016-11-28 17:21:21 -08003676 Intent intent = new Intent(activityIntent);
3677 intent.setFlags(intent.getFlags() & ~(Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3678 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION));
3679 intent.removeUnsafeExtras();
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003680 content.setDefaultIntent(intent);
3681 }
Adam Skory4aaed142015-04-22 11:29:31 -06003682 } else {
Felipe Leme640f30a2017-03-06 15:44:06 -08003683 if (!forAutofill) {
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003684 content.setDefaultIntent(new Intent());
3685 }
Adam Skory4aaed142015-04-22 11:29:31 -06003686 }
Felipe Leme640f30a2017-03-06 15:44:06 -08003687 if (!forAutofill) {
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003688 r.activity.onProvideAssistContent(content);
3689 }
Dianne Hackborna83ce1d2015-03-11 15:16:13 -07003690 }
Sunny Goyald40c3452019-03-20 12:46:55 -07003691
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003692 }
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003693 if (structure == null) {
3694 structure = new AssistStructure();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003695 }
Felipe Leme0200d9e2017-01-24 15:10:26 -08003696
Felipe Leme85d1c2d2017-04-21 08:56:04 -07003697 // TODO: decide if lastSessionId logic applies to autofill sessions
Amith Yamasani858f98d2017-02-22 12:59:53 -08003698
3699 structure.setAcquisitionStartTime(startTime);
3700 structure.setAcquisitionEndTime(SystemClock.uptimeMillis());
3701
Amith Yamasani4f128e42016-05-10 11:44:12 -07003702 mLastAssistStructures.add(new WeakReference<>(structure));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003703 IActivityTaskManager mgr = ActivityTaskManager.getService();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003704 try {
Dianne Hackborna3acdb32015-06-08 17:07:40 -07003705 mgr.reportAssistContextExtras(cmd.requestToken, data, structure, content, referrer);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003706 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003707 throw e.rethrowFromSystemServer();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003708 }
3709 }
Craig Mautner5eda9b32013-07-02 11:58:16 -07003710
Sunny Goyald40c3452019-03-20 12:46:55 -07003711 /** Fetches the user actions for the corresponding activity */
3712 private void handleRequestDirectActions(@NonNull IBinder activityToken,
Svet Ganov3b6be082019-04-28 10:21:01 -07003713 @NonNull IVoiceInteractor interactor, @NonNull CancellationSignal cancellationSignal,
3714 @NonNull RemoteCallback callback) {
Sunny Goyald40c3452019-03-20 12:46:55 -07003715 final ActivityClientRecord r = mActivities.get(activityToken);
Svet Ganov3b6be082019-04-28 10:21:01 -07003716 if (r == null) {
Felipe Lemeada51842019-05-14 15:19:52 -07003717 Log.w(TAG, "requestDirectActions(): no activity for " + activityToken);
Svet Ganov3b6be082019-04-28 10:21:01 -07003718 callback.sendResult(null);
3719 return;
3720 }
3721 final int lifecycleState = r.getLifecycleState();
3722 if (lifecycleState < ON_START || lifecycleState >= ON_STOP) {
Felipe Lemeada51842019-05-14 15:19:52 -07003723 Log.w(TAG, "requestDirectActions(" + r + "): wrong lifecycle: " + lifecycleState);
Svet Ganov3b6be082019-04-28 10:21:01 -07003724 callback.sendResult(null);
3725 return;
3726 }
3727 if (r.activity.mVoiceInteractor == null
3728 || r.activity.mVoiceInteractor.mInteractor.asBinder()
3729 != interactor.asBinder()) {
3730 if (r.activity.mVoiceInteractor != null) {
3731 r.activity.mVoiceInteractor.destroy();
Sunny Goyald40c3452019-03-20 12:46:55 -07003732 }
Svet Ganov3b6be082019-04-28 10:21:01 -07003733 r.activity.mVoiceInteractor = new VoiceInteractor(interactor, r.activity,
3734 r.activity, Looper.myLooper());
3735 }
3736 r.activity.onGetDirectActions(cancellationSignal, (actions) -> {
Daulet Zhanguzin0af97d62019-12-30 15:41:28 +00003737 Objects.requireNonNull(actions);
Sunny Goyald40c3452019-03-20 12:46:55 -07003738 Preconditions.checkCollectionElementsNotNull(actions, "actions");
Svet Ganov3b6be082019-04-28 10:21:01 -07003739 if (!actions.isEmpty()) {
Sunny Goyald40c3452019-03-20 12:46:55 -07003740 final int actionCount = actions.size();
3741 for (int i = 0; i < actionCount; i++) {
3742 final DirectAction action = actions.get(i);
3743 action.setSource(r.activity.getTaskId(), r.activity.getAssistToken());
3744 }
3745 final Bundle result = new Bundle();
3746 result.putParcelable(DirectAction.KEY_ACTIONS_LIST,
3747 new ParceledListSlice<>(actions));
3748 callback.sendResult(result);
Svet Ganov3b6be082019-04-28 10:21:01 -07003749 } else {
3750 callback.sendResult(null);
Sunny Goyald40c3452019-03-20 12:46:55 -07003751 }
Svet Ganov3b6be082019-04-28 10:21:01 -07003752 });
Sunny Goyald40c3452019-03-20 12:46:55 -07003753 }
3754
3755 /** Performs an actions in the corresponding activity */
3756 private void handlePerformDirectAction(@NonNull IBinder activityToken,
3757 @NonNull String actionId, @Nullable Bundle arguments,
3758 @NonNull CancellationSignal cancellationSignal,
3759 @NonNull RemoteCallback resultCallback) {
3760 final ActivityClientRecord r = mActivities.get(activityToken);
3761 if (r != null) {
3762 final int lifecycleState = r.getLifecycleState();
3763 if (lifecycleState < ON_START || lifecycleState >= ON_STOP) {
3764 resultCallback.sendResult(null);
3765 return;
3766 }
3767 final Bundle nonNullArguments = (arguments != null) ? arguments : Bundle.EMPTY;
Sunny Goyald40c3452019-03-20 12:46:55 -07003768 r.activity.onPerformDirectAction(actionId, nonNullArguments, cancellationSignal,
Svet Ganov3b6be082019-04-28 10:21:01 -07003769 resultCallback::sendResult);
3770 } else {
3771 resultCallback.sendResult(null);
Sunny Goyald40c3452019-03-20 12:46:55 -07003772 }
Sunny Goyald40c3452019-03-20 12:46:55 -07003773 }
3774
Craig Mautner5eda9b32013-07-02 11:58:16 -07003775 public void handleTranslucentConversionComplete(IBinder token, boolean drawComplete) {
3776 ActivityClientRecord r = mActivities.get(token);
3777 if (r != null) {
3778 r.activity.onTranslucentConversionComplete(drawComplete);
3779 }
3780 }
3781
Craig Mautnereb8abf72014-07-02 15:04:09 -07003782 public void onNewActivityOptions(IBinder token, ActivityOptions options) {
3783 ActivityClientRecord r = mActivities.get(token);
3784 if (r != null) {
3785 r.activity.onNewActivityOptions(options);
3786 }
3787 }
3788
Jeff Sharkeydd97f422013-10-08 17:01:30 -07003789 public void handleInstallProvider(ProviderInfo info) {
Jeff Sharkeybb2e2ca2014-10-23 11:42:31 -07003790 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3791 try {
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -06003792 installContentProviders(mInitialApplication, Arrays.asList(info));
Jeff Sharkeybb2e2ca2014-10-23 11:42:31 -07003793 } finally {
3794 StrictMode.setThreadPolicy(oldPolicy);
3795 }
Jeff Sharkeydd97f422013-10-08 17:01:30 -07003796 }
3797
Craig Mautner8746a472014-07-24 15:12:54 -07003798 private void handleEnterAnimationComplete(IBinder token) {
3799 ActivityClientRecord r = mActivities.get(token);
3800 if (r != null) {
Filip Gruszczynski6eafa902014-11-14 14:24:37 -08003801 r.activity.dispatchEnterAnimationComplete();
Craig Mautner8746a472014-07-24 15:12:54 -07003802 }
3803 }
3804
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04003805 private void handleStartBinderTracking() {
3806 Binder.enableTracing();
3807 }
3808
3809 private void handleStopBinderTrackingAndDump(ParcelFileDescriptor fd) {
3810 try {
3811 Binder.disableTracing();
3812 Binder.getTransactionTracker().writeTracesToFile(fd);
3813 } finally {
3814 IoUtils.closeQuietly(fd);
3815 Binder.getTransactionTracker().clearTraces();
3816 }
3817 }
3818
Andrii Kulian446e8242017-10-26 15:17:29 -07003819 @Override
jorgegil@google.com06bc3232019-10-31 14:51:22 -07003820 public void handlePictureInPictureRequested(IBinder token) {
3821 final ActivityClientRecord r = mActivities.get(token);
3822 if (r == null) {
3823 Log.w(TAG, "Activity to request PIP to no longer exists");
3824 return;
3825 }
3826
jorgegil@google.comb8ee18f2020-02-03 13:21:27 -08003827 final boolean receivedByApp = r.activity.onPictureInPictureRequested();
3828 if (!receivedByApp) {
3829 // Previous recommendation was for apps to enter picture-in-picture in
3830 // onUserLeavingHint() for cases such as the app being put into the background. For
3831 // backwards compatibility with apps that are not using the newer
3832 // onPictureInPictureRequested() callback, we schedule the life cycle events needed to
3833 // trigger onUserLeavingHint(), then we return the activity to its previous state.
3834 schedulePauseWithUserLeaveHintAndReturnToCurrentState(r);
3835 }
jorgegil@google.com06bc3232019-10-31 14:51:22 -07003836 }
3837
3838 /**
3839 * Cycle activity through onPause and onUserLeaveHint so that PIP is entered if supported, then
3840 * return to its previous state. This allows activities that rely on onUserLeaveHint instead of
3841 * onPictureInPictureRequested to enter picture-in-picture.
3842 */
jorgegil@google.comb8ee18f2020-02-03 13:21:27 -08003843 private void schedulePauseWithUserLeaveHintAndReturnToCurrentState(ActivityClientRecord r) {
jorgegil@google.com06bc3232019-10-31 14:51:22 -07003844 final int prevState = r.getLifecycleState();
3845 if (prevState != ON_RESUME && prevState != ON_PAUSE) {
3846 return;
3847 }
3848
3849 switch (prevState) {
3850 case ON_RESUME:
3851 // Schedule a PAUSE then return to RESUME.
3852 schedulePauseWithUserLeavingHint(r);
3853 scheduleResume(r);
3854 break;
3855 case ON_PAUSE:
3856 // Schedule a RESUME then return to PAUSE.
3857 scheduleResume(r);
3858 schedulePauseWithUserLeavingHint(r);
3859 break;
3860 }
3861 }
3862
3863 private void schedulePauseWithUserLeavingHint(ActivityClientRecord r) {
3864 final ClientTransaction transaction = ClientTransaction.obtain(this.mAppThread, r.token);
3865 transaction.setLifecycleStateRequest(PauseActivityItem.obtain(r.activity.isFinishing(),
3866 /* userLeaving */ true, r.activity.mConfigChangeFlags, /* dontReport */ false));
3867 executeTransaction(transaction);
3868 }
3869
3870 private void scheduleResume(ActivityClientRecord r) {
3871 final ClientTransaction transaction = ClientTransaction.obtain(this.mAppThread, r.token);
3872 transaction.setLifecycleStateRequest(ResumeActivityItem.obtain(/* isForward */ false));
3873 executeTransaction(transaction);
3874 }
3875
Amith Yamasani0af6fa72016-01-17 15:36:19 -08003876 private void handleLocalVoiceInteractionStarted(IBinder token, IVoiceInteractor interactor) {
3877 final ActivityClientRecord r = mActivities.get(token);
3878 if (r != null) {
3879 r.voiceInteractor = interactor;
3880 r.activity.setVoiceInteractor(interactor);
3881 if (interactor == null) {
3882 r.activity.onLocalVoiceInteractionStopped();
3883 } else {
3884 r.activity.onLocalVoiceInteractionStarted();
3885 }
3886 }
3887 }
3888
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003889 private static boolean attemptAttachAgent(String agent, ClassLoader classLoader) {
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003890 try {
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003891 VMDebug.attachAgent(agent, classLoader);
3892 return true;
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003893 } catch (IOException e) {
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003894 Slog.e(TAG, "Attaching agent with " + classLoader + " failed: " + agent);
3895 return false;
3896 }
3897 }
3898
3899 static void handleAttachAgent(String agent, LoadedApk loadedApk) {
3900 ClassLoader classLoader = loadedApk != null ? loadedApk.getClassLoader() : null;
3901 if (attemptAttachAgent(agent, classLoader)) {
3902 return;
3903 }
3904 if (classLoader != null) {
3905 attemptAttachAgent(agent, null);
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003906 }
3907 }
3908
Alex Light2d0691c2019-10-03 14:36:57 -07003909 static void handleAttachStartupAgents(String dataDir) {
3910 try {
3911 Path code_cache = ContextImpl.getCodeCacheDirBeforeBind(new File(dataDir)).toPath();
3912 if (!Files.exists(code_cache)) {
3913 return;
3914 }
3915 Path startup_path = code_cache.resolve("startup_agents");
3916 if (Files.exists(startup_path)) {
3917 for (Path p : Files.newDirectoryStream(startup_path)) {
3918 handleAttachAgent(
3919 p.toAbsolutePath().toString()
3920 + "="
3921 + dataDir,
3922 null);
3923 }
3924 }
3925 } catch (Exception e) {
3926 // Ignored.
3927 }
3928 }
3929
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003930 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
3931
3932 /**
3933 * Return the Intent that's currently being handled by a
3934 * BroadcastReceiver on this thread, or null if none.
3935 * @hide
3936 */
3937 public static Intent getIntentBeingBroadcast() {
3938 return sCurrentBroadcastIntent.get();
3939 }
3940
Mathew Inwood31755f92018-12-20 13:53:36 +00003941 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Romain Guy65b345f2011-07-27 18:51:50 -07003942 private void handleReceiver(ReceiverData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003943 // If we are getting ready to gc after going to the background, well
3944 // we are back active so skip it.
3945 unscheduleGcIdler();
3946
3947 String component = data.intent.getComponent().getClassName();
3948
Todd Kennedy233a0b12018-01-29 20:30:24 +00003949 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003950 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003951
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003952 IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003953
Adam Lesinski4e862812016-11-21 16:02:24 -08003954 Application app;
Romain Guy65b345f2011-07-27 18:51:50 -07003955 BroadcastReceiver receiver;
Adam Lesinski4e862812016-11-21 16:02:24 -08003956 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00003958 app = packageInfo.makeApplication(false, mInstrumentation);
Adam Lesinski4e862812016-11-21 16:02:24 -08003959 context = (ContextImpl) app.getBaseContext();
3960 if (data.info.splitName != null) {
3961 context = (ContextImpl) context.createContextForSplit(data.info.splitName);
3962 }
3963 java.lang.ClassLoader cl = context.getClassLoader();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964 data.intent.setExtrasClassLoader(cl);
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003965 data.intent.prepareToEnterProcess();
Dianne Hackborne829fef2010-10-26 17:44:01 -07003966 data.setExtrasClassLoader(cl);
Todd Kennedy233a0b12018-01-29 20:30:24 +00003967 receiver = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05003968 .instantiateReceiver(cl, data.info.name, data.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07003970 if (DEBUG_BROADCAST) Slog.i(TAG,
3971 "Finishing failed broadcast to " + data.intent.getComponent());
3972 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003973 throw new RuntimeException(
3974 "Unable to instantiate receiver " + component
3975 + ": " + e.toString(), e);
3976 }
3977
3978 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003979 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 TAG, "Performing receive of " + data.intent
3981 + ": app=" + app
3982 + ", appName=" + app.getPackageName()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003983 + ", pkg=" + packageInfo.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984 + ", comp=" + data.intent.getComponent().toShortString()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003985 + ", dir=" + packageInfo.getAppDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003987 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07003988 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003989 receiver.onReceive(context.getReceiverRestrictedContext(),
3990 data.intent);
3991 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07003992 if (DEBUG_BROADCAST) Slog.i(TAG,
3993 "Finishing failed broadcast to " + data.intent.getComponent());
3994 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003995 if (!mInstrumentation.onException(receiver, e)) {
3996 throw new RuntimeException(
3997 "Unable to start receiver " + component
3998 + ": " + e.toString(), e);
3999 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07004000 } finally {
4001 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004002 }
4003
Dianne Hackborne829fef2010-10-26 17:44:01 -07004004 if (receiver.getPendingResult() != null) {
4005 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 }
4007 }
4008
Christopher Tate181fafa2009-05-14 11:12:14 -07004009 // Instantiate a BackupAgent and tell it that it's alive
Romain Guy65b345f2011-07-27 18:51:50 -07004010 private void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004011 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07004012
Christopher Tate346acb12012-10-15 19:20:25 -07004013 // Sanity check the requested target package's uid against ours
4014 try {
4015 PackageInfo requestedPackage = getPackageManager().getPackageInfo(
4016 data.appInfo.packageName, 0, UserHandle.myUserId());
4017 if (requestedPackage.applicationInfo.uid != Process.myUid()) {
4018 Slog.w(TAG, "Asked to instantiate non-matching package "
4019 + data.appInfo.packageName);
4020 return;
4021 }
4022 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004023 throw e.rethrowFromSystemServer();
Christopher Tate346acb12012-10-15 19:20:25 -07004024 }
4025
Christopher Tate181fafa2009-05-14 11:12:14 -07004026 // no longer idle; we have backup work to do
4027 unscheduleGcIdler();
4028
4029 // instantiate the BackupAgent class named in the manifest
Todd Kennedy233a0b12018-01-29 20:30:24 +00004030 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
4031 String packageName = packageInfo.mPackageName;
Christopher Tate346acb12012-10-15 19:20:25 -07004032 if (packageName == null) {
4033 Slog.d(TAG, "Asked to create backup agent for nonexistent package");
4034 return;
4035 }
4036
Christopher Tate181fafa2009-05-14 11:12:14 -07004037 String classname = data.appInfo.backupAgentName;
Christopher Tate79ec80d2011-06-24 14:58:49 -07004038 // full backup operation but no app-supplied agent? use the default implementation
Sudheer Shankacc6418f2016-10-13 12:03:44 -07004039 if (classname == null && (data.backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL
4040 || data.backupMode == ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL)) {
Christopher Tate4a627c72011-04-01 14:43:32 -07004041 classname = "android.app.backup.FullBackupAgent";
Christopher Tate181fafa2009-05-14 11:12:14 -07004042 }
Christopher Tate4a627c72011-04-01 14:43:32 -07004043
Christopher Tate181fafa2009-05-14 11:12:14 -07004044 try {
Christopher Tated1475e02009-07-09 15:36:17 -07004045 IBinder binder = null;
Annie Mengd5827872019-01-30 20:28:57 +00004046 ArrayMap<String, BackupAgent> backupAgents = getBackupAgentsForUser(data.userId);
4047 BackupAgent agent = backupAgents.get(packageName);
Christopher Tate2e40d112014-07-15 12:37:38 -07004048 if (agent != null) {
4049 // reusing the existing instance
4050 if (DEBUG_BACKUP) {
4051 Slog.v(TAG, "Reusing existing agent instance");
Christopher Tated1475e02009-07-09 15:36:17 -07004052 }
Christopher Tate2e40d112014-07-15 12:37:38 -07004053 binder = agent.onBind();
4054 } else {
4055 try {
4056 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing agent class " + classname);
4057
Todd Kennedy233a0b12018-01-29 20:30:24 +00004058 java.lang.ClassLoader cl = packageInfo.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04004059 agent = (BackupAgent) cl.loadClass(classname).newInstance();
Christopher Tate2e40d112014-07-15 12:37:38 -07004060
4061 // set up the agent's context
Todd Kennedy233a0b12018-01-29 20:30:24 +00004062 ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
Christopher Tate2e40d112014-07-15 12:37:38 -07004063 context.setOuterContext(agent);
4064 agent.attach(context);
4065
Ruslan Tkhakokhov063180f2019-01-28 20:29:46 +00004066 agent.onCreate(UserHandle.of(data.userId));
Christopher Tate2e40d112014-07-15 12:37:38 -07004067 binder = agent.onBind();
Annie Mengd5827872019-01-30 20:28:57 +00004068 backupAgents.put(packageName, agent);
Christopher Tate2e40d112014-07-15 12:37:38 -07004069 } catch (Exception e) {
4070 // If this is during restore, fail silently; otherwise go
4071 // ahead and let the user see the crash.
4072 Slog.e(TAG, "Agent threw during creation: " + e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07004073 if (data.backupMode != ApplicationThreadConstants.BACKUP_MODE_RESTORE
4074 && data.backupMode !=
4075 ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL) {
Christopher Tate2e40d112014-07-15 12:37:38 -07004076 throw e;
4077 }
4078 // falling through with 'binder' still null
4079 }
Christopher Tated1475e02009-07-09 15:36:17 -07004080 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004081
4082 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07004083 try {
Annie Mengd5827872019-01-30 20:28:57 +00004084 ActivityManager.getService().backupAgentCreated(packageName, binder, data.userId);
Christopher Tate181fafa2009-05-14 11:12:14 -07004085 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004086 throw e.rethrowFromSystemServer();
Christopher Tate181fafa2009-05-14 11:12:14 -07004087 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004088 } catch (Exception e) {
4089 throw new RuntimeException("Unable to create BackupAgent "
Christopher Tate4a627c72011-04-01 14:43:32 -07004090 + classname + ": " + e.toString(), e);
Christopher Tate181fafa2009-05-14 11:12:14 -07004091 }
4092 }
4093
4094 // Tear down a BackupAgent
Romain Guy65b345f2011-07-27 18:51:50 -07004095 private void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004096 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07004097
Todd Kennedy233a0b12018-01-29 20:30:24 +00004098 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
4099 String packageName = packageInfo.mPackageName;
Annie Mengd5827872019-01-30 20:28:57 +00004100 ArrayMap<String, BackupAgent> backupAgents = getBackupAgentsForUser(data.userId);
4101 BackupAgent agent = backupAgents.get(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004102 if (agent != null) {
4103 try {
4104 agent.onDestroy();
4105 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004106 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07004107 e.printStackTrace();
4108 }
Annie Mengd5827872019-01-30 20:28:57 +00004109 backupAgents.remove(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004110 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004111 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07004112 }
4113 }
4114
Annie Mengd5827872019-01-30 20:28:57 +00004115 private ArrayMap<String, BackupAgent> getBackupAgentsForUser(int userId) {
4116 ArrayMap<String, BackupAgent> backupAgents = mBackupAgentsByUser.get(userId);
4117 if (backupAgents == null) {
4118 backupAgents = new ArrayMap<>();
4119 mBackupAgentsByUser.put(userId, backupAgents);
4120 }
4121 return backupAgents;
4122 }
4123
Mathew Inwood61e8ae62018-08-14 14:17:44 +01004124 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07004125 private void handleCreateService(CreateServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 // If we are getting ready to gc after going to the background, well
4127 // we are back active so skip it.
4128 unscheduleGcIdler();
4129
Todd Kennedy233a0b12018-01-29 20:30:24 +00004130 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004131 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132 Service service = null;
4133 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004134 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004135
Todd Kennedy233a0b12018-01-29 20:30:24 +00004136 ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
Todd Kennedy233a0b12018-01-29 20:30:24 +00004137 Application app = packageInfo.makeApplication(false, mInstrumentation);
Dave Mankoff66d22c82019-09-11 14:14:45 -04004138 java.lang.ClassLoader cl = packageInfo.getClassLoader();
4139 service = packageInfo.getAppFactory()
4140 .instantiateService(cl, data.info.name, data.intent);
Ryan Mitchell0cbfd2b2020-02-07 11:19:16 -08004141 // Service resources must be initialized with the same loaders as the application
4142 // context.
4143 context.getResources().addLoaders(
4144 app.getResources().getLoaders().toArray(new ResourcesLoader[0]));
4145
Dave Mankoff66d22c82019-09-11 14:14:45 -04004146 context.setOuterContext(service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004147 service.attach(context, this, data.info.name, data.token, app,
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004148 ActivityManager.getService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004149 service.onCreate();
4150 mServices.put(data.token, service);
4151 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004152 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08004153 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004154 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004155 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004156 }
4157 } catch (Exception e) {
4158 if (!mInstrumentation.onException(service, e)) {
4159 throw new RuntimeException(
4160 "Unable to create service " + data.info.name
4161 + ": " + e.toString(), e);
4162 }
4163 }
4164 }
4165
Romain Guy65b345f2011-07-27 18:51:50 -07004166 private void handleBindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167 Service s = mServices.get(data.token);
Amith Yamasani742a6712011-05-04 14:49:28 -07004168 if (DEBUG_SERVICE)
4169 Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004170 if (s != null) {
4171 try {
4172 data.intent.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01004173 data.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 try {
4175 if (!data.rebind) {
4176 IBinder binder = s.onBind(data.intent);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004177 ActivityManager.getService().publishService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004178 data.token, data.intent, binder);
4179 } else {
4180 s.onRebind(data.intent);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004181 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08004182 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004183 }
4184 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004185 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004186 }
4187 } catch (Exception e) {
4188 if (!mInstrumentation.onException(s, e)) {
4189 throw new RuntimeException(
4190 "Unable to bind to service " + s
4191 + " with " + data.intent + ": " + e.toString(), e);
4192 }
4193 }
4194 }
4195 }
4196
Romain Guy65b345f2011-07-27 18:51:50 -07004197 private void handleUnbindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004198 Service s = mServices.get(data.token);
4199 if (s != null) {
4200 try {
4201 data.intent.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01004202 data.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004203 boolean doRebind = s.onUnbind(data.intent);
4204 try {
4205 if (doRebind) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004206 ActivityManager.getService().unbindFinished(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004207 data.token, data.intent, doRebind);
4208 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004209 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08004210 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 }
4212 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004213 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004214 }
4215 } catch (Exception e) {
4216 if (!mInstrumentation.onException(s, e)) {
4217 throw new RuntimeException(
4218 "Unable to unbind to service " + s
4219 + " with " + data.intent + ": " + e.toString(), e);
4220 }
4221 }
4222 }
4223 }
4224
Dianne Hackborn625ac272010-09-17 18:29:22 -07004225 private void handleDumpService(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08004226 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
4227 try {
4228 Service s = mServices.get(info.token);
4229 if (s != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07004230 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
4231 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08004232 s.dump(info.fd.getFileDescriptor(), pw, info.args);
4233 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08004235 } finally {
4236 IoUtils.closeQuietly(info.fd);
4237 StrictMode.setThreadPolicy(oldPolicy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004238 }
4239 }
4240
Dianne Hackborn625ac272010-09-17 18:29:22 -07004241 private void handleDumpActivity(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08004242 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
4243 try {
4244 ActivityClientRecord r = mActivities.get(info.token);
4245 if (r != null && r.activity != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07004246 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
4247 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08004248 r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
4249 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07004250 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08004251 } finally {
4252 IoUtils.closeQuietly(info.fd);
4253 StrictMode.setThreadPolicy(oldPolicy);
Dianne Hackborn625ac272010-09-17 18:29:22 -07004254 }
4255 }
4256
Marco Nelissen18cb2872011-11-15 11:19:53 -08004257 private void handleDumpProvider(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08004258 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
4259 try {
4260 ProviderClientRecord r = mLocalProviders.get(info.token);
4261 if (r != null && r.mLocalProvider != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07004262 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
4263 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08004264 r.mLocalProvider.dump(info.fd.getFileDescriptor(), pw, info.args);
4265 pw.flush();
Marco Nelissen18cb2872011-11-15 11:19:53 -08004266 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08004267 } finally {
4268 IoUtils.closeQuietly(info.fd);
4269 StrictMode.setThreadPolicy(oldPolicy);
Marco Nelissen18cb2872011-11-15 11:19:53 -08004270 }
4271 }
4272
Romain Guy65b345f2011-07-27 18:51:50 -07004273 private void handleServiceArgs(ServiceArgsData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004274 Service s = mServices.get(data.token);
4275 if (s != null) {
4276 try {
4277 if (data.args != null) {
4278 data.args.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01004279 data.args.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004280 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004281 int res;
4282 if (!data.taskRemoved) {
4283 res = s.onStartCommand(data.args, data.flags, data.startId);
4284 } else {
4285 s.onTaskRemoved(data.args);
4286 res = Service.START_TASK_REMOVED_COMPLETE;
4287 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07004288
4289 QueuedWork.waitToFinish();
4290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004292 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08004293 data.token, SERVICE_DONE_EXECUTING_START, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004294 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004295 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 }
4297 } catch (Exception e) {
4298 if (!mInstrumentation.onException(s, e)) {
4299 throw new RuntimeException(
4300 "Unable to start service " + s
4301 + " with " + data.args + ": " + e.toString(), e);
4302 }
4303 }
4304 }
4305 }
4306
Romain Guy65b345f2011-07-27 18:51:50 -07004307 private void handleStopService(IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 Service s = mServices.remove(token);
4309 if (s != null) {
4310 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004311 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004312 s.onDestroy();
Amith Yamasani75928252017-05-22 15:10:47 -07004313 s.detachAndCleanUp();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004314 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08004315 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004316 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08004317 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004318 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07004319
4320 QueuedWork.waitToFinish();
4321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004322 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004323 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08004324 token, SERVICE_DONE_EXECUTING_STOP, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004326 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004327 }
4328 } catch (Exception e) {
4329 if (!mInstrumentation.onException(s, e)) {
4330 throw new RuntimeException(
4331 "Unable to stop service " + s
4332 + ": " + e.toString(), e);
4333 }
Craig Mautner66c4a822015-01-16 12:48:16 -08004334 Slog.i(TAG, "handleStopService: exception for " + token, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004335 }
Craig Mautner9776ad42015-01-15 14:38:39 -08004336 } else {
4337 Slog.i(TAG, "handleStopService: token=" + token + " not found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004338 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004339 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004340 }
4341
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004342 /**
4343 * Resume the activity.
4344 * @param token Target activity token.
4345 * @param finalStateRequest Flag indicating if this is part of final state resolution for a
4346 * transaction.
4347 * @param reason Reason for performing the action.
4348 *
4349 * @return The {@link ActivityClientRecord} that was resumed, {@code null} otherwise.
4350 */
4351 @VisibleForTesting
4352 public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
Andrii Kuliandfbf9712018-03-08 15:42:24 -08004353 String reason) {
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004354 final ActivityClientRecord r = mActivities.get(token);
4355 if (localLOGV) {
4356 Slog.v(TAG, "Performing resume of " + r + " finished=" + r.activity.mFinished);
4357 }
Andrii Kulian0f3356c2019-03-18 21:34:40 +00004358 if (r == null || r.activity.mFinished) {
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004359 return null;
4360 }
4361 if (r.getLifecycleState() == ON_RESUME) {
4362 if (!finalStateRequest) {
4363 final RuntimeException e = new IllegalStateException(
4364 "Trying to resume activity which is already resumed");
4365 Slog.e(TAG, e.getMessage(), e);
4366 Slog.e(TAG, r.getStateString());
4367 // TODO(lifecycler): A double resume request is possible when an activity
4368 // receives two consequent transactions with relaunch requests and "resumed"
4369 // final state requests and the second relaunch is omitted. We still try to
4370 // handle two resume requests for the final state. For cases other than this
4371 // one, we don't expect it to happen.
Andrii Kulian9956d892018-02-14 13:48:56 -08004372 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004373 return null;
4374 }
4375 if (finalStateRequest) {
4376 r.hideForNow = false;
4377 r.activity.mStartedActivity = false;
4378 }
4379 try {
4380 r.activity.onStateNotSaved();
4381 r.activity.mFragments.noteStateNotSaved();
4382 checkAndBlockForNetworkAccess();
4383 if (r.pendingIntents != null) {
4384 deliverNewIntents(r, r.pendingIntents);
4385 r.pendingIntents = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004386 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004387 if (r.pendingResults != null) {
Andrii Kuliane55b0092018-04-19 15:29:22 -07004388 deliverResults(r, r.pendingResults, reason);
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004389 r.pendingResults = null;
4390 }
4391 r.activity.performResume(r.startsNotResumed, reason);
Bob Leee5408332009-09-04 18:31:17 -07004392
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004393 r.state = null;
4394 r.persistentState = null;
4395 r.setState(ON_RESUME);
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004396
Andrii Kulian86024012019-04-18 19:41:23 -07004397 reportTopResumedActivityChanged(r, r.isTopResumedActivity, "topWhenResuming");
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004398 } catch (Exception e) {
4399 if (!mInstrumentation.onException(r.activity, e)) {
4400 throw new RuntimeException("Unable to resume activity "
4401 + r.intent.getComponent().toShortString() + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004402 }
4403 }
4404 return r;
4405 }
4406
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004407 static final void cleanUpPendingRemoveWindows(ActivityClientRecord r, boolean force) {
4408 if (r.mPreserveWindow && !force) {
4409 return;
4410 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004411 if (r.mPendingRemoveWindow != null) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004412 r.mPendingRemoveWindowManager.removeViewImmediate(
4413 r.mPendingRemoveWindow.getDecorView());
4414 IBinder wtoken = r.mPendingRemoveWindow.getDecorView().getWindowToken();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004415 if (wtoken != null) {
Jeff Brown98365d72012-08-19 20:30:52 -07004416 WindowManagerGlobal.getInstance().closeAll(wtoken,
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004417 r.activity.getClass().getName(), "Activity");
4418 }
4419 }
4420 r.mPendingRemoveWindow = null;
4421 r.mPendingRemoveWindowManager = null;
4422 }
4423
Andrii Kulian446e8242017-10-26 15:17:29 -07004424 @Override
Andrii Kuliandfbf9712018-03-08 15:42:24 -08004425 public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004426 String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004427 // If we are getting ready to gc after going to the background, well
4428 // we are back active so skip it.
4429 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004430 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004431
Adam Powellcfbe9be2013-11-06 14:58:58 -08004432 // TODO Push resumeArgs into the activity for consideration
Andrii Kuliandfbf9712018-03-08 15:42:24 -08004433 final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004434 if (r == null) {
4435 // We didn't actually resume the activity, so skipping any follow-up actions.
4436 return;
4437 }
Riddle Hsu66b74a82018-07-26 00:20:12 +08004438 if (mActivitiesToBeDestroyed.containsKey(token)) {
4439 // Although the activity is resumed, it is going to be destroyed. So the following
4440 // UI operations are unnecessary and also prevents exception because its token may
4441 // be gone that window manager cannot recognize it. All necessary cleanup actions
4442 // performed below will be done while handling destruction.
4443 return;
4444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004445
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004446 final Activity a = r.activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004447
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004448 if (localLOGV) {
4449 Slog.v(TAG, "Resume " + r + " started activity: " + a.mStartedActivity
4450 + ", hideForNow: " + r.hideForNow + ", finished: " + a.mFinished);
4451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004452
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004453 final int forwardBit = isForward
4454 ? WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07004455
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004456 // If the window hasn't yet been added to the window manager,
4457 // and this guy didn't finish itself or start another activity,
4458 // then go ahead and add the window.
4459 boolean willBeVisible = !a.mStartedActivity;
4460 if (!willBeVisible) {
4461 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004462 willBeVisible = ActivityTaskManager.getService().willActivityBeVisible(
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004463 a.getActivityToken());
4464 } catch (RemoteException e) {
4465 throw e.rethrowFromSystemServer();
4466 }
4467 }
4468 if (r.window == null && !a.mFinished && willBeVisible) {
4469 r.window = r.activity.getWindow();
4470 View decor = r.window.getDecorView();
4471 decor.setVisibility(View.INVISIBLE);
4472 ViewManager wm = a.getWindowManager();
4473 WindowManager.LayoutParams l = r.window.getAttributes();
4474 a.mDecor = decor;
4475 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
4476 l.softInputMode |= forwardBit;
4477 if (r.mPreserveWindow) {
4478 a.mWindowAdded = true;
4479 r.mPreserveWindow = false;
4480 // Normally the ViewRoot sets up callbacks with the Activity
4481 // in addView->ViewRootImpl#setView. If we are instead reusing
4482 // the decor view we have to notify the view root that the
4483 // callbacks may have changed.
4484 ViewRootImpl impl = decor.getViewRootImpl();
4485 if (impl != null) {
4486 impl.notifyChildRebuilt();
Dianne Hackborn061d58a2010-03-12 15:07:06 -08004487 }
4488 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004489 if (a.mVisibleFromClient) {
4490 if (!a.mWindowAdded) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004491 a.mWindowAdded = true;
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004492 wm.addView(decor, l);
4493 } else {
4494 // The activity will get a callback for this {@link LayoutParams} change
4495 // earlier. However, at that time the decor will not be set (this is set
4496 // in this method), so no action will be taken. This call ensures the
4497 // callback occurs with the decor set.
4498 a.onWindowAttributesChanged(l);
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004499 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004500 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004501
4502 // If the window has already been added, but during resume
4503 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08004504 // window visible.
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004505 } else if (!willBeVisible) {
4506 if (localLOGV) Slog.v(TAG, "Launch " + r + " mStartedActivity set");
4507 r.hideForNow = true;
4508 }
4509
4510 // Get rid of anything left hanging around.
4511 cleanUpPendingRemoveWindows(r, false /* force */);
4512
4513 // The window is now visible if it has been added, we are not
4514 // simply finishing, and we are not starting another activity.
4515 if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) {
4516 if (r.newConfig != null) {
Riddle Hsue553a892020-04-14 17:19:46 +08004517 performConfigurationChangedForActivity(r, r.newConfig,
4518 false /* alwaysReportChange */);
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004519 if (DEBUG_CONFIGURATION) {
4520 Slog.v(TAG, "Resuming activity " + r.activityInfo.name + " with newConfig "
4521 + r.activity.mCurrentConfig);
4522 }
4523 r.newConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004524 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004525 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward=" + isForward);
Tiger Huang4a7835f2019-11-06 00:07:56 +08004526 ViewRootImpl impl = r.window.getDecorView().getViewRootImpl();
4527 WindowManager.LayoutParams l = impl != null
4528 ? impl.mWindowAttributes : r.window.getAttributes();
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004529 if ((l.softInputMode
4530 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
4531 != forwardBit) {
4532 l.softInputMode = (l.softInputMode
4533 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
4534 | forwardBit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004535 if (r.activity.mVisibleFromClient) {
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004536 ViewManager wm = a.getWindowManager();
4537 View decor = r.window.getDecorView();
4538 wm.updateViewLayout(decor, l);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004539 }
4540 }
4541
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004542 r.activity.mVisibleFromServer = true;
4543 mNumVisibleActivities++;
4544 if (r.activity.mVisibleFromClient) {
4545 r.activity.makeVisible();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004546 }
4547 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004548
4549 r.nextIdle = mNewActivities;
4550 mNewActivities = r;
4551 if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);
4552 Looper.myQueue().addIdleHandler(new Idler());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004553 }
4554
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004555
4556 @Override
4557 public void handleTopResumedActivityChanged(IBinder token, boolean onTop, String reason) {
4558 ActivityClientRecord r = mActivities.get(token);
4559 if (r == null || r.activity == null) {
4560 Slog.w(TAG, "Not found target activity to report position change for token: " + token);
4561 return;
4562 }
4563
4564 if (DEBUG_ORDER) {
4565 Slog.d(TAG, "Received position change to top: " + onTop + " for activity: " + r);
4566 }
4567
4568 if (r.isTopResumedActivity == onTop) {
4569 throw new IllegalStateException("Activity top position already set to onTop=" + onTop);
4570 }
4571
4572 r.isTopResumedActivity = onTop;
4573
4574 if (r.getLifecycleState() == ON_RESUME) {
Andrii Kulian86024012019-04-18 19:41:23 -07004575 reportTopResumedActivityChanged(r, onTop, "topStateChangedWhenResumed");
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004576 } else {
4577 if (DEBUG_ORDER) {
4578 Slog.d(TAG, "Won't deliver top position change in state=" + r.getLifecycleState());
4579 }
4580 }
4581 }
4582
4583 /**
4584 * Call {@link Activity#onTopResumedActivityChanged(boolean)} if its top resumed state changed
4585 * since the last report.
4586 */
Andrii Kulian86024012019-04-18 19:41:23 -07004587 private void reportTopResumedActivityChanged(ActivityClientRecord r, boolean onTop,
4588 String reason) {
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004589 if (r.lastReportedTopResumedState != onTop) {
4590 r.lastReportedTopResumedState = onTop;
Andrii Kulian86024012019-04-18 19:41:23 -07004591 r.activity.performTopResumedActivityChanged(onTop, reason);
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004592 }
4593 }
4594
Andrii Kulian446e8242017-10-26 15:17:29 -07004595 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004596 public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
Andrii Kuliana6176e32018-02-27 11:51:18 -08004597 int configChanges, PendingTransactionActions pendingActions, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004598 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004599 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004600 if (userLeaving) {
4601 performUserLeavingActivity(r);
4602 }
Bob Leee5408332009-09-04 18:31:17 -07004603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004604 r.activity.mConfigChangeFlags |= configChanges;
Andrii Kuliand25680c2018-02-21 15:16:58 -08004605 performPauseActivity(r, finished, reason, pendingActions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004606
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07004607 // Make sure any pending writes are now committed.
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004608 if (r.isPreHoneycomb()) {
4609 QueuedWork.waitToFinish();
4610 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004611 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004612 }
4613 }
4614
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004615 final void performUserLeavingActivity(ActivityClientRecord r) {
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004616 mInstrumentation.callActivityOnPictureInPictureRequested(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004617 mInstrumentation.callActivityOnUserLeaving(r.activity);
4618 }
4619
Andrii Kulian8ae79572018-01-26 15:36:06 -08004620 final Bundle performPauseActivity(IBinder token, boolean finished, String reason,
4621 PendingTransactionActions pendingActions) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004622 ActivityClientRecord r = mActivities.get(token);
Andrii Kulian8ae79572018-01-26 15:36:06 -08004623 return r != null ? performPauseActivity(r, finished, reason, pendingActions) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004624 }
4625
Andrii Kulian8ae79572018-01-26 15:36:06 -08004626 /**
4627 * Pause the activity.
4628 * @return Saved instance state for pre-Honeycomb apps if it was saved, {@code null} otherwise.
4629 */
4630 private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
4631 PendingTransactionActions pendingActions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004632 if (r.paused) {
Andrii Kulian0f3356c2019-03-18 21:34:40 +00004633 if (r.activity.mFinished) {
4634 // If we are finishing, we won't call onResume() in certain cases.
4635 // So here we likewise don't want to call onPause() if the activity
4636 // isn't resumed.
4637 return null;
4638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004639 RuntimeException e = new RuntimeException(
4640 "Performing pause of activity that is not resumed: "
4641 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004642 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004644 if (finished) {
4645 r.activity.mFinished = true;
4646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004647
Andrii Kulian8ae79572018-01-26 15:36:06 -08004648 // Pre-Honeycomb apps always save their state before pausing
4649 final boolean shouldSaveState = !r.activity.mFinished && r.isPreHoneycomb();
4650 if (shouldSaveState) {
4651 callActivityOnSaveInstanceState(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004652 }
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004653
4654 performPauseActivityIfNeeded(r, reason);
Jeff Hamilton52d32032011-01-08 15:31:26 -06004655
4656 // Notify any outstanding on paused listeners
4657 ArrayList<OnActivityPausedListener> listeners;
4658 synchronized (mOnPauseListeners) {
4659 listeners = mOnPauseListeners.remove(r.activity);
4660 }
4661 int size = (listeners != null ? listeners.size() : 0);
4662 for (int i = 0; i < size; i++) {
4663 listeners.get(i).onPaused(r.activity);
4664 }
4665
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004666 final Bundle oldState = pendingActions != null ? pendingActions.getOldState() : null;
4667 if (oldState != null) {
4668 // We need to keep around the original state, in case we need to be created again.
4669 // But we only do this for pre-Honeycomb apps, which always save their state when
4670 // pausing, so we can not have them save their state when restarting from a paused
4671 // state. For HC and later, we want to (and can) let the state be saved as the
4672 // normal part of stopping the activity.
4673 if (r.isPreHoneycomb()) {
4674 r.state = oldState;
4675 }
4676 }
4677
Andrii Kulian8ae79572018-01-26 15:36:06 -08004678 return shouldSaveState ? r.state : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004679 }
4680
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004681 private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
4682 if (r.paused) {
4683 // You are already paused silly...
4684 return;
4685 }
4686
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004687 // Always reporting top resumed position loss when pausing an activity. If necessary, it
4688 // will be restored in performResumeActivity().
Andrii Kulian86024012019-04-18 19:41:23 -07004689 reportTopResumedActivityChanged(r, false /* onTop */, "pausing");
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004690
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004691 try {
4692 r.activity.mCalled = false;
4693 mInstrumentation.callActivityOnPause(r.activity);
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004694 if (!r.activity.mCalled) {
4695 throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
4696 + " did not call through to super.onPause()");
4697 }
4698 } catch (SuperNotCalledException e) {
4699 throw e;
4700 } catch (Exception e) {
4701 if (!mInstrumentation.onException(r.activity, e)) {
4702 throw new RuntimeException("Unable to pause activity "
4703 + safeToComponentShortString(r.intent) + ": " + e.toString(), e);
4704 }
4705 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004706 r.setState(ON_PAUSE);
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004707 }
4708
Andrii Kulian829829c2018-03-19 18:19:05 -07004709 /** Called from {@link LocalActivityManager}. */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01004710 @UnsupportedAppUsage
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08004711 final void performStopActivity(IBinder token, boolean saveState, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004712 ActivityClientRecord r = mActivities.get(token);
Andrii Kulianb9faa032019-10-17 23:11:54 -07004713 performStopActivityInner(r, null /* stopInfo */, saveState, false /* finalStateRequest */,
4714 reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004715 }
4716
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004717 private static final class ProviderRefCount {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07004718 public final ContentProviderHolder holder;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004719 public final ProviderClientRecord client;
4720 public int stableCount;
4721 public int unstableCount;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004722
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004723 // When this is set, the stable and unstable ref counts are 0 and
4724 // we have a pending operation scheduled to remove the ref count
4725 // from the activity manager. On the activity manager we are still
4726 // holding an unstable ref, though it is not reflected in the counts
4727 // here.
4728 public boolean removePending;
4729
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07004730 ProviderRefCount(ContentProviderHolder inHolder,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004731 ProviderClientRecord inClient, int sCount, int uCount) {
4732 holder = inHolder;
4733 client = inClient;
4734 stableCount = sCount;
4735 unstableCount = uCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004736 }
4737 }
4738
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004739 /**
Andrii Kulianb9faa032019-10-17 23:11:54 -07004740 * Core implementation of stopping an activity.
Andrii Kulian829829c2018-03-19 18:19:05 -07004741 * @param r Target activity client record.
4742 * @param info Action that will report activity stop to server.
Andrii Kulian829829c2018-03-19 18:19:05 -07004743 * @param saveState Flag indicating whether the activity state should be saved.
4744 * @param finalStateRequest Flag indicating if this call is handling final lifecycle state
4745 * request for a transaction.
4746 * @param reason Reason for performing this operation.
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004747 */
Andrii Kulianb9faa032019-10-17 23:11:54 -07004748 private void performStopActivityInner(ActivityClientRecord r, StopInfo info,
Andrii Kulian829829c2018-03-19 18:19:05 -07004749 boolean saveState, boolean finalStateRequest, String reason) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004750 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004751 if (r != null) {
Andrii Kulianb9faa032019-10-17 23:11:54 -07004752 if (r.stopped) {
Andrii Kulian0f3356c2019-03-18 21:34:40 +00004753 if (r.activity.mFinished) {
4754 // If we are finishing, we won't call onResume() in certain
4755 // cases. So here we likewise don't want to call onStop()
4756 // if the activity isn't resumed.
4757 return;
4758 }
4759 if (!finalStateRequest) {
4760 final RuntimeException e = new RuntimeException(
4761 "Performing stop of activity that is already stopped: "
4762 + r.intent.getComponent().toShortString());
4763 Slog.e(TAG, e.getMessage(), e);
4764 Slog.e(TAG, r.getStateString());
4765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004766 }
4767
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004768 // One must first be paused before stopped...
4769 performPauseActivityIfNeeded(r, reason);
4770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004771 if (info != null) {
4772 try {
4773 // First create a thumbnail for the activity...
Dianne Hackborn0500b3c2011-11-01 15:28:43 -07004774 // For now, don't create the thumbnail here; we are
4775 // doing that by doing a screen snapshot.
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004776 info.setDescription(r.activity.onCreateDescription());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004777 } catch (Exception e) {
4778 if (!mInstrumentation.onException(r.activity, e)) {
4779 throw new RuntimeException(
4780 "Unable to save state of activity "
4781 + r.intent.getComponent().toShortString()
4782 + ": " + e.toString(), e);
4783 }
4784 }
4785 }
4786
Andrii Kulianb9faa032019-10-17 23:11:54 -07004787 callActivityOnStop(r, saveState, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004788 }
4789 }
4790
Andrii Kulian8ae79572018-01-26 15:36:06 -08004791 /**
4792 * Calls {@link Activity#onStop()} and {@link Activity#onSaveInstanceState(Bundle)}, and updates
4793 * the client record's state.
4794 * All calls to stop an activity must be done through this method to make sure that
4795 * {@link Activity#onSaveInstanceState(Bundle)} is also executed in the same call.
4796 */
4797 private void callActivityOnStop(ActivityClientRecord r, boolean saveState, String reason) {
Andrii Kulian391161f2018-01-29 10:50:02 -08004798 // Before P onSaveInstanceState was called before onStop, starting with P it's
4799 // called after. Before Honeycomb state was always saved before onPause.
Andrii Kulian8ae79572018-01-26 15:36:06 -08004800 final boolean shouldSaveState = saveState && !r.activity.mFinished && r.state == null
4801 && !r.isPreHoneycomb();
Andrii Kulian391161f2018-01-29 10:50:02 -08004802 final boolean isPreP = r.isPreP();
4803 if (shouldSaveState && isPreP) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004804 callActivityOnSaveInstanceState(r);
4805 }
4806
4807 try {
Garfield Tanc1681e62018-05-29 11:05:05 -07004808 r.activity.performStop(r.mPreserveWindow, reason);
Andrii Kulian8ae79572018-01-26 15:36:06 -08004809 } catch (SuperNotCalledException e) {
4810 throw e;
4811 } catch (Exception e) {
4812 if (!mInstrumentation.onException(r.activity, e)) {
4813 throw new RuntimeException(
4814 "Unable to stop activity "
4815 + r.intent.getComponent().toShortString()
4816 + ": " + e.toString(), e);
4817 }
4818 }
4819 r.setState(ON_STOP);
Andrii Kulian391161f2018-01-29 10:50:02 -08004820
4821 if (shouldSaveState && !isPreP) {
4822 callActivityOnSaveInstanceState(r);
4823 }
Andrii Kulian8ae79572018-01-26 15:36:06 -08004824 }
4825
Romain Guy65b345f2011-07-27 18:51:50 -07004826 private void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004827 View v = r.activity.mDecor;
4828 if (v != null) {
4829 if (show) {
4830 if (!r.activity.mVisibleFromServer) {
4831 r.activity.mVisibleFromServer = true;
4832 mNumVisibleActivities++;
4833 if (r.activity.mVisibleFromClient) {
4834 r.activity.makeVisible();
4835 }
4836 }
4837 if (r.newConfig != null) {
Riddle Hsue553a892020-04-14 17:19:46 +08004838 performConfigurationChangedForActivity(r, r.newConfig,
4839 false /* alwaysReportChange */);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004840 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Adam Lesinski082614c2016-03-04 14:33:47 -08004841 + r.activityInfo.name + " with new config "
4842 + r.activity.mCurrentConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004843 r.newConfig = null;
4844 }
4845 } else {
4846 if (r.activity.mVisibleFromServer) {
4847 r.activity.mVisibleFromServer = false;
4848 mNumVisibleActivities--;
4849 v.setVisibility(View.INVISIBLE);
4850 }
4851 }
4852 }
4853 }
4854
Andrii Kulian446e8242017-10-26 15:17:29 -07004855 @Override
Andrii Kulianb9faa032019-10-17 23:11:54 -07004856 public void handleStopActivity(IBinder token, int configChanges,
Andrii Kulian829829c2018-03-19 18:19:05 -07004857 PendingTransactionActions pendingActions, boolean finalStateRequest, String reason) {
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004858 final ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004859 r.activity.mConfigChangeFlags |= configChanges;
4860
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004861 final StopInfo stopInfo = new StopInfo();
Andrii Kulianb9faa032019-10-17 23:11:54 -07004862 performStopActivityInner(r, stopInfo, true /* saveState */, finalStateRequest,
Andrii Kulian829829c2018-03-19 18:19:05 -07004863 reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004864
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004865 if (localLOGV) Slog.v(
Andrii Kulianb9faa032019-10-17 23:11:54 -07004866 TAG, "Finishing stop of " + r + ": win=" + r.window);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004867
Andrii Kulianb9faa032019-10-17 23:11:54 -07004868 updateVisibility(r, false);
Bob Leee5408332009-09-04 18:31:17 -07004869
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004870 // Make sure any pending writes are now committed.
4871 if (!r.isPreHoneycomb()) {
4872 QueuedWork.waitToFinish();
4873 }
4874
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004875 stopInfo.setActivity(r);
4876 stopInfo.setState(r.state);
4877 stopInfo.setPersistentState(r.persistentState);
4878 pendingActions.setStopInfo(stopInfo);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004879 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004880 }
4881
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004882 /**
4883 * Schedule the call to tell the activity manager we have stopped. We don't do this
4884 * immediately, because we want to have a chance for any other pending work (in particular
4885 * memory trim requests) to complete before you tell the activity manager to proceed and allow
4886 * us to go fully into the background.
4887 */
4888 @Override
4889 public void reportStop(PendingTransactionActions pendingActions) {
4890 mH.post(pendingActions.getStopInfo());
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07004891 }
4892
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004893 @Override
4894 public void performRestartActivity(IBinder token, boolean start) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004895 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004896 if (r.stopped) {
Andrii Kuliand25680c2018-02-21 15:16:58 -08004897 r.activity.performRestart(start, "performRestartActivity");
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004898 if (start) {
4899 r.setState(ON_START);
4900 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004901 }
4902 }
4903
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004904 private void handleSetCoreSettings(Bundle coreSettings) {
Craig Mautner88c05892013-06-28 09:47:45 -07004905 synchronized (mResourcesManager) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08004906 mCoreSettings = coreSettings;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004907 }
Jon Miranda836c0a82014-08-11 12:32:26 -07004908 onCoreSettingsChange();
4909 }
4910
4911 private void onCoreSettingsChange() {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08004912 if (updateDebugViewAttributeState()) {
Jon Miranda836c0a82014-08-11 12:32:26 -07004913 // request all activities to relaunch for the changes to take place
Adrian Roos03dd48c2019-03-19 17:17:37 -04004914 relaunchAllActivities(false /* preserveWindows */);
Fyodor Kupolovcb93d6f2017-05-04 17:27:16 -07004915 }
4916 }
4917
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08004918 private boolean updateDebugViewAttributeState() {
4919 boolean previousState = View.sDebugViewAttributes;
4920
4921 View.sDebugViewAttributesApplicationPackage = mCoreSettings.getString(
4922 Settings.Global.DEBUG_VIEW_ATTRIBUTES_APPLICATION_PACKAGE, "");
4923 String currentPackage = (mBoundApplication != null && mBoundApplication.appInfo != null)
MÃ¥rten Kongstad62eed6b2019-09-19 15:35:44 +02004924 ? mBoundApplication.appInfo.packageName : "<unknown-app>";
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08004925 View.sDebugViewAttributes =
4926 mCoreSettings.getInt(Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0
4927 || View.sDebugViewAttributesApplicationPackage.equals(currentPackage);
4928 return previousState != View.sDebugViewAttributes;
4929 }
4930
Adrian Roos03dd48c2019-03-19 17:17:37 -04004931 private void relaunchAllActivities(boolean preserveWindows) {
Fyodor Kupolovcb93d6f2017-05-04 17:27:16 -07004932 for (Map.Entry<IBinder, ActivityClientRecord> entry : mActivities.entrySet()) {
Adrian Roos03dd48c2019-03-19 17:17:37 -04004933 final ActivityClientRecord r = entry.getValue();
4934 if (!r.activity.mFinished) {
4935 if (preserveWindows && r.window != null) {
4936 r.mPreserveWindow = true;
4937 }
Andrii Kulian320e3b52018-05-03 16:26:25 -07004938 scheduleRelaunchActivity(entry.getKey());
Jon Miranda836c0a82014-08-11 12:32:26 -07004939 }
4940 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004941 }
4942
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004943 private void handleUpdatePackageCompatibilityInfo(UpdateCompatibilityData data) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00004944 LoadedApk apk = peekPackageInfo(data.pkg, false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004945 if (apk != null) {
Craig Mautner48d0d182013-06-11 07:53:06 -07004946 apk.setCompatibilityInfo(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004947 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00004948 apk = peekPackageInfo(data.pkg, true);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004949 if (apk != null) {
Craig Mautner48d0d182013-06-11 07:53:06 -07004950 apk.setCompatibilityInfo(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004951 }
4952 handleConfigurationChanged(mConfiguration, data.info);
Jeff Brown98365d72012-08-19 20:30:52 -07004953 WindowManagerGlobal.getInstance().reportNewConfiguration(mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004954 }
4955
Andrii Kuliane55b0092018-04-19 15:29:22 -07004956 private void deliverResults(ActivityClientRecord r, List<ResultInfo> results, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004957 final int N = results.size();
4958 for (int i=0; i<N; i++) {
4959 ResultInfo ri = results.get(i);
4960 try {
4961 if (ri.mData != null) {
4962 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01004963 ri.mData.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004964 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004965 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07004966 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004967 r.activity.dispatchActivityResult(ri.mResultWho,
Andrii Kuliane55b0092018-04-19 15:29:22 -07004968 ri.mRequestCode, ri.mResultCode, ri.mData, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004969 } catch (Exception e) {
4970 if (!mInstrumentation.onException(r.activity, e)) {
4971 throw new RuntimeException(
4972 "Failure delivering result " + ri + " to activity "
4973 + r.intent.getComponent().toShortString()
4974 + ": " + e.toString(), e);
4975 }
4976 }
4977 }
4978 }
4979
Andrii Kulian446e8242017-10-26 15:17:29 -07004980 @Override
Andrii Kuliane55b0092018-04-19 15:29:22 -07004981 public void handleSendResult(IBinder token, List<ResultInfo> results, String reason) {
Andrii Kulian446e8242017-10-26 15:17:29 -07004982 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004983 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004984 if (r != null) {
4985 final boolean resumed = !r.paused;
4986 if (!r.activity.mFinished && r.activity.mDecor != null
4987 && r.hideForNow && resumed) {
4988 // We had hidden the activity because it started another
4989 // one... we have gotten a result back and we are not
4990 // paused, so make sure our window is visible.
4991 updateVisibility(r, true);
4992 }
4993 if (resumed) {
4994 try {
4995 // Now we are idle.
4996 r.activity.mCalled = false;
4997 mInstrumentation.callActivityOnPause(r.activity);
4998 if (!r.activity.mCalled) {
4999 throw new SuperNotCalledException(
5000 "Activity " + r.intent.getComponent().toShortString()
5001 + " did not call through to super.onPause()");
5002 }
5003 } catch (SuperNotCalledException e) {
5004 throw e;
5005 } catch (Exception e) {
5006 if (!mInstrumentation.onException(r.activity, e)) {
5007 throw new RuntimeException(
5008 "Unable to pause activity "
5009 + r.intent.getComponent().toShortString()
5010 + ": " + e.toString(), e);
5011 }
5012 }
5013 }
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07005014 checkAndBlockForNetworkAccess();
Andrii Kuliane55b0092018-04-19 15:29:22 -07005015 deliverResults(r, results, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005016 if (resumed) {
Andrii Kuliane55b0092018-04-19 15:29:22 -07005017 r.activity.performResume(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005018 }
5019 }
5020 }
5021
Andrii Kulian88e05cb2017-12-05 17:21:10 -08005022 /** Core implementation of activity destroy call. */
5023 ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
Bryce Leea33c13d2018-02-08 14:37:06 -08005024 int configChanges, boolean getNonConfigInstance, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005025 ActivityClientRecord r = mActivities.get(token);
Darryl Johnson700c2062020-04-23 18:14:40 +00005026 Class<? extends Activity> activityClass = null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005027 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005028 if (r != null) {
Darryl Johnson700c2062020-04-23 18:14:40 +00005029 activityClass = r.activity.getClass();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005030 r.activity.mConfigChangeFlags |= configChanges;
5031 if (finishing) {
5032 r.activity.mFinished = true;
5033 }
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07005034
5035 performPauseActivityIfNeeded(r, "destroy");
5036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005037 if (!r.stopped) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08005038 callActivityOnStop(r, false /* saveState */, "destroy");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005039 }
5040 if (getNonConfigInstance) {
5041 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07005042 r.lastNonConfigurationInstances
5043 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005044 } catch (Exception e) {
5045 if (!mInstrumentation.onException(r.activity, e)) {
5046 throw new RuntimeException(
5047 "Unable to retain activity "
5048 + r.intent.getComponent().toShortString()
5049 + ": " + e.toString(), e);
5050 }
5051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005052 }
5053 try {
5054 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005055 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005056 if (!r.activity.mCalled) {
5057 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07005058 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005059 " did not call through to super.onDestroy()");
5060 }
5061 if (r.window != null) {
5062 r.window.closeAllPanels();
5063 }
5064 } catch (SuperNotCalledException e) {
5065 throw e;
5066 } catch (Exception e) {
5067 if (!mInstrumentation.onException(r.activity, e)) {
5068 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07005069 "Unable to destroy activity " + safeToComponentShortString(r.intent)
5070 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005071 }
5072 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08005073 r.setState(ON_DESTROY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005074 }
Tim Murray59f3dc12018-10-22 15:26:08 -07005075 schedulePurgeIdler();
Garfield Tan0443b372019-01-04 15:00:13 -08005076 // updatePendingActivityConfiguration() reads from mActivities to update
5077 // ActivityClientRecord which runs in a different thread. Protect modifications to
5078 // mActivities to avoid race.
5079 synchronized (mResourcesManager) {
5080 mActivities.remove(token);
5081 }
Darryl Johnson700c2062020-04-23 18:14:40 +00005082 StrictMode.decrementExpectedActivityCount(activityClass);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005083 return r;
5084 }
5085
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07005086 private static String safeToComponentShortString(Intent intent) {
5087 ComponentName component = intent.getComponent();
5088 return component == null ? "[Unknown]" : component.toShortString();
5089 }
5090
Andrii Kulian446e8242017-10-26 15:17:29 -07005091 @Override
Riddle Hsud3062cb2018-06-30 02:06:42 +08005092 public Map<IBinder, ClientTransactionItem> getActivitiesToBeDestroyed() {
5093 return mActivitiesToBeDestroyed;
5094 }
5095
5096 @Override
Andrii Kulian446e8242017-10-26 15:17:29 -07005097 public void handleDestroyActivity(IBinder token, boolean finishing, int configChanges,
Bryce Leea33c13d2018-02-08 14:37:06 -08005098 boolean getNonConfigInstance, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005099 ActivityClientRecord r = performDestroyActivity(token, finishing,
Bryce Leea33c13d2018-02-08 14:37:06 -08005100 configChanges, getNonConfigInstance, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005101 if (r != null) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07005102 cleanUpPendingRemoveWindows(r, finishing);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005103 WindowManager wm = r.activity.getWindowManager();
5104 View v = r.activity.mDecor;
5105 if (v != null) {
5106 if (r.activity.mVisibleFromServer) {
5107 mNumVisibleActivities--;
5108 }
5109 IBinder wtoken = v.getWindowToken();
5110 if (r.activity.mWindowAdded) {
Robert Carr77bdfb52016-05-02 18:18:31 -07005111 if (r.mPreserveWindow) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005112 // Hold off on removing this until the new activity's
5113 // window is being added.
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07005114 r.mPendingRemoveWindow = r.window;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005115 r.mPendingRemoveWindowManager = wm;
Andrii Kulianeac0ea52016-05-11 15:50:24 -07005116 // We can only keep the part of the view hierarchy that we control,
5117 // everything else must be removed, because it might not be able to
5118 // behave properly when activity is relaunching.
5119 r.window.clearContentView();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005120 } else {
5121 wm.removeViewImmediate(v);
5122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005123 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005124 if (wtoken != null && r.mPendingRemoveWindow == null) {
Jeff Brown98365d72012-08-19 20:30:52 -07005125 WindowManagerGlobal.getInstance().closeAll(wtoken,
Darryl Johnson700c2062020-04-23 18:14:40 +00005126 r.activity.getClass().getName(), "Activity");
Andrii Kulianeac0ea52016-05-11 15:50:24 -07005127 } else if (r.mPendingRemoveWindow != null) {
5128 // We're preserving only one window, others should be closed so app views
5129 // will be detached before the final tear down. It should be done now because
5130 // some components (e.g. WebView) rely on detach callbacks to perform receiver
5131 // unregister and other cleanup.
5132 WindowManagerGlobal.getInstance().closeAllExceptView(token, v,
Darryl Johnson700c2062020-04-23 18:14:40 +00005133 r.activity.getClass().getName(), "Activity");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005134 }
5135 r.activity.mDecor = null;
5136 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005137 if (r.mPendingRemoveWindow == null) {
5138 // If we are delaying the removal of the activity window, then
5139 // we can't clean up all windows here. Note that we can't do
5140 // so later either, which means any windows that aren't closed
5141 // by the app will leak. Well we try to warning them a lot
5142 // about leaking windows, because that is a bug, so if they are
5143 // using this recreate facility then they get to live with leaks.
Jeff Brown98365d72012-08-19 20:30:52 -07005144 WindowManagerGlobal.getInstance().closeAll(token,
Darryl Johnson700c2062020-04-23 18:14:40 +00005145 r.activity.getClass().getName(), "Activity");
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005147
5148 // Mocked out contexts won't be participating in the normal
5149 // process lifecycle, but if we're running with a proper
5150 // ApplicationContext we need to have it tear down things
5151 // cleanly.
Darryl Johnson700c2062020-04-23 18:14:40 +00005152 Context c = r.activity.getBaseContext();
5153 if (c instanceof ContextImpl) {
5154 ((ContextImpl) c).scheduleFinalCleanup(
5155 r.activity.getClass().getName(), "Activity");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005156 }
5157 }
5158 if (finishing) {
5159 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07005160 ActivityTaskManager.getService().activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005161 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005162 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005163 }
5164 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07005165 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005166 }
5167
Andrii Kulianb372da62018-01-18 10:46:24 -08005168 @Override
5169 public ActivityClientRecord prepareRelaunchActivity(IBinder token,
Dianne Hackborn85d558c2014-11-04 10:31:54 -08005170 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
Andrii Kulianb372da62018-01-18 10:46:24 -08005171 int configChanges, MergedConfiguration config, boolean preserveWindow) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005172 ActivityClientRecord target = null;
Andrii Kulianb372da62018-01-18 10:46:24 -08005173 boolean scheduleRelaunch = false;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005174
Craig Mautner88c05892013-06-28 09:47:45 -07005175 synchronized (mResourcesManager) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005176 for (int i=0; i<mRelaunchingActivities.size(); i++) {
5177 ActivityClientRecord r = mRelaunchingActivities.get(i);
Filip Gruszczynskic3b61792016-01-22 16:43:48 -08005178 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: " + this + ", trying: " + r);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005179 if (r.token == token) {
5180 target = r;
5181 if (pendingResults != null) {
5182 if (r.pendingResults != null) {
5183 r.pendingResults.addAll(pendingResults);
5184 } else {
5185 r.pendingResults = pendingResults;
5186 }
5187 }
5188 if (pendingNewIntents != null) {
5189 if (r.pendingIntents != null) {
5190 r.pendingIntents.addAll(pendingNewIntents);
5191 } else {
5192 r.pendingIntents = pendingNewIntents;
5193 }
5194 }
5195 break;
5196 }
5197 }
5198
5199 if (target == null) {
Andrii Kulianb372da62018-01-18 10:46:24 -08005200 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: target is null");
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005201 target = new ActivityClientRecord();
5202 target.token = token;
5203 target.pendingResults = pendingResults;
5204 target.pendingIntents = pendingNewIntents;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07005205 target.mPreserveWindow = preserveWindow;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005206 mRelaunchingActivities.add(target);
Andrii Kulianb372da62018-01-18 10:46:24 -08005207 scheduleRelaunch = true;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005208 }
Andrii Kulianb372da62018-01-18 10:46:24 -08005209 target.createdConfig = config.getGlobalConfiguration();
5210 target.overrideConfig = config.getOverrideConfiguration();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005211 target.pendingConfigChanges |= configChanges;
5212 }
Andrii Kulianb372da62018-01-18 10:46:24 -08005213
5214 return scheduleRelaunch ? target : null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005215 }
5216
Andrii Kulianb372da62018-01-18 10:46:24 -08005217 @Override
5218 public void handleRelaunchActivity(ActivityClientRecord tmp,
5219 PendingTransactionActions pendingActions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005220 // If we are getting ready to gc after going to the background, well
5221 // we are back active so skip it.
5222 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07005223 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005224
5225 Configuration changedConfig = null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005226 int configChanges = 0;
Bob Leee5408332009-09-04 18:31:17 -07005227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005228 // First: make sure we have the most recent configuration and most
5229 // recent version of the activity, or skip it if some previous call
5230 // had taken a more recent version.
Craig Mautner88c05892013-06-28 09:47:45 -07005231 synchronized (mResourcesManager) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005232 int N = mRelaunchingActivities.size();
5233 IBinder token = tmp.token;
5234 tmp = null;
5235 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005236 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005237 if (r.token == token) {
5238 tmp = r;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005239 configChanges |= tmp.pendingConfigChanges;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005240 mRelaunchingActivities.remove(i);
5241 i--;
5242 N--;
5243 }
5244 }
Bob Leee5408332009-09-04 18:31:17 -07005245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005246 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005247 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005248 return;
5249 }
Bob Leee5408332009-09-04 18:31:17 -07005250
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005251 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
5252 + tmp.token + " with configChanges=0x"
5253 + Integer.toHexString(configChanges));
5254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005255 if (mPendingConfiguration != null) {
5256 changedConfig = mPendingConfiguration;
5257 mPendingConfiguration = null;
5258 }
5259 }
Bob Leee5408332009-09-04 18:31:17 -07005260
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08005261 if (tmp.createdConfig != null) {
5262 // If the activity manager is passing us its current config,
5263 // assume that is really what we want regardless of what we
5264 // may have pending.
5265 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005266 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
5267 && mConfiguration.diff(tmp.createdConfig) != 0)) {
5268 if (changedConfig == null
5269 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
5270 changedConfig = tmp.createdConfig;
5271 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08005272 }
5273 }
Tim Murraye1e6c662015-04-07 13:24:14 -07005274
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005275 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07005276 + tmp.token + ": changedConfig=" + changedConfig);
Tim Murraye1e6c662015-04-07 13:24:14 -07005277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005278 // If there was a pending configuration change, execute it first.
5279 if (changedConfig != null) {
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005280 mCurDefaultDisplayDpi = changedConfig.densityDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -07005281 updateDefaultDensity();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04005282 handleConfigurationChanged(changedConfig, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005283 }
Bob Leee5408332009-09-04 18:31:17 -07005284
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005285 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005286 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005287 if (r == null) {
5288 return;
5289 }
Bob Leee5408332009-09-04 18:31:17 -07005290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005291 r.activity.mConfigChangeFlags |= configChanges;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07005292 r.mPreserveWindow = tmp.mPreserveWindow;
Bob Leee5408332009-09-04 18:31:17 -07005293
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08005294 r.activity.mChangingConfigurations = true;
5295
Robert Carr23fa16b2016-01-13 13:19:58 -08005296 // If we are preserving the main window across relaunches we would also like to preserve
5297 // the children. However the client side view system does not support preserving
5298 // the child views so we notify the window manager to expect these windows to
5299 // be replaced and defer requests to destroy or hide them. This way we can achieve
5300 // visual continuity. It's important that we do this here prior to pause and destroy
5301 // as that is when we may hide or remove the child views.
Robert Carr77bdfb52016-05-02 18:18:31 -07005302 //
5303 // There is another scenario, if we have decided locally to relaunch the app from a
5304 // call to recreate, then none of the windows will be prepared for replacement or
5305 // preserved by the server, so we want to notify it that we are preparing to replace
5306 // everything
Robert Carr23fa16b2016-01-13 13:19:58 -08005307 try {
Andrii Kulianb372da62018-01-18 10:46:24 -08005308 if (r.mPreserveWindow) {
Robert Carr77bdfb52016-05-02 18:18:31 -07005309 WindowManagerGlobal.getWindowSession().prepareToReplaceWindows(
Andrii Kulianb372da62018-01-18 10:46:24 -08005310 r.token, true /* childrenOnly */);
Robert Carr23fa16b2016-01-13 13:19:58 -08005311 }
5312 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005313 throw e.rethrowFromSystemServer();
Robert Carr23fa16b2016-01-13 13:19:58 -08005314 }
5315
Hongwei Wang5711b8f2019-11-15 15:44:12 -08005316 // Save the current windowing mode to be restored and compared to the new configuration's
5317 // windowing mode (needed because we update the last reported windowing mode when launching
5318 // an activity and we can't tell inside performLaunchActivity whether we are relaunching)
5319 final int oldWindowingMode = mLastReportedWindowingMode.getOrDefault(
5320 r.activity.getActivityToken(), WINDOWING_MODE_UNDEFINED);
Wale Ogunwale5527a502018-02-20 18:18:21 -08005321 handleRelaunchActivityInner(r, configChanges, tmp.pendingResults, tmp.pendingIntents,
5322 pendingActions, tmp.startsNotResumed, tmp.overrideConfig, "handleRelaunchActivity");
Hongwei Wang5711b8f2019-11-15 15:44:12 -08005323 mLastReportedWindowingMode.put(r.activity.getActivityToken(), oldWindowingMode);
5324 handleWindowingModeChangeIfNeeded(r.activity, r.activity.mCurrentConfig);
Wale Ogunwale5527a502018-02-20 18:18:21 -08005325
5326 if (pendingActions != null) {
5327 // Only report a successful relaunch to WindowManager.
5328 pendingActions.setReportRelaunchToWindowManager(true);
Dianne Hackborne2b04802010-12-09 09:24:55 -08005329 }
Wale Ogunwale5527a502018-02-20 18:18:21 -08005330 }
5331
Andrii Kulian320e3b52018-05-03 16:26:25 -07005332 /**
5333 * Post a message to relaunch the activity. We do this instead of launching it immediately,
5334 * because this will destroy the activity from which it was called and interfere with the
5335 * lifecycle changes it was going through before. We need to make sure that we have finished
5336 * handling current transaction item before relaunching the activity.
5337 */
5338 void scheduleRelaunchActivity(IBinder token) {
Amin Shaikh96e60d72019-04-24 13:47:57 -04005339 mH.removeMessages(H.RELAUNCH_ACTIVITY, token);
Andrii Kulian320e3b52018-05-03 16:26:25 -07005340 sendMessage(H.RELAUNCH_ACTIVITY, token);
5341 }
Bob Leee5408332009-09-04 18:31:17 -07005342
Andrii Kulian320e3b52018-05-03 16:26:25 -07005343 /** Performs the activity relaunch locally vs. requesting from system-server. */
5344 private void handleRelaunchActivityLocally(IBinder token) {
Wale Ogunwale5527a502018-02-20 18:18:21 -08005345 final ActivityClientRecord r = mActivities.get(token);
5346 if (r == null) {
Andrii Kulian320e3b52018-05-03 16:26:25 -07005347 Log.w(TAG, "Activity to relaunch no longer exists");
Wale Ogunwale5527a502018-02-20 18:18:21 -08005348 return;
5349 }
5350
5351 final int prevState = r.getLifecycleState();
5352
Andrii Kulian320e3b52018-05-03 16:26:25 -07005353 if (prevState < ON_RESUME || prevState > ON_STOP) {
5354 Log.w(TAG, "Activity state must be in [ON_RESUME..ON_STOP] in order to be relaunched,"
5355 + "current state is " + prevState);
Wale Ogunwale5527a502018-02-20 18:18:21 -08005356 return;
5357 }
5358
Wale Ogunwale5527a502018-02-20 18:18:21 -08005359
Andrii Kulian914aa7d2018-03-19 21:51:53 -07005360 // Initialize a relaunch request.
5361 final MergedConfiguration mergedConfiguration = new MergedConfiguration(
5362 r.createdConfig != null ? r.createdConfig : mConfiguration,
5363 r.overrideConfig);
5364 final ActivityRelaunchItem activityRelaunchItem = ActivityRelaunchItem.obtain(
5365 null /* pendingResults */, null /* pendingIntents */, 0 /* configChanges */,
5366 mergedConfiguration, r.mPreserveWindow);
5367 // Make sure to match the existing lifecycle state in the end of the transaction.
5368 final ActivityLifecycleItem lifecycleRequest =
5369 TransactionExecutorHelper.getLifecycleRequestForCurrentState(r);
5370 // Schedule the transaction.
5371 final ClientTransaction transaction = ClientTransaction.obtain(this.mAppThread, r.token);
5372 transaction.addCallback(activityRelaunchItem);
5373 transaction.setLifecycleStateRequest(lifecycleRequest);
5374 executeTransaction(transaction);
Wale Ogunwale5527a502018-02-20 18:18:21 -08005375 }
5376
5377 private void handleRelaunchActivityInner(ActivityClientRecord r, int configChanges,
5378 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingIntents,
5379 PendingTransactionActions pendingActions, boolean startsNotResumed,
5380 Configuration overrideConfig, String reason) {
Andrii Kulian770c4032018-05-02 18:40:59 -07005381 // Preserve last used intent, it may be set from Activity#setIntent().
5382 final Intent customIntent = r.activity.mIntent;
Wale Ogunwale5527a502018-02-20 18:18:21 -08005383 // Need to ensure state is saved.
5384 if (!r.paused) {
5385 performPauseActivity(r, false, reason, null /* pendingActions */);
5386 }
5387 if (!r.stopped) {
5388 callActivityOnStop(r, true /* saveState */, reason);
5389 }
5390
5391 handleDestroyActivity(r.token, false, configChanges, true, reason);
Bob Leee5408332009-09-04 18:31:17 -07005392
Darryl Johnson700c2062020-04-23 18:14:40 +00005393 r.activity = null;
5394 r.window = null;
5395 r.hideForNow = false;
5396 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07005397 // Merge any pending results and pending intents; don't just replace them
Wale Ogunwale5527a502018-02-20 18:18:21 -08005398 if (pendingResults != null) {
The Android Open Source Project10592532009-03-18 17:39:46 -07005399 if (r.pendingResults == null) {
Wale Ogunwale5527a502018-02-20 18:18:21 -08005400 r.pendingResults = pendingResults;
The Android Open Source Project10592532009-03-18 17:39:46 -07005401 } else {
Wale Ogunwale5527a502018-02-20 18:18:21 -08005402 r.pendingResults.addAll(pendingResults);
The Android Open Source Project10592532009-03-18 17:39:46 -07005403 }
5404 }
Wale Ogunwale5527a502018-02-20 18:18:21 -08005405 if (pendingIntents != null) {
The Android Open Source Project10592532009-03-18 17:39:46 -07005406 if (r.pendingIntents == null) {
Wale Ogunwale5527a502018-02-20 18:18:21 -08005407 r.pendingIntents = pendingIntents;
The Android Open Source Project10592532009-03-18 17:39:46 -07005408 } else {
Wale Ogunwale5527a502018-02-20 18:18:21 -08005409 r.pendingIntents.addAll(pendingIntents);
The Android Open Source Project10592532009-03-18 17:39:46 -07005410 }
5411 }
Wale Ogunwale5527a502018-02-20 18:18:21 -08005412 r.startsNotResumed = startsNotResumed;
5413 r.overrideConfig = overrideConfig;
Bob Leee5408332009-09-04 18:31:17 -07005414
Andrii Kulian770c4032018-05-02 18:40:59 -07005415 handleLaunchActivity(r, pendingActions, customIntent);
Andrii Kulianb372da62018-01-18 10:46:24 -08005416 }
Jorim Jaggife89d122015-12-22 16:28:44 +01005417
Andrii Kulianb372da62018-01-18 10:46:24 -08005418 @Override
5419 public void reportRelaunch(IBinder token, PendingTransactionActions pendingActions) {
5420 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07005421 ActivityTaskManager.getService().activityRelaunched(token);
Andrii Kulianb372da62018-01-18 10:46:24 -08005422 final ActivityClientRecord r = mActivities.get(token);
5423 if (pendingActions.shouldReportRelaunchToWindowManager() && r != null
5424 && r.window != null) {
5425 r.window.reportActivityRelaunched();
Jorim Jaggife89d122015-12-22 16:28:44 +01005426 }
Andrii Kulianb372da62018-01-18 10:46:24 -08005427 } catch (RemoteException e) {
5428 throw e.rethrowFromSystemServer();
Jorim Jaggife89d122015-12-22 16:28:44 +01005429 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005430 }
5431
Andrii Kulian8ae79572018-01-26 15:36:06 -08005432 private void callActivityOnSaveInstanceState(ActivityClientRecord r) {
Craig Mautnera0026042014-04-23 11:45:37 -07005433 r.state = new Bundle();
5434 r.state.setAllowFds(false);
5435 if (r.isPersistable()) {
5436 r.persistentState = new PersistableBundle();
5437 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state,
5438 r.persistentState);
5439 } else {
5440 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
5441 }
5442 }
5443
Dianne Hackborn73c14162012-09-19 15:45:06 -07005444 ArrayList<ComponentCallbacks2> collectComponentCallbacks(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005445 boolean allActivities, Configuration newConfig) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005446 ArrayList<ComponentCallbacks2> callbacks
5447 = new ArrayList<ComponentCallbacks2>();
Bob Leee5408332009-09-04 18:31:17 -07005448
Craig Mautner88c05892013-06-28 09:47:45 -07005449 synchronized (mResourcesManager) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005450 final int NAPP = mAllApplications.size();
5451 for (int i=0; i<NAPP; i++) {
Dianne Hackborn73c14162012-09-19 15:45:06 -07005452 callbacks.add(mAllApplications.get(i));
5453 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005454 final int NACT = mActivities.size();
5455 for (int i=0; i<NACT; i++) {
5456 ActivityClientRecord ar = mActivities.valueAt(i);
5457 Activity a = ar.activity;
5458 if (a != null) {
5459 Configuration thisConfig = applyConfigCompatMainThread(
5460 mCurDefaultDisplayDpi, newConfig,
Todd Kennedy233a0b12018-01-29 20:30:24 +00005461 ar.packageInfo.getCompatibilityInfo());
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005462 if (!ar.activity.mFinished && (allActivities || !ar.paused)) {
5463 // If the activity is currently resumed, its configuration
5464 // needs to change right now.
5465 callbacks.add(a);
5466 } else if (thisConfig != null) {
5467 // Otherwise, we will tell it about the change
5468 // the next time it is resumed or shown. Note that
5469 // the activity manager may, before then, decide the
5470 // activity needs to be destroyed to handle its new
5471 // configuration.
5472 if (DEBUG_CONFIGURATION) {
5473 Slog.v(TAG, "Setting activity "
5474 + ar.activityInfo.name + " newConfig=" + thisConfig);
Romain Guya998dff2012-03-23 18:58:36 -07005475 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005476 ar.newConfig = thisConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005477 }
5478 }
5479 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005480 final int NSVC = mServices.size();
5481 for (int i=0; i<NSVC; i++) {
lumarkddc77fb2019-06-27 22:22:23 +08005482 final ComponentCallbacks2 serviceComp = mServices.valueAt(i);
5483 if (serviceComp instanceof InputMethodService) {
5484 mHasImeComponent = true;
5485 }
5486 callbacks.add(serviceComp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005487 }
5488 }
5489 synchronized (mProviderMap) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005490 final int NPRV = mLocalProviders.size();
5491 for (int i=0; i<NPRV; i++) {
5492 callbacks.add(mLocalProviders.valueAt(i).mLocalProvider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005493 }
5494 }
Bob Leee5408332009-09-04 18:31:17 -07005495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005496 return callbacks;
5497 }
Bob Leee5408332009-09-04 18:31:17 -07005498
Adam Lesinski082614c2016-03-04 14:33:47 -08005499 /**
5500 * Updates the configuration for an Activity. The ActivityClientRecord's
5501 * {@link ActivityClientRecord#overrideConfig} is used to compute the final Configuration for
5502 * that Activity. {@link ActivityClientRecord#tmpConfig} is used as a temporary for delivering
5503 * the updated Configuration.
5504 * @param r ActivityClientRecord representing the Activity.
5505 * @param newBaseConfig The new configuration to use. This may be augmented with
5506 * {@link ActivityClientRecord#overrideConfig}.
Riddle Hsue553a892020-04-14 17:19:46 +08005507 * @param alwaysReportChange If the configuration is changed, always report to activity.
Adam Lesinski082614c2016-03-04 14:33:47 -08005508 */
5509 private void performConfigurationChangedForActivity(ActivityClientRecord r,
Riddle Hsue553a892020-04-14 17:19:46 +08005510 Configuration newBaseConfig, boolean alwaysReportChange) {
5511 performConfigurationChangedForActivity(r, newBaseConfig, r.activity.getDisplayId(),
5512 false /* movedToDifferentDisplay */, alwaysReportChange);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005513 }
5514
5515 /**
5516 * Updates the configuration for an Activity. The ActivityClientRecord's
5517 * {@link ActivityClientRecord#overrideConfig} is used to compute the final Configuration for
5518 * that Activity. {@link ActivityClientRecord#tmpConfig} is used as a temporary for delivering
5519 * the updated Configuration.
5520 * @param r ActivityClientRecord representing the Activity.
5521 * @param newBaseConfig The new configuration to use. This may be augmented with
5522 * {@link ActivityClientRecord#overrideConfig}.
5523 * @param displayId The id of the display where the Activity currently resides.
5524 * @param movedToDifferentDisplay Indicates if the activity was moved to different display.
Riddle Hsue553a892020-04-14 17:19:46 +08005525 * @param alwaysReportChange If the configuration is changed, always report to activity.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005526 * @return {@link Configuration} instance sent to client, null if not sent.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005527 */
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005528 private Configuration performConfigurationChangedForActivity(ActivityClientRecord r,
Riddle Hsue553a892020-04-14 17:19:46 +08005529 Configuration newBaseConfig, int displayId, boolean movedToDifferentDisplay,
5530 boolean alwaysReportChange) {
Adam Lesinski082614c2016-03-04 14:33:47 -08005531 r.tmpConfig.setTo(newBaseConfig);
5532 if (r.overrideConfig != null) {
5533 r.tmpConfig.updateFrom(r.overrideConfig);
5534 }
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005535 final Configuration reportedConfig = performActivityConfigurationChanged(r.activity,
Riddle Hsue553a892020-04-14 17:19:46 +08005536 r.tmpConfig, r.overrideConfig, displayId, movedToDifferentDisplay,
5537 alwaysReportChange);
Adam Lesinski082614c2016-03-04 14:33:47 -08005538 freeTextLayoutCachesIfNeeded(r.activity.mCurrentConfig.diff(r.tmpConfig));
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005539 return reportedConfig;
Adam Lesinski082614c2016-03-04 14:33:47 -08005540 }
5541
5542 /**
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -07005543 * Creates a new Configuration only if override would modify base. Otherwise returns base.
5544 * @param base The base configuration.
5545 * @param override The update to apply to the base configuration. Can be null.
5546 * @return A Configuration representing base with override applied.
5547 */
5548 private static Configuration createNewConfigAndUpdateIfNotNull(@NonNull Configuration base,
5549 @Nullable Configuration override) {
5550 if (override == null) {
5551 return base;
5552 }
5553 Configuration newConfig = new Configuration(base);
5554 newConfig.updateFrom(override);
5555 return newConfig;
5556 }
5557
5558 /**
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005559 * Decides whether to update a component's configuration and whether to inform it.
Adam Lesinski082614c2016-03-04 14:33:47 -08005560 * @param cb The component callback to notify of configuration change.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005561 * @param newConfig The new configuration.
5562 */
5563 private void performConfigurationChanged(ComponentCallbacks2 cb, Configuration newConfig) {
5564 if (!REPORT_TO_ACTIVITY) {
5565 return;
5566 }
5567
5568 // ContextThemeWrappers may override the configuration for that context. We must check and
5569 // apply any overrides defined.
5570 Configuration contextThemeWrapperOverrideConfig = null;
5571 if (cb instanceof ContextThemeWrapper) {
5572 final ContextThemeWrapper contextThemeWrapper = (ContextThemeWrapper) cb;
5573 contextThemeWrapperOverrideConfig = contextThemeWrapper.getOverrideConfiguration();
5574 }
5575
5576 // Apply the ContextThemeWrapper override if necessary.
5577 // NOTE: Make sure the configurations are not modified, as they are treated as immutable
5578 // in many places.
5579 final Configuration configToReport = createNewConfigAndUpdateIfNotNull(
5580 newConfig, contextThemeWrapperOverrideConfig);
5581 cb.onConfigurationChanged(configToReport);
5582 }
5583
5584 /**
5585 * Decides whether to update an Activity's configuration and whether to inform it.
5586 * @param activity The activity to notify of configuration change.
Adam Lesinski082614c2016-03-04 14:33:47 -08005587 * @param newConfig The new configuration.
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -07005588 * @param amOverrideConfig The override config that differentiates the Activity's configuration
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005589 * from the base global configuration. This is supplied by
5590 * ActivityManager.
5591 * @param displayId Id of the display where activity currently resides.
5592 * @param movedToDifferentDisplay Indicates if the activity was moved to different display.
Riddle Hsue553a892020-04-14 17:19:46 +08005593 * @param alwaysReportChange If the configuration is changed, always report to activity.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005594 * @return Configuration sent to client, null if no changes and not moved to different display.
Adam Lesinski082614c2016-03-04 14:33:47 -08005595 */
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005596 private Configuration performActivityConfigurationChanged(Activity activity,
5597 Configuration newConfig, Configuration amOverrideConfig, int displayId,
Riddle Hsue553a892020-04-14 17:19:46 +08005598 boolean movedToDifferentDisplay, boolean alwaysReportChange) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005599 if (activity == null) {
5600 throw new IllegalArgumentException("No activity provided.");
5601 }
5602 final IBinder activityToken = activity.getActivityToken();
5603 if (activityToken == null) {
5604 throw new IllegalArgumentException("Activity token not set. Is the activity attached?");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005605 }
Bob Leee5408332009-09-04 18:31:17 -07005606
Hongwei Wang5711b8f2019-11-15 15:44:12 -08005607 // multi-window / pip mode changes, if any, should be sent before the configuration change
5608 // callback, see also PinnedStackTests#testConfigurationChangeOrderDuringTransition
5609 handleWindowingModeChangeIfNeeded(activity, newConfig);
5610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005611 boolean shouldChangeConfig = false;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005612 if (activity.mCurrentConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005613 shouldChangeConfig = true;
5614 } else {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005615 // If the new config is the same as the config this Activity is already running with and
5616 // the override config also didn't change, then don't bother calling
5617 // onConfigurationChanged.
Bryce Lee658d9842017-07-28 08:33:36 -07005618 final int diff = activity.mCurrentConfig.diffPublicOnly(newConfig);
5619
Andrii Kulian3b3c9142016-07-18 19:15:56 -07005620 if (diff != 0 || !mResourcesManager.isSameResourcesOverrideConfig(activityToken,
5621 amOverrideConfig)) {
Chong Zhang4951f9d2016-06-23 13:15:08 -07005622 // Always send the task-level config changes. For system-level configuration, if
5623 // this activity doesn't handle any of the config changes, then don't bother
5624 // calling onConfigurationChanged as we're going to destroy it.
Riddle Hsue553a892020-04-14 17:19:46 +08005625 if (alwaysReportChange
Chong Zhang4951f9d2016-06-23 13:15:08 -07005626 || (~activity.mActivityInfo.getRealConfigChanged() & diff) == 0
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005627 || !REPORT_TO_ACTIVITY) {
Chong Zhang4951f9d2016-06-23 13:15:08 -07005628 shouldChangeConfig = true;
5629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005630 }
5631 }
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005632 if (!shouldChangeConfig && !movedToDifferentDisplay) {
5633 // Nothing significant, don't proceed with updating and reporting.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005634 return null;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005635 }
5636
5637 // Propagate the configuration change to ResourcesManager and Activity.
5638
5639 // ContextThemeWrappers may override the configuration for that context. We must check and
5640 // apply any overrides defined.
5641 Configuration contextThemeWrapperOverrideConfig = activity.getOverrideConfiguration();
5642
5643 // We only update an Activity's configuration if this is not a global configuration change.
5644 // This must also be done before the callback, or else we violate the contract that the new
5645 // resources are available in ComponentCallbacks2#onConfigurationChanged(Configuration).
5646 // Also apply the ContextThemeWrapper override if necessary.
5647 // NOTE: Make sure the configurations are not modified, as they are treated as immutable in
5648 // many places.
5649 final Configuration finalOverrideConfig = createNewConfigAndUpdateIfNotNull(
5650 amOverrideConfig, contextThemeWrapperOverrideConfig);
5651 mResourcesManager.updateResourcesForActivity(activityToken, finalOverrideConfig,
5652 displayId, movedToDifferentDisplay);
5653
5654 activity.mConfigChangeFlags = 0;
5655 activity.mCurrentConfig = new Configuration(newConfig);
5656
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005657 // Apply the ContextThemeWrapper override if necessary.
5658 // NOTE: Make sure the configurations are not modified, as they are treated as immutable
5659 // in many places.
5660 final Configuration configToReport = createNewConfigAndUpdateIfNotNull(newConfig,
5661 contextThemeWrapperOverrideConfig);
5662
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005663 if (!REPORT_TO_ACTIVITY) {
5664 // Not configured to report to activity.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005665 return configToReport;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005666 }
5667
5668 if (movedToDifferentDisplay) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005669 activity.dispatchMovedToDisplay(displayId, configToReport);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005670 }
Bob Leee5408332009-09-04 18:31:17 -07005671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005672 if (shouldChangeConfig) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005673 activity.mCalled = false;
5674 activity.onConfigurationChanged(configToReport);
5675 if (!activity.mCalled) {
5676 throw new SuperNotCalledException("Activity " + activity.getLocalClassName() +
5677 " did not call through to super.onConfigurationChanged()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005678 }
5679 }
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005680
5681 return configToReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005682 }
5683
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07005684 public final void applyConfigurationToResources(Configuration config) {
Craig Mautner88c05892013-06-28 09:47:45 -07005685 synchronized (mResourcesManager) {
5686 mResourcesManager.applyConfigurationToResourcesLocked(config, null);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07005687 }
5688 }
5689
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005690 final Configuration applyCompatConfiguration(int displayDensity) {
Dianne Hackborn836e2622011-10-04 18:32:39 -07005691 Configuration config = mConfiguration;
5692 if (mCompatConfiguration == null) {
5693 mCompatConfiguration = new Configuration();
5694 }
5695 mCompatConfiguration.setTo(mConfiguration);
Adam Lesinski082614c2016-03-04 14:33:47 -08005696 if (mResourcesManager.applyCompatConfigurationLocked(displayDensity,
5697 mCompatConfiguration)) {
Dianne Hackborn836e2622011-10-04 18:32:39 -07005698 config = mCompatConfiguration;
5699 }
5700 return config;
5701 }
5702
Andrii Kulian446e8242017-10-26 15:17:29 -07005703 @Override
5704 public void handleConfigurationChanged(Configuration config) {
5705 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "configChanged");
5706 mCurDefaultDisplayDpi = config.densityDpi;
Riddle Hsue553a892020-04-14 17:19:46 +08005707 handleConfigurationChanged(config, null /* compat */);
Andrii Kulian446e8242017-10-26 15:17:29 -07005708 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
5709 }
5710
5711 private void handleConfigurationChanged(Configuration config, CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005712
Tiger Huang968064b2019-05-28 14:36:18 +08005713 int configDiff;
5714 boolean equivalent;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005715
Todd Kennedy35a9a382018-01-25 13:25:37 -08005716 final Theme systemTheme = getSystemContext().getTheme();
5717 final Theme systemUiTheme = getSystemUiContext().getTheme();
Bryce Lee658d9842017-07-28 08:33:36 -07005718
Craig Mautner88c05892013-06-28 09:47:45 -07005719 synchronized (mResourcesManager) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005720 if (mPendingConfiguration != null) {
5721 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
5722 config = mPendingConfiguration;
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005723 mCurDefaultDisplayDpi = config.densityDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -07005724 updateDefaultDensity();
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005725 }
5726 mPendingConfiguration = null;
5727 }
5728
5729 if (config == null) {
lumarkddc77fb2019-06-27 22:22:23 +08005730 // TODO (b/135719017): Temporary log for debugging IME service.
5731 if (Build.IS_DEBUGGABLE && mHasImeComponent) {
5732 Log.w(TAG, "handleConfigurationChanged for IME app but config is null");
5733 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005734 return;
5735 }
Tim Murraye1e6c662015-04-07 13:24:14 -07005736
Tiger Huang968064b2019-05-28 14:36:18 +08005737 // This flag tracks whether the new configuration is fundamentally equivalent to the
5738 // existing configuration. This is necessary to determine whether non-activity callbacks
5739 // should receive notice when the only changes are related to non-public fields.
5740 // We do not gate calling {@link #performActivityConfigurationChanged} based on this
5741 // flag as that method uses the same check on the activity config override as well.
5742 equivalent = mConfiguration != null && (0 == mConfiguration.diffPublicOnly(config));
5743
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005744 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005745 + config);
Craig Mautner88c05892013-06-28 09:47:45 -07005746
5747 mResourcesManager.applyConfigurationToResourcesLocked(config, compat);
Adam Lesinskib61e4052016-05-19 18:23:05 -07005748 updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
5749 mResourcesManager.getConfiguration().getLocales());
Craig Mautner88c05892013-06-28 09:47:45 -07005750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005751 if (mConfiguration == null) {
5752 mConfiguration = new Configuration();
5753 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04005754 if (!mConfiguration.isOtherSeqNewer(config) && compat == null) {
lumarkddc77fb2019-06-27 22:22:23 +08005755 // TODO (b/135719017): Temporary log for debugging IME service.
5756 if (Build.IS_DEBUGGABLE && mHasImeComponent) {
5757 Log.w(TAG, "handleConfigurationChanged for IME app but config seq is obsolete "
5758 + ", config=" + config
5759 + ", mConfiguration=" + mConfiguration);
5760 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005761 return;
5762 }
Alan Viverettee54d2452015-05-06 10:41:43 -07005763
5764 configDiff = mConfiguration.updateFrom(config);
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005765 config = applyCompatConfiguration(mCurDefaultDisplayDpi);
Alan Viverette395cd012015-08-11 17:27:04 -04005766
Alan Viverette395cd012015-08-11 17:27:04 -04005767 if ((systemTheme.getChangingConfigurations() & configDiff) != 0) {
5768 systemTheme.rebase();
5769 }
Adam Lesinskia82b6262017-03-21 16:56:17 -07005770
Adam Lesinskia82b6262017-03-21 16:56:17 -07005771 if ((systemUiTheme.getChangingConfigurations() & configDiff) != 0) {
5772 systemUiTheme.rebase();
5773 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005774 }
Dianne Hackborn73c14162012-09-19 15:45:06 -07005775
5776 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(false, config);
5777
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005778 freeTextLayoutCachesIfNeeded(configDiff);
5779
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005780 if (callbacks != null) {
5781 final int N = callbacks.size();
5782 for (int i=0; i<N; i++) {
Andrii Kulian701214b2016-04-07 09:36:33 -07005783 ComponentCallbacks2 cb = callbacks.get(i);
5784 if (cb instanceof Activity) {
5785 // If callback is an Activity - call corresponding method to consider override
5786 // config and avoid onConfigurationChanged if it hasn't changed.
5787 Activity a = (Activity) cb;
5788 performConfigurationChangedForActivity(mActivities.get(a.getActivityToken()),
Riddle Hsue553a892020-04-14 17:19:46 +08005789 config, false /* alwaysReportChange */);
Bryce Lee658d9842017-07-28 08:33:36 -07005790 } else if (!equivalent) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005791 performConfigurationChanged(cb, config);
lumarkddc77fb2019-06-27 22:22:23 +08005792 } else {
5793 // TODO (b/135719017): Temporary log for debugging IME service.
5794 if (Build.IS_DEBUGGABLE && cb instanceof InputMethodService) {
5795 Log.w(TAG, "performConfigurationChanged didn't callback to IME "
5796 + ", configDiff=" + configDiff
5797 + ", mConfiguration=" + mConfiguration);
5798 }
Andrii Kulian701214b2016-04-07 09:36:33 -07005799 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005801 }
5802 }
5803
Winson72dbe7e2019-04-29 14:55:30 -07005804 /**
Hongwei Wang5711b8f2019-11-15 15:44:12 -08005805 * Sends windowing mode change callbacks to {@link Activity} if applicable.
5806 *
5807 * See also {@link Activity#onMultiWindowModeChanged(boolean, Configuration)} and
5808 * {@link Activity#onPictureInPictureModeChanged(boolean, Configuration)}
5809 */
5810 private void handleWindowingModeChangeIfNeeded(Activity activity,
5811 Configuration newConfiguration) {
5812 final int newWindowingMode = newConfiguration.windowConfiguration.getWindowingMode();
5813 final IBinder token = activity.getActivityToken();
5814 final int oldWindowingMode = mLastReportedWindowingMode.getOrDefault(token,
5815 WINDOWING_MODE_UNDEFINED);
5816 if (oldWindowingMode == newWindowingMode) return;
5817 // PiP callback is sent before the MW one.
5818 if (newWindowingMode == WINDOWING_MODE_PINNED) {
5819 activity.dispatchPictureInPictureModeChanged(true, newConfiguration);
5820 } else if (oldWindowingMode == WINDOWING_MODE_PINNED) {
5821 activity.dispatchPictureInPictureModeChanged(false, newConfiguration);
5822 }
5823 final boolean wasInMultiWindowMode = WindowConfiguration.inMultiWindowMode(
5824 oldWindowingMode);
5825 final boolean nowInMultiWindowMode = WindowConfiguration.inMultiWindowMode(
5826 newWindowingMode);
5827 if (wasInMultiWindowMode != nowInMultiWindowMode) {
5828 activity.dispatchMultiWindowModeChanged(nowInMultiWindowMode, newConfiguration);
5829 }
5830 mLastReportedWindowingMode.put(token, newWindowingMode);
5831 }
5832
5833 /**
Winson72dbe7e2019-04-29 14:55:30 -07005834 * Updates the application info.
5835 *
5836 * This only works in the system process. Must be called on the main thread.
5837 */
5838 public void handleSystemApplicationInfoChanged(@NonNull ApplicationInfo ai) {
5839 Preconditions.checkState(mSystemThread, "Must only be called in the system process");
5840 handleApplicationInfoChanged(ai);
5841 }
5842
Adrian Roos03dd48c2019-03-19 17:17:37 -04005843 @VisibleForTesting(visibility = PACKAGE)
5844 public void handleApplicationInfoChanged(@NonNull final ApplicationInfo ai) {
Adam Lesinskid33ef562017-01-19 14:49:59 -08005845 // Updates triggered by package installation go through a package update
5846 // receiver. Here we try to capture ApplicationInfo changes that are
5847 // caused by other sources, such as overlays. That means we want to be as conservative
5848 // about code changes as possible. Take the diff of the old ApplicationInfo and the new
5849 // to see if anything needs to change.
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005850 LoadedApk apk;
5851 LoadedApk resApk;
5852 // Update all affected loaded packages with new package information
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005853 synchronized (mResourcesManager) {
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005854 WeakReference<LoadedApk> ref = mPackages.get(ai.packageName);
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005855 apk = ref != null ? ref.get() : null;
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005856 ref = mResourcePackages.get(ai.packageName);
5857 resApk = ref != null ? ref.get() : null;
5858 }
Winsond605e2d2019-02-11 16:05:51 -08005859
5860 final String[] oldResDirs = new String[2];
5861
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005862 if (apk != null) {
Winsond605e2d2019-02-11 16:05:51 -08005863 oldResDirs[0] = apk.getResDir();
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005864 final ArrayList<String> oldPaths = new ArrayList<>();
5865 LoadedApk.makePaths(this, apk.getApplicationInfo(), oldPaths);
5866 apk.updateApplicationInfo(ai, oldPaths);
5867 }
5868 if (resApk != null) {
Winsond605e2d2019-02-11 16:05:51 -08005869 oldResDirs[1] = resApk.getResDir();
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005870 final ArrayList<String> oldPaths = new ArrayList<>();
5871 LoadedApk.makePaths(this, resApk.getApplicationInfo(), oldPaths);
5872 resApk.updateApplicationInfo(ai, oldPaths);
5873 }
Winsond605e2d2019-02-11 16:05:51 -08005874
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005875 synchronized (mResourcesManager) {
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005876 // Update all affected Resources objects to use new ResourcesImpl
Winsond605e2d2019-02-11 16:05:51 -08005877 mResourcesManager.applyNewResourceDirsLocked(ai, oldResDirs);
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005878 }
5879
5880 ApplicationPackageManager.configurationChanged();
5881
5882 // Trigger a regular Configuration change event, only with a different assetsSeq number
5883 // so that we actually call through to all components.
Adam Lesinskia82b6262017-03-21 16:56:17 -07005884 // TODO(adamlesinski): Change this to make use of ActivityManager's upcoming ability to
5885 // store configurations per-process.
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005886 Configuration newConfig = new Configuration();
Adam Lesinskia82b6262017-03-21 16:56:17 -07005887 newConfig.assetsSeq = (mConfiguration != null ? mConfiguration.assetsSeq : 0) + 1;
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005888 handleConfigurationChanged(newConfig, null);
5889
Adrian Roos03dd48c2019-03-19 17:17:37 -04005890 // Preserve windows to avoid black flickers when overlays change.
5891 relaunchAllActivities(true /* preserveWindows */);
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005892 }
5893
Romain Guy46bfc482013-08-16 18:38:29 -07005894 static void freeTextLayoutCachesIfNeeded(int configDiff) {
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005895 if (configDiff != 0) {
5896 // Ask text layout engine to free its caches if there is a locale change
5897 boolean hasLocaleConfigChange = ((configDiff & ActivityInfo.CONFIG_LOCALE) != 0);
5898 if (hasLocaleConfigChange) {
5899 Canvas.freeTextLayoutCaches();
5900 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Cleared TextLayout Caches");
5901 }
5902 }
5903 }
5904
Garfield Tan0443b372019-01-04 15:00:13 -08005905 @Override
5906 public void updatePendingActivityConfiguration(IBinder activityToken,
5907 Configuration overrideConfig) {
5908 final ActivityClientRecord r;
5909 synchronized (mResourcesManager) {
5910 r = mActivities.get(activityToken);
5911 }
5912
5913 if (r == null) {
5914 if (DEBUG_CONFIGURATION) {
5915 Slog.w(TAG, "Not found target activity to update its pending config.");
5916 }
5917 return;
5918 }
5919
5920 synchronized (r) {
5921 r.mPendingOverrideConfig = overrideConfig;
5922 }
5923 }
5924
Riddle Hsue553a892020-04-14 17:19:46 +08005925 @Override
5926 public void handleActivityConfigurationChanged(IBinder activityToken,
5927 Configuration overrideConfig, int displayId) {
5928 handleActivityConfigurationChanged(activityToken, overrideConfig, displayId,
5929 // This is the only place that uses alwaysReportChange=true. The entry point should
5930 // be from ActivityConfigurationChangeItem or MoveToDisplayItem, so the server side
5931 // has confirmed the activity should handle the configuration instead of relaunch.
5932 // If Activity#onConfigurationChanged is called unexpectedly, then we can know it is
5933 // something wrong from server side.
5934 true /* alwaysReportChange */);
5935 }
5936
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005937 /**
5938 * Handle new activity configuration and/or move to a different display.
Andrii Kulian446e8242017-10-26 15:17:29 -07005939 * @param activityToken Target activity token.
5940 * @param overrideConfig Activity override config.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005941 * @param displayId Id of the display where activity was moved to, -1 if there was no move and
5942 * value didn't change.
Riddle Hsue553a892020-04-14 17:19:46 +08005943 * @param alwaysReportChange If the configuration is changed, always report to activity.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005944 */
Riddle Hsue553a892020-04-14 17:19:46 +08005945 void handleActivityConfigurationChanged(IBinder activityToken, Configuration overrideConfig,
5946 int displayId, boolean alwaysReportChange) {
Andrii Kulian446e8242017-10-26 15:17:29 -07005947 ActivityClientRecord r = mActivities.get(activityToken);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005948 // Check input params.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005949 if (r == null || r.activity == null) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005950 if (DEBUG_CONFIGURATION) Slog.w(TAG, "Not found target activity to report to: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005951 return;
5952 }
Andrii Kulian51c1b672017-04-07 18:39:32 -07005953 final boolean movedToDifferentDisplay = displayId != INVALID_DISPLAY
Yohei Yukawa5281b6b2018-10-15 07:38:25 +08005954 && displayId != r.activity.getDisplayId();
Bob Leee5408332009-09-04 18:31:17 -07005955
Garfield Tan0443b372019-01-04 15:00:13 -08005956 synchronized (r) {
5957 if (r.mPendingOverrideConfig != null
5958 && !r.mPendingOverrideConfig.isOtherSeqNewer(overrideConfig)) {
5959 overrideConfig = r.mPendingOverrideConfig;
5960 }
5961 r.mPendingOverrideConfig = null;
5962 }
5963
5964 if (r.overrideConfig != null && !r.overrideConfig.isOtherSeqNewer(overrideConfig)
5965 && !movedToDifferentDisplay) {
5966 if (DEBUG_CONFIGURATION) {
5967 Slog.v(TAG, "Activity already handled newer configuration so drop this"
5968 + " transaction. overrideConfig=" + overrideConfig + " r.overrideConfig="
5969 + r.overrideConfig);
5970 }
5971 return;
5972 }
5973
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005974 // Perform updates.
Andrii Kulian446e8242017-10-26 15:17:29 -07005975 r.overrideConfig = overrideConfig;
Stephen Kiazykf903b732017-03-20 16:23:45 -07005976 final ViewRootImpl viewRoot = r.activity.mDecor != null
5977 ? r.activity.mDecor.getViewRootImpl() : null;
5978
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005979 if (movedToDifferentDisplay) {
5980 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity moved to display, activity:"
5981 + r.activityInfo.name + ", displayId=" + displayId
Andrii Kulian446e8242017-10-26 15:17:29 -07005982 + ", config=" + overrideConfig);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005983
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005984 final Configuration reportedConfig = performConfigurationChangedForActivity(r,
Riddle Hsue553a892020-04-14 17:19:46 +08005985 mCompatConfiguration, displayId, true /* movedToDifferentDisplay */,
5986 alwaysReportChange);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005987 if (viewRoot != null) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005988 viewRoot.onMovedToDisplay(displayId, reportedConfig);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005989 }
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005990 } else {
5991 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Andrii Kulian446e8242017-10-26 15:17:29 -07005992 + r.activityInfo.name + ", config=" + overrideConfig);
Riddle Hsue553a892020-04-14 17:19:46 +08005993 performConfigurationChangedForActivity(r, mCompatConfiguration, alwaysReportChange);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005994 }
Andrii Kulian44607962017-03-16 11:06:24 -07005995 // Notify the ViewRootImpl instance about configuration changes. It may have initiated this
5996 // update to make sure that resources are updated before updating itself.
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005997 if (viewRoot != null) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005998 viewRoot.updateConfiguration(displayId);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005999 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006000 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 }
6002
Jeff Hao1b012d32014-08-20 10:35:34 -07006003 final void handleProfilerControl(boolean start, ProfilerInfo profilerInfo, int profileType) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08006004 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08006005 try {
Romain Guy7eabe552011-07-21 14:56:34 -07006006 switch (profileType) {
Jeff Hao1b012d32014-08-20 10:35:34 -07006007 default:
6008 mProfiler.setProfiler(profilerInfo);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07006009 mProfiler.startProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07006010 break;
6011 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08006012 } catch (RuntimeException e) {
Jeff Hao1b012d32014-08-20 10:35:34 -07006013 Slog.w(TAG, "Profiling failed on path " + profilerInfo.profileFile
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08006014 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07006015 } finally {
Andreas Gampe2b073a02017-06-22 17:28:57 -07006016 profilerInfo.closeFd();
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08006017 }
6018 } else {
Romain Guy7eabe552011-07-21 14:56:34 -07006019 switch (profileType) {
Romain Guy7eabe552011-07-21 14:56:34 -07006020 default:
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07006021 mProfiler.stopProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07006022 break;
Romain Guy7eabe552011-07-21 14:56:34 -07006023 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08006024 }
6025 }
Bob Leee5408332009-09-04 18:31:17 -07006026
Andreas Gampe4c79fea2016-01-28 20:11:41 -08006027 /**
6028 * Public entrypoint to stop profiling. This is required to end profiling when the app crashes,
6029 * so that profiler data won't be lost.
6030 *
6031 * @hide
6032 */
6033 public void stopProfiling() {
Amith Yamasanib1684432017-01-26 14:57:20 -08006034 if (mProfiler != null) {
6035 mProfiler.stopProfiling();
6036 }
Andreas Gampe4c79fea2016-01-28 20:11:41 -08006037 }
6038
Christopher Ferris8d652f82017-04-11 16:29:18 -07006039 static void handleDumpHeap(DumpHeapData dhd) {
Makoto Onuki4556b7b2017-07-07 14:58:58 -07006040 if (dhd.runGc) {
6041 System.gc();
6042 System.runFinalization();
6043 System.gc();
6044 }
Kweku Adams4af1b502019-05-23 16:23:48 -07006045 try (ParcelFileDescriptor fd = dhd.fd) {
6046 if (dhd.managed) {
6047 Debug.dumpHprofData(dhd.path, fd.getFileDescriptor());
6048 } else if (dhd.mallocInfo) {
6049 Debug.dumpNativeMallocInfo(fd.getFileDescriptor());
6050 } else {
6051 Debug.dumpNativeHeap(fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07006052 }
Kweku Adams4af1b502019-05-23 16:23:48 -07006053 } catch (IOException e) {
6054 if (dhd.managed) {
6055 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
6056 + " -- can the process access this path?", e);
6057 } else {
6058 Slog.w(TAG, "Failed to dump heap", e);
6059 }
6060 } catch (RuntimeException e) {
6061 // This should no longer happening now that we're copying the file descriptor.
6062 Slog.wtf(TAG, "Heap dumper threw a runtime exception", e);
Andy McFadden824c5102010-07-09 16:26:57 -07006063 }
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08006064 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006065 ActivityManager.getService().dumpHeapFinished(dhd.path);
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08006066 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006067 throw e.rethrowFromSystemServer();
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08006068 }
Makoto Onuki2c6657f2018-06-06 15:24:02 -07006069 if (dhd.finishCallback != null) {
6070 dhd.finishCallback.sendResult(null);
6071 }
Andy McFadden824c5102010-07-09 16:26:57 -07006072 }
6073
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07006074 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00006075 boolean hasPkgInfo = false;
Todd Kennedy39bfee52016-02-24 10:28:21 -08006076 switch (cmd) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07006077 case ApplicationThreadConstants.PACKAGE_REMOVED:
6078 case ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL:
Todd Kennedy39bfee52016-02-24 10:28:21 -08006079 {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07006080 final boolean killApp = cmd == ApplicationThreadConstants.PACKAGE_REMOVED;
Todd Kennedy39bfee52016-02-24 10:28:21 -08006081 if (packages == null) {
6082 break;
6083 }
6084 synchronized (mResourcesManager) {
6085 for (int i = packages.length - 1; i >= 0; i--) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00006086 if (!hasPkgInfo) {
Todd Kennedy39bfee52016-02-24 10:28:21 -08006087 WeakReference<LoadedApk> ref = mPackages.get(packages[i]);
6088 if (ref != null && ref.get() != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00006089 hasPkgInfo = true;
Todd Kennedy39bfee52016-02-24 10:28:21 -08006090 } else {
6091 ref = mResourcePackages.get(packages[i]);
6092 if (ref != null && ref.get() != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00006093 hasPkgInfo = true;
Todd Kennedy39bfee52016-02-24 10:28:21 -08006094 }
6095 }
6096 }
6097 if (killApp) {
6098 mPackages.remove(packages[i]);
6099 mResourcePackages.remove(packages[i]);
6100 }
6101 }
6102 }
6103 break;
6104 }
Sudheer Shankacc6418f2016-10-13 12:03:44 -07006105 case ApplicationThreadConstants.PACKAGE_REPLACED:
Todd Kennedy39bfee52016-02-24 10:28:21 -08006106 {
6107 if (packages == null) {
6108 break;
6109 }
Winson23863be2019-04-04 17:41:28 -07006110
6111 List<String> packagesHandled = new ArrayList<>();
6112
Todd Kennedy39bfee52016-02-24 10:28:21 -08006113 synchronized (mResourcesManager) {
6114 for (int i = packages.length - 1; i >= 0; i--) {
Winson23863be2019-04-04 17:41:28 -07006115 String packageName = packages[i];
6116 WeakReference<LoadedApk> ref = mPackages.get(packageName);
Todd Kennedy233a0b12018-01-29 20:30:24 +00006117 LoadedApk pkgInfo = ref != null ? ref.get() : null;
6118 if (pkgInfo != null) {
6119 hasPkgInfo = true;
mark_chen89764e32014-12-12 15:38:48 +08006120 } else {
Winson23863be2019-04-04 17:41:28 -07006121 ref = mResourcePackages.get(packageName);
Todd Kennedy233a0b12018-01-29 20:30:24 +00006122 pkgInfo = ref != null ? ref.get() : null;
6123 if (pkgInfo != null) {
6124 hasPkgInfo = true;
mark_chen89764e32014-12-12 15:38:48 +08006125 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07006126 }
Todd Kennedy39bfee52016-02-24 10:28:21 -08006127 // If the package is being replaced, yet it still has a valid
6128 // LoadedApk object, the package was updated with _DONT_KILL.
6129 // Adjust it's internal references to the application info and
6130 // resources.
Todd Kennedy233a0b12018-01-29 20:30:24 +00006131 if (pkgInfo != null) {
Winson23863be2019-04-04 17:41:28 -07006132 packagesHandled.add(packageName);
Todd Kennedy39bfee52016-02-24 10:28:21 -08006133 try {
Todd Kennedy39bfee52016-02-24 10:28:21 -08006134 final ApplicationInfo aInfo =
6135 sPackageManager.getApplicationInfo(
6136 packageName,
Svet Ganov6ce92392017-09-27 16:04:10 -07006137 PackageManager.GET_SHARED_LIBRARY_FILES,
Todd Kennedy39bfee52016-02-24 10:28:21 -08006138 UserHandle.myUserId());
6139
6140 if (mActivities.size() > 0) {
6141 for (ActivityClientRecord ar : mActivities.values()) {
6142 if (ar.activityInfo.applicationInfo.packageName
6143 .equals(packageName)) {
6144 ar.activityInfo.applicationInfo = aInfo;
Todd Kennedy233a0b12018-01-29 20:30:24 +00006145 ar.packageInfo = pkgInfo;
Todd Kennedy39bfee52016-02-24 10:28:21 -08006146 }
6147 }
6148 }
Winsond605e2d2019-02-11 16:05:51 -08006149
6150 final String[] oldResDirs = { pkgInfo.getResDir() };
6151
Todd Kennedyb9656a92018-05-02 10:59:45 +01006152 final ArrayList<String> oldPaths = new ArrayList<>();
6153 LoadedApk.makePaths(this, pkgInfo.getApplicationInfo(), oldPaths);
Todd Kennedy233a0b12018-01-29 20:30:24 +00006154 pkgInfo.updateApplicationInfo(aInfo, oldPaths);
Winsond605e2d2019-02-11 16:05:51 -08006155
6156 synchronized (mResourcesManager) {
6157 // Update affected Resources objects to use new ResourcesImpl
6158 mResourcesManager.applyNewResourceDirsLocked(aInfo, oldResDirs);
6159 }
Todd Kennedy39bfee52016-02-24 10:28:21 -08006160 } catch (RemoteException e) {
6161 }
6162 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07006163 }
6164 }
Winson23863be2019-04-04 17:41:28 -07006165
6166 try {
6167 getPackageManager().notifyPackagesReplacedReceived(
6168 packagesHandled.toArray(new String[0]));
6169 } catch (RemoteException ignored) {
6170 }
6171
Todd Kennedy39bfee52016-02-24 10:28:21 -08006172 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07006173 }
6174 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00006175 ApplicationPackageManager.handlePackageBroadcast(cmd, packages, hasPkgInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07006176 }
Tim Murraye1e6c662015-04-07 13:24:14 -07006177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006178 final void handleLowMemory() {
Dianne Hackborn73c14162012-09-19 15:45:06 -07006179 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(true, null);
Bob Leee5408332009-09-04 18:31:17 -07006180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006181 final int N = callbacks.size();
6182 for (int i=0; i<N; i++) {
6183 callbacks.get(i).onLowMemory();
6184 }
6185
Chris Tatece229052009-03-25 16:44:52 -07006186 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
6187 if (Process.myUid() != Process.SYSTEM_UID) {
6188 int sqliteReleased = SQLiteDatabase.releaseMemory();
6189 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
6190 }
Bob Leee5408332009-09-04 18:31:17 -07006191
Mike Reedcaf0df12009-04-27 14:32:05 -04006192 // Ask graphics to free up as much as possible (font/image caches)
6193 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006194
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07006195 // Ask text layout engine to free also as much as possible
6196 Canvas.freeTextLayoutCaches();
6197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006198 BinderInternal.forceGc("mem");
6199 }
6200
Jorim Jaggib29e3182018-04-30 18:51:56 +02006201 private void handleTrimMemory(int level) {
6202 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "trimMemory");
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07006203 if (DEBUG_MEMORY_TRIM) Slog.v(TAG, "Trimming memory to level: " + level);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07006204
Dianne Hackborn73c14162012-09-19 15:45:06 -07006205 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(true, null);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07006206
6207 final int N = callbacks.size();
Romain Guya998dff2012-03-23 18:58:36 -07006208 for (int i = 0; i < N; i++) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07006209 callbacks.get(i).onTrimMemory(level);
6210 }
Romain Guy19f86e82012-04-23 15:19:07 -07006211
John Reckf47a5942014-06-30 16:20:04 -07006212 WindowManagerGlobal.getInstance().trimMemory(level);
Jorim Jaggib29e3182018-04-30 18:51:56 +02006213 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Makoto Onuki0a9ee1a2019-06-19 08:58:02 -07006214
6215 if (SystemProperties.getInt("debug.am.run_gc_trim_level", Integer.MAX_VALUE) <= level) {
6216 unscheduleGcIdler();
6217 doGcIfNeeded("tm");
6218 }
6219 if (SystemProperties.getInt("debug.am.run_mallopt_trim_level", Integer.MAX_VALUE)
6220 <= level) {
6221 unschedulePurgeIdler();
6222 purgePendingResources();
6223 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006224 }
6225
Jesse Hall317fa5a2017-05-23 15:46:55 -07006226 private void setupGraphicsSupport(Context context) {
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006227 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setupGraphicsSupport");
Romain Guya9582652011-11-10 14:20:10 -08006228
Jesse Hall317fa5a2017-05-23 15:46:55 -07006229 // The system package doesn't have real data directories, so don't set up cache paths.
6230 if (!"android".equals(context.getPackageName())) {
6231 // This cache location probably points at credential-encrypted
6232 // storage which may not be accessible yet; assign it anyway instead
6233 // of pointing at device-encrypted storage.
6234 final File cacheDir = context.getCacheDir();
6235 if (cacheDir != null) {
6236 // Provide a usable directory for temporary files
6237 System.setProperty("java.io.tmpdir", cacheDir.getAbsolutePath());
6238 } else {
6239 Log.v(TAG, "Unable to initialize \"java.io.tmpdir\" property "
6240 + "due to missing cache directory");
Romain Guya9582652011-11-10 14:20:10 -08006241 }
Jesse Hall317fa5a2017-05-23 15:46:55 -07006242
6243 // Setup a location to store generated/compiled graphics code.
6244 final Context deviceContext = context.createDeviceProtectedStorageContext();
6245 final File codeCacheDir = deviceContext.getCodeCacheDir();
6246 if (codeCacheDir != null) {
6247 try {
6248 int uid = Process.myUid();
6249 String[] packages = getPackageManager().getPackagesForUid(uid);
6250 if (packages != null) {
John Reck8785ceb2018-10-29 16:45:58 -07006251 HardwareRenderer.setupDiskCache(codeCacheDir);
Romain Guycecbe072017-07-18 15:42:06 -07006252 RenderScriptCacheDir.setupDiskCache(codeCacheDir);
Jesse Hall317fa5a2017-05-23 15:46:55 -07006253 }
6254 } catch (RemoteException e) {
6255 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6256 throw e.rethrowFromSystemServer();
6257 }
6258 } else {
6259 Log.w(TAG, "Unable to use shader/script cache: missing code-cache directory");
6260 }
Romain Guya9582652011-11-10 14:20:10 -08006261 }
Jesse Hall317fa5a2017-05-23 15:46:55 -07006262
Cody Northropdeb43282018-10-04 16:04:05 -06006263 GraphicsEnvironment.getInstance().setup(context, mCoreSettings);
Jesse Hall317fa5a2017-05-23 15:46:55 -07006264 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborndde331c2012-08-03 14:01:57 -07006265 }
6266
6267 private void updateDefaultDensity() {
Alan Viverette2ac46f12016-02-04 16:58:14 -05006268 final int densityDpi = mCurDefaultDisplayDpi;
6269 if (!mDensityCompatMode
6270 && densityDpi != Configuration.DENSITY_DPI_UNDEFINED
6271 && densityDpi != DisplayMetrics.DENSITY_DEVICE) {
6272 DisplayMetrics.DENSITY_DEVICE = densityDpi;
6273 Bitmap.setDefaultDensity(densityDpi);
Dianne Hackborndde331c2012-08-03 14:01:57 -07006274 }
6275 }
6276
Todd Kennedye713efc2016-05-10 13:45:40 -07006277 /**
6278 * Returns the correct library directory for the current ABI.
6279 * <p>
6280 * If we're dealing with a multi-arch application that has both 32 and 64 bit shared
6281 * libraries, we might need to choose the secondary depending on what the current
6282 * runtime's instruction set is.
6283 */
6284 private String getInstrumentationLibrary(ApplicationInfo appInfo, InstrumentationInfo insInfo) {
Patrick Baumanneb595802018-04-17 09:49:55 -07006285 if (appInfo.primaryCpuAbi != null && appInfo.secondaryCpuAbi != null
6286 && appInfo.secondaryCpuAbi.equals(insInfo.secondaryCpuAbi)) {
Todd Kennedye713efc2016-05-10 13:45:40 -07006287 // Get the instruction set supported by the secondary ABI. In the presence
6288 // of a native bridge this might be different than the one secondary ABI used.
6289 String secondaryIsa =
6290 VMRuntime.getInstructionSet(appInfo.secondaryCpuAbi);
6291 final String secondaryDexCodeIsa =
6292 SystemProperties.get("ro.dalvik.vm.isa." + secondaryIsa);
6293 secondaryIsa = secondaryDexCodeIsa.isEmpty() ? secondaryIsa : secondaryDexCodeIsa;
6294
6295 final String runtimeIsa = VMRuntime.getRuntime().vmInstructionSet();
6296 if (runtimeIsa.equals(secondaryIsa)) {
6297 return insInfo.secondaryNativeLibraryDir;
6298 }
6299 }
6300 return insInfo.nativeLibraryDir;
6301 }
6302
Adam Lesinskib61e4052016-05-19 18:23:05 -07006303 /**
6304 * The LocaleList set for the app's resources may have been shuffled so that the preferred
6305 * Locale is at position 0. We must find the index of this preferred Locale in the
6306 * original LocaleList.
6307 */
6308 private void updateLocaleListFromAppContext(Context context, LocaleList newLocaleList) {
6309 final Locale bestLocale = context.getResources().getConfiguration().getLocales().get(0);
6310 final int newLocaleListSize = newLocaleList.size();
6311 for (int i = 0; i < newLocaleListSize; i++) {
6312 if (bestLocale.equals(newLocaleList.get(i))) {
6313 LocaleList.setDefault(newLocaleList, i);
6314 return;
6315 }
6316 }
Adam Lesinski27d30162016-05-25 16:45:14 -07006317
6318 // The app may have overridden the LocaleList with its own Locale
6319 // (not present in the available list). Push the chosen Locale
6320 // to the front of the list.
6321 LocaleList.setDefault(new LocaleList(bestLocale, newLocaleList));
Adam Lesinskib61e4052016-05-19 18:23:05 -07006322 }
6323
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006324 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07006325 private void handleBindApplication(AppBindData data) {
Calin Juravle8f5770d2016-04-12 14:12:04 +01006326 // Register the UI Thread as a sensitive thread to the runtime.
6327 VMRuntime.registerSensitiveThread();
Mathieu Chartier90aa9452019-03-29 13:49:35 -07006328 // In the case the stack depth property exists, pass it down to the runtime.
6329 String property = SystemProperties.get("debug.allocTracker.stackDepth");
6330 if (property.length() != 0) {
6331 VMDebug.setAllocTrackerStackDepth(Integer.parseInt(property));
6332 }
Man Caocfa78b22015-06-11 20:14:34 -07006333 if (data.trackAllocation) {
6334 DdmVmInternal.enableRecentAllocations(true);
6335 }
Dianne Hackbornd98885c2016-03-01 17:13:03 -08006336 // Note when this process has started.
6337 Process.setStartTimes(SystemClock.elapsedRealtime(), SystemClock.uptimeMillis());
6338
Mathew Inwood80652db2019-06-24 12:07:22 +01006339 AppCompatCallbacks.install(data.disabledCompatChanges);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006340 mBoundApplication = data;
6341 mConfiguration = new Configuration(data.config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07006342 mCompatConfiguration = new Configuration(data.config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006343
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07006344 mProfiler = new Profiler();
Andreas Gampeab8a63b2018-01-05 13:55:15 -08006345 String agent = null;
Jeff Hao1b012d32014-08-20 10:35:34 -07006346 if (data.initProfilerInfo != null) {
6347 mProfiler.profileFile = data.initProfilerInfo.profileFile;
6348 mProfiler.profileFd = data.initProfilerInfo.profileFd;
6349 mProfiler.samplingInterval = data.initProfilerInfo.samplingInterval;
6350 mProfiler.autoStopProfiler = data.initProfilerInfo.autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -08006351 mProfiler.streamingOutput = data.initProfilerInfo.streamingOutput;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08006352 if (data.initProfilerInfo.attachAgentDuringBind) {
6353 agent = data.initProfilerInfo.agent;
6354 }
Jeff Hao1b012d32014-08-20 10:35:34 -07006355 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07006356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006357 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08006358 Process.setArgV0(data.processName);
Siva Velusamyd693dfa2012-09-10 14:36:58 -07006359 android.ddm.DdmHandleAppName.setAppName(data.processName,
Chester Hsiehab720ee2019-11-12 12:01:54 -08006360 data.appInfo.packageName,
Siva Velusamyd693dfa2012-09-10 14:36:58 -07006361 UserHandle.myUserId());
Mathew Inwood37b6ca82018-05-02 10:42:23 +01006362 VMRuntime.setProcessPackageName(data.appInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363
David Brazdil06f2e1292019-04-03 13:00:55 +01006364 // Pass data directory path to ART. This is used for caching information and
6365 // should be set before any application code is loaded.
6366 VMRuntime.setProcessDataDirectory(data.appInfo.dataDir);
6367
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07006368 if (mProfiler.profileFd != null) {
6369 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006370 }
6371
Joe Onoratod630f102011-03-17 18:42:26 -07006372 // If the app is Honeycomb MR1 or earlier, switch its AsyncTask
6373 // implementation to use the pool executor. Normally, we use the
6374 // serialized executor as the default. This has to happen in the
6375 // main thread so the main looper is set right.
Dianne Hackborn81e92762011-10-09 16:00:21 -07006376 if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
Joe Onoratod630f102011-03-17 18:42:26 -07006377 AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
6378 }
6379
Kweku Adams4be0b1a2019-04-25 16:16:34 -07006380 // Let the util.*Array classes maintain "undefined" for apps targeting Pie or earlier.
6381 UtilConfig.setThrowExceptionForUpperArrayOutOfBounds(
6382 data.appInfo.targetSdkVersion >= Build.VERSION_CODES.Q);
6383
Dianne Hackborn7895bc22014-09-05 15:09:03 -07006384 Message.updateCheckRecycle(data.appInfo.targetSdkVersion);
6385
Leon Scroggins III8290eab2018-03-19 10:51:44 -04006386 // Prior to P, internal calls to decode Bitmaps used BitmapFactory,
6387 // which may scale up to account for density. In P, we switched to
6388 // ImageDecoder, which skips the upscale to save memory. ImageDecoder
6389 // needs to still scale up in older apps, in case they rely on the
6390 // size of the Bitmap without considering its density.
6391 ImageDecoder.sApiLevel = data.appInfo.targetSdkVersion;
6392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006393 /*
6394 * Before spawning a new process, reset the time zone to be the system time zone.
6395 * This needs to be done because the system time zone could have changed after the
6396 * the spawning of this process. Without doing this this process would have the incorrect
6397 * system time zone.
6398 */
6399 TimeZone.setDefault(null);
6400
Adam Lesinskib61e4052016-05-19 18:23:05 -07006401 /*
6402 * Set the LocaleList. This may change once we create the App Context.
6403 */
6404 LocaleList.setDefault(data.config.getLocales());
6405
6406 synchronized (mResourcesManager) {
6407 /*
6408 * Update the system configuration since its preloaded and might not
6409 * reflect configuration changes. The configuration object passed
6410 * in AppBindData can be safely assumed to be up to date
6411 */
6412 mResourcesManager.applyConfigurationToResourcesLocked(data.config, data.compatInfo);
6413 mCurDefaultDisplayDpi = data.config.densityDpi;
6414
6415 // This calls mResourcesManager so keep it within the synchronized block.
6416 applyCompatConfiguration(mCurDefaultDisplayDpi);
6417 }
6418
Todd Kennedy233a0b12018-01-29 20:30:24 +00006419 data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006420
Andreas Gampeab8a63b2018-01-05 13:55:15 -08006421 if (agent != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00006422 handleAttachAgent(agent, data.info);
Andreas Gampeab8a63b2018-01-05 13:55:15 -08006423 }
6424
Dianne Hackborndde331c2012-08-03 14:01:57 -07006425 /**
6426 * Switch this process to density compatibility mode if needed.
6427 */
6428 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
6429 == 0) {
6430 mDensityCompatMode = true;
6431 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
6432 }
6433 updateDefaultDensity();
6434
Neil Fullerc66ec402016-11-14 16:06:42 +00006435 final String use24HourSetting = mCoreSettings.getString(Settings.System.TIME_12_24);
6436 Boolean is24Hr = null;
6437 if (use24HourSetting != null) {
6438 is24Hr = "24".equals(use24HourSetting) ? Boolean.TRUE : Boolean.FALSE;
6439 }
6440 // null : use locale default for 12/24 hour formatting,
6441 // false : use 12 hour format,
6442 // true : use 24 hour format.
Narayan Kamathccb2a0862013-12-19 14:49:36 +00006443 DateFormat.set24HourTimePref(is24Hr);
6444
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08006445 updateDebugViewAttributeState();
Jon Miranda836c0a82014-08-11 12:32:26 -07006446
Jeff Sharkey89182982017-11-01 19:02:56 -06006447 StrictMode.initThreadDefaults(data.appInfo);
6448 StrictMode.initVmDefaults(data.appInfo);
Jeff Sharkey344744b2016-01-28 19:03:30 -07006449
Sudheer Shankacc6418f2016-10-13 12:03:44 -07006450 if (data.debugMode != ApplicationThreadConstants.DEBUG_OFF) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006451 // XXX should have option to change the port.
6452 Debug.changeDebugPort(8100);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07006453 if (data.debugMode == ApplicationThreadConstants.DEBUG_WAIT) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00006454 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006455 + " is waiting for the debugger on port 8100...");
6456
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006457 IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006458 try {
6459 mgr.showWaitingForDebugger(mAppThread, true);
6460 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006461 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 }
6463
6464 Debug.waitForDebugger();
6465
6466 try {
6467 mgr.showWaitingForDebugger(mAppThread, false);
6468 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006469 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006470 }
6471
6472 } else {
Todd Kennedy233a0b12018-01-29 20:30:24 +00006473 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006474 + " can be debugged on port 8100...");
6475 }
6476 }
6477
Chris Craikce030282018-10-16 14:33:11 -07006478 // Allow binder tracing, and application-generated systrace messages if we're profileable.
6479 boolean isAppProfileable = data.appInfo.isProfileableByShell();
6480 Trace.setAppTracingAllowed(isAppProfileable);
Tim Murray6d2b1bf2020-05-11 10:26:01 -07006481 if ((isAppProfileable || Build.IS_DEBUGGABLE) && data.enableBinderTracking) {
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04006482 Binder.enableTracing();
6483 }
Jamie Gennisf9c7d6b2013-03-25 14:18:25 -07006484
Ryan Savitskicfdc1512018-12-14 16:20:52 +00006485 // Initialize heap profiling.
6486 if (isAppProfileable || Build.IS_DEBUGGABLE) {
6487 nInitZygoteChildHeapProfiling();
6488 }
6489
Chris Craikce030282018-10-16 14:33:11 -07006490 // Allow renderer debugging features if we're debuggable.
6491 boolean isAppDebuggable = (data.appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
John Reck8785ceb2018-10-29 16:45:58 -07006492 HardwareRenderer.setDebuggingEnabled(isAppDebuggable || Build.IS_DEBUGGABLE);
6493 HardwareRenderer.setPackageName(data.appInfo.packageName);
Chris Craikce030282018-10-16 14:33:11 -07006494
Robert Greenwalt434203a2010-10-11 16:00:27 -07006495 /**
6496 * Initialize the default http proxy in this process for the reasons we set the time zone.
6497 */
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006498 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Setup proxies");
Alan Viverettebe64eae2015-09-03 14:56:04 -04006499 final IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08006500 if (b != null) {
6501 // In pre-boot mode (doing initial launch to collect password), not
6502 // all system is up. This includes the connectivity service, so don't
6503 // crash if we can't get it.
Alan Viverettebe64eae2015-09-03 14:56:04 -04006504 final IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08006505 try {
Irina Dumitrescu18622d32018-12-05 16:19:47 +00006506 Proxy.setHttpProxySystemProperty(service.getProxyForNetwork(null));
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006507 } catch (RemoteException e) {
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006508 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006509 throw e.rethrowFromSystemServer();
6510 }
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08006511 }
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006512 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Robert Greenwalt434203a2010-10-11 16:00:27 -07006513
Alan Viverette2107d692015-09-03 14:55:27 -04006514 // Instrumentation info affects the class loader, so load it before
6515 // setting up the app context.
6516 final InstrumentationInfo ii;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006517 if (data.instrumentationName != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006518 try {
Todd Kennedy8f135982019-07-02 07:35:15 -07006519 ii = new ApplicationPackageManager(
6520 null, getPackageManager(), getPermissionManager())
Alan Viverette2107d692015-09-03 14:55:27 -04006521 .getInstrumentationInfo(data.instrumentationName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006522 } catch (PackageManager.NameNotFoundException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006523 throw new RuntimeException(
Alan Viverette2107d692015-09-03 14:55:27 -04006524 "Unable to find instrumentation info for: " + data.instrumentationName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006525 }
6526
Patrick Baumanneb595802018-04-17 09:49:55 -07006527 // Warn of potential ABI mismatches.
6528 if (!Objects.equals(data.appInfo.primaryCpuAbi, ii.primaryCpuAbi)
6529 || !Objects.equals(data.appInfo.secondaryCpuAbi, ii.secondaryCpuAbi)) {
6530 Slog.w(TAG, "Package uses different ABI(s) than its instrumentation: "
6531 + "package[" + data.appInfo.packageName + "]: "
6532 + data.appInfo.primaryCpuAbi + ", " + data.appInfo.secondaryCpuAbi
6533 + " instrumentation[" + ii.packageName + "]: "
6534 + ii.primaryCpuAbi + ", " + ii.secondaryCpuAbi);
6535 }
6536
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07006537 mInstrumentationPackageName = ii.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006538 mInstrumentationAppDir = ii.sourceDir;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07006539 mInstrumentationSplitAppDirs = ii.splitSourceDirs;
Todd Kennedye713efc2016-05-10 13:45:40 -07006540 mInstrumentationLibDir = getInstrumentationLibrary(data.appInfo, ii);
Todd Kennedy233a0b12018-01-29 20:30:24 +00006541 mInstrumentedAppDir = data.info.getAppDir();
6542 mInstrumentedSplitAppDirs = data.info.getSplitAppDirs();
6543 mInstrumentedLibDir = data.info.getLibDir();
Alan Viverette2107d692015-09-03 14:55:27 -04006544 } else {
6545 ii = null;
6546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006547
Todd Kennedy233a0b12018-01-29 20:30:24 +00006548 final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
Adam Lesinskib61e4052016-05-19 18:23:05 -07006549 updateLocaleListFromAppContext(appContext,
6550 mResourcesManager.getConfiguration().getLocales());
Seigo Nonakac14dd782016-03-30 23:09:16 +09006551
Jesse Hall317fa5a2017-05-23 15:46:55 -07006552 if (!Process.isIsolated()) {
Jeff Sharkey89182982017-11-01 19:02:56 -06006553 final int oldMask = StrictMode.allowThreadDiskWritesMask();
6554 try {
6555 setupGraphicsSupport(appContext);
6556 } finally {
6557 StrictMode.setThreadPolicyMask(oldMask);
6558 }
John Reck56428472018-03-16 17:27:17 -07006559 } else {
John Reck8785ceb2018-10-29 16:45:58 -07006560 HardwareRenderer.setIsolatedProcess(true);
Michael Lentine2ba303f2016-02-01 20:44:34 -06006561 }
Michael Lentine03d8f7682016-01-31 15:37:11 -06006562
Chad Brubaker78d47122015-11-17 22:26:58 -08006563 // Install the Network Security Config Provider. This must happen before the application
6564 // code is loaded to prevent issues with instances of TLS objects being created before
6565 // the provider is installed.
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006566 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "NetworkSecurityConfigProvider.install");
Chad Brubaker276ee962016-06-08 12:57:46 -07006567 NetworkSecurityConfigProvider.install(appContext);
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006568 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Chad Brubaker78d47122015-11-17 22:26:58 -08006569
Alan Viverette2107d692015-09-03 14:55:27 -04006570 // Continue loading instrumentation.
6571 if (ii != null) {
Dianne Hackbornf4ef6eb2017-12-07 13:57:21 -08006572 ApplicationInfo instrApp;
6573 try {
6574 instrApp = getPackageManager().getApplicationInfo(ii.packageName, 0,
6575 UserHandle.myUserId());
6576 } catch (RemoteException e) {
6577 instrApp = null;
6578 }
6579 if (instrApp == null) {
6580 instrApp = new ApplicationInfo();
6581 }
Jeff Sharkey15447792015-11-05 16:18:51 -08006582 ii.copyTo(instrApp);
Fyodor Kupolovaf38b8e2015-12-02 16:16:07 -08006583 instrApp.initForUser(UserHandle.myUserId());
Todd Kennedy233a0b12018-01-29 20:30:24 +00006584 final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07006585 appContext.getClassLoader(), false, true, false);
Makoto Onuki4becc352019-01-30 13:30:41 -08006586
6587 // The test context's op package name == the target app's op package name, because
6588 // the app ops manager checks the op package name against the real calling UID,
6589 // which is what the target package name is associated with.
6590 final ContextImpl instrContext = ContextImpl.createAppContext(this, pi,
6591 appContext.getOpPackageName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006592
6593 try {
Alan Viverettebe64eae2015-09-03 14:56:04 -04006594 final ClassLoader cl = instrContext.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04006595 mInstrumentation = (Instrumentation)
6596 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006597 } catch (Exception e) {
6598 throw new RuntimeException(
6599 "Unable to instantiate instrumentation "
6600 + data.instrumentationName + ": " + e.toString(), e);
6601 }
6602
Alan Viverettebe64eae2015-09-03 14:56:04 -04006603 final ComponentName component = new ComponentName(ii.packageName, ii.name);
6604 mInstrumentation.init(this, instrContext, appContext, component,
6605 data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006606
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07006607 if (mProfiler.profileFile != null && !ii.handleProfiling
6608 && mProfiler.profileFd == null) {
6609 mProfiler.handlingProfiling = true;
Alan Viverettebe64eae2015-09-03 14:56:04 -04006610 final File file = new File(mProfiler.profileFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006611 file.getParentFile().mkdirs();
6612 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
6613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614 } else {
6615 mInstrumentation = new Instrumentation();
Jason Monka80bfb52017-11-16 17:15:37 -05006616 mInstrumentation.basicInit(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006617 }
6618
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08006619 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
Dianne Hackbornde398512011-01-18 18:45:21 -08006620 dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
Mathieu Chartier24cee072015-01-08 14:42:20 -08006621 } else {
6622 // Small heap, clamp to the current growth limit and let the heap release
6623 // pages after the growth limit to the non growth limit capacity. b/18387825
6624 dalvik.system.VMRuntime.getRuntime().clampGrowthLimit();
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08006625 }
6626
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006627 // Allow disk access during application and provider setup. This could
Jeff Sharkey7c501672012-02-28 12:08:37 -08006628 // block processing ordered broadcasts, but later processing would
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006629 // probably end up doing the same disk access.
Kurt Nelson5e154362017-06-29 17:20:56 -07006630 Application app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08006631 final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
Kurt Nelson571c3f62017-07-10 11:09:04 -07006632 final StrictMode.ThreadPolicy writesAllowedPolicy = StrictMode.getThreadPolicy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006633 try {
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006634 // If the app is being launched for full backup or restore, bring it up in
6635 // a restricted environment with the base application class.
Todd Kennedy233a0b12018-01-29 20:30:24 +00006636 app = data.info.makeApplication(data.restrictedBackupMode, null);
Svetoslav Ganov24c90452017-12-27 15:17:14 -08006637
6638 // Propagate autofill compat state
Felipe Lemea4f39cd2019-02-19 15:08:59 -08006639 app.setAutofillOptions(data.autofillOptions);
Svetoslav Ganov24c90452017-12-27 15:17:14 -08006640
Felipe Leme326f15a2019-02-19 09:42:24 -08006641 // Propagate Content Capture options
6642 app.setContentCaptureOptions(data.contentCaptureOptions);
6643
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006644 mInitialApplication = app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08006645
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006646 // don't bring up providers in restricted mode; they may depend on the
6647 // app's custom Application class
6648 if (!data.restrictedBackupMode) {
Jeff Sharkey3e195892016-03-05 19:48:59 -07006649 if (!ArrayUtils.isEmpty(data.providers)) {
6650 installContentProviders(app, data.providers);
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006651 }
6652 }
6653
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006654 // Do this after providers, since instrumentation tests generally start their
6655 // test thread at this point, and we don't want that racing.
6656 try {
6657 mInstrumentation.onCreate(data.instrumentationArgs);
6658 }
6659 catch (Exception e) {
6660 throw new RuntimeException(
6661 "Exception thrown in onCreate() of "
6662 + data.instrumentationName + ": " + e.toString(), e);
6663 }
Kurt Nelson571c3f62017-07-10 11:09:04 -07006664 try {
6665 mInstrumentation.callApplicationOnCreate(app);
6666 } catch (Exception e) {
6667 if (!mInstrumentation.onException(app, e)) {
6668 throw new RuntimeException(
6669 "Unable to create application " + app.getClass().getName()
6670 + ": " + e.toString(), e);
6671 }
6672 }
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006673 } finally {
Kurt Nelson571c3f62017-07-10 11:09:04 -07006674 // If the app targets < O-MR1, or doesn't change the thread policy
6675 // during startup, clobber the policy to maintain behavior of b/36951662
Jeff Sharkeyaa1a9112018-04-10 15:18:12 -06006676 if (data.appInfo.targetSdkVersion < Build.VERSION_CODES.O_MR1
Kurt Nelson571c3f62017-07-10 11:09:04 -07006677 || StrictMode.getThreadPolicy().equals(writesAllowedPolicy)) {
6678 StrictMode.setThreadPolicy(savedPolicy);
Kurt Nelson5e154362017-06-29 17:20:56 -07006679 }
6680 }
6681
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00006682 // Preload fonts resources
Seigo Nonaka54084b62017-04-24 14:46:23 -07006683 FontsContract.setApplicationContextForResources(appContext);
Torne (Richard Coles)85ecae52018-01-30 18:13:00 -05006684 if (!Process.isIsolated()) {
6685 try {
6686 final ApplicationInfo info =
6687 getPackageManager().getApplicationInfo(
6688 data.appInfo.packageName,
6689 PackageManager.GET_META_DATA /*flags*/,
6690 UserHandle.myUserId());
6691 if (info.metaData != null) {
6692 final int preloadedFontsResource = info.metaData.getInt(
6693 ApplicationInfo.METADATA_PRELOADED_FONTS, 0);
6694 if (preloadedFontsResource != 0) {
6695 data.info.getResources().preloadFonts(preloadedFontsResource);
6696 }
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00006697 }
Torne (Richard Coles)85ecae52018-01-30 18:13:00 -05006698 } catch (RemoteException e) {
6699 throw e.rethrowFromSystemServer();
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00006700 }
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00006701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006702 }
6703
6704 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006705 IActivityManager am = ActivityManager.getService();
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07006706 if (mProfiler.profileFile != null && mProfiler.handlingProfiling
6707 && mProfiler.profileFd == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006708 Debug.stopMethodTracing();
6709 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006710 //Slog.i(TAG, "am: " + ActivityManager.getService()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006711 // + ", app thr: " + mAppThread);
6712 try {
6713 am.finishInstrumentation(mAppThread, resultCode, results);
6714 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006715 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006716 }
6717 }
6718
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006719 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07006720 private void installContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006721 Context context, List<ProviderInfo> providers) {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006722 final ArrayList<ContentProviderHolder> results = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006723
Romain Guya998dff2012-03-23 18:58:36 -07006724 for (ProviderInfo cpi : providers) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08006725 if (DEBUG_PROVIDER) {
6726 StringBuilder buf = new StringBuilder(128);
6727 buf.append("Pub ");
6728 buf.append(cpi.authority);
6729 buf.append(": ");
6730 buf.append(cpi.name);
6731 Log.i(TAG, buf.toString());
6732 }
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006733 ContentProviderHolder cph = installProvider(context, null, cpi,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006734 false /*noisy*/, true /*noReleaseNeeded*/, true /*stable*/);
6735 if (cph != null) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006736 cph.noReleaseNeeded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006737 results.add(cph);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006738 }
6739 }
6740
6741 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006742 ActivityManager.getService().publishContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006743 getApplicationThread(), results);
6744 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006745 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006746 }
6747 }
6748
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006749 @UnsupportedAppUsage
Jeff Sharkey6d515712012-09-20 16:06:08 -07006750 public final IContentProvider acquireProvider(
6751 Context c, String auth, int userId, boolean stable) {
Wale Ogunwale1d646122015-04-24 14:45:14 -07006752 final IContentProvider provider = acquireExistingProvider(c, auth, userId, stable);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006753 if (provider != null) {
6754 return provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006755 }
6756
Wale Ogunwale1d646122015-04-24 14:45:14 -07006757 // There is a possible race here. Another thread may try to acquire
6758 // the same provider at the same time. When this happens, we want to ensure
6759 // that the first one wins.
6760 // Note that we cannot hold the lock while acquiring and installing the
6761 // provider since it might take a long time to run and it could also potentially
6762 // be re-entrant in the case where the provider is in the same process.
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006763 ContentProviderHolder holder = null;
Wale Ogunwale1d646122015-04-24 14:45:14 -07006764 try {
Makoto Onukib6c79ea2018-05-31 11:03:56 -07006765 synchronized (getGetProviderLock(auth, userId)) {
6766 holder = ActivityManager.getService().getContentProvider(
Dianne Hackborn24bbe582018-12-17 11:58:31 -08006767 getApplicationThread(), c.getOpPackageName(), auth, userId, stable);
Makoto Onukib6c79ea2018-05-31 11:03:56 -07006768 }
Wale Ogunwale1d646122015-04-24 14:45:14 -07006769 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006770 throw ex.rethrowFromSystemServer();
Wale Ogunwale67fe0a42015-04-24 14:44:54 -07006771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006772 if (holder == null) {
Jeff Sharkey6d515712012-09-20 16:06:08 -07006773 Slog.e(TAG, "Failed to find provider info for " + auth);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006774 return null;
6775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006776
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006777 // Install provider will increment the reference count for us, and break
6778 // any ties in the race.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006779 holder = installProvider(c, holder, holder.info,
6780 true /*noisy*/, holder.noReleaseNeeded, stable);
6781 return holder.provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006782 }
6783
Makoto Onukib6c79ea2018-05-31 11:03:56 -07006784 private Object getGetProviderLock(String auth, int userId) {
6785 final ProviderKey key = new ProviderKey(auth, userId);
6786 synchronized (mGetProviderLocks) {
6787 Object lock = mGetProviderLocks.get(key);
6788 if (lock == null) {
6789 lock = key;
6790 mGetProviderLocks.put(key, lock);
6791 }
6792 return lock;
6793 }
6794 }
6795
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006796 private final void incProviderRefLocked(ProviderRefCount prc, boolean stable) {
6797 if (stable) {
6798 prc.stableCount += 1;
6799 if (prc.stableCount == 1) {
6800 // We are acquiring a new stable reference on the provider.
6801 int unstableDelta;
6802 if (prc.removePending) {
6803 // We have a pending remove operation, which is holding the
6804 // last unstable reference. At this point we are converting
6805 // that unstable reference to our new stable reference.
6806 unstableDelta = -1;
6807 // Cancel the removal of the provider.
6808 if (DEBUG_PROVIDER) {
6809 Slog.v(TAG, "incProviderRef: stable "
6810 + "snatched provider from the jaws of death");
6811 }
6812 prc.removePending = false;
Guobin Zhang9e3e52662013-03-21 13:57:11 +08006813 // There is a race! It fails to remove the message, which
6814 // will be handled in completeRemoveProvider().
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006815 mH.removeMessages(H.REMOVE_PROVIDER, prc);
6816 } else {
6817 unstableDelta = 0;
6818 }
6819 try {
6820 if (DEBUG_PROVIDER) {
6821 Slog.v(TAG, "incProviderRef Now stable - "
6822 + prc.holder.info.name + ": unstableDelta="
6823 + unstableDelta);
6824 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006825 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006826 prc.holder.connection, 1, unstableDelta);
6827 } catch (RemoteException e) {
6828 //do nothing content provider object is dead any way
6829 }
6830 }
6831 } else {
6832 prc.unstableCount += 1;
6833 if (prc.unstableCount == 1) {
6834 // We are acquiring a new unstable reference on the provider.
6835 if (prc.removePending) {
6836 // Oh look, we actually have a remove pending for the
6837 // provider, which is still holding the last unstable
6838 // reference. We just need to cancel that to take new
6839 // ownership of the reference.
6840 if (DEBUG_PROVIDER) {
6841 Slog.v(TAG, "incProviderRef: unstable "
6842 + "snatched provider from the jaws of death");
6843 }
6844 prc.removePending = false;
6845 mH.removeMessages(H.REMOVE_PROVIDER, prc);
6846 } else {
6847 // First unstable ref, increment our count in the
6848 // activity manager.
6849 try {
6850 if (DEBUG_PROVIDER) {
6851 Slog.v(TAG, "incProviderRef: Now unstable - "
6852 + prc.holder.info.name);
6853 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006854 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006855 prc.holder.connection, 0, 1);
6856 } catch (RemoteException e) {
6857 //do nothing content provider object is dead any way
6858 }
6859 }
6860 }
6861 }
6862 }
6863
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006864 @UnsupportedAppUsage
Jeff Sharkey6d515712012-09-20 16:06:08 -07006865 public final IContentProvider acquireExistingProvider(
6866 Context c, String auth, int userId, boolean stable) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006867 synchronized (mProviderMap) {
Wale Ogunwale1d646122015-04-24 14:45:14 -07006868 final ProviderKey key = new ProviderKey(auth, userId);
Jeff Sharkey6d515712012-09-20 16:06:08 -07006869 final ProviderClientRecord pr = mProviderMap.get(key);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006870 if (pr == null) {
6871 return null;
6872 }
6873
6874 IContentProvider provider = pr.mProvider;
6875 IBinder jBinder = provider.asBinder();
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006876 if (!jBinder.isBinderAlive()) {
6877 // The hosting process of the provider has died; we can't
6878 // use this one.
Wale Ogunwale1d646122015-04-24 14:45:14 -07006879 Log.i(TAG, "Acquiring provider " + auth + " for user " + userId
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006880 + ": existing object's process dead");
6881 handleUnstableProviderDiedLocked(jBinder, true);
6882 return null;
6883 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006884
6885 // Only increment the ref count if we have one. If we don't then the
6886 // provider is not reference counted and never needs to be released.
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006887 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006888 if (prc != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006889 incProviderRefLocked(prc, stable);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006890 }
6891 return provider;
6892 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006893 }
6894
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006895 @UnsupportedAppUsage
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006896 public final boolean releaseProvider(IContentProvider provider, boolean stable) {
6897 if (provider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006898 return false;
6899 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006901 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006902 synchronized (mProviderMap) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006903 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006904 if (prc == null) {
6905 // The provider has no ref count, no release is needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006906 return false;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006907 }
6908
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006909 boolean lastRef = false;
6910 if (stable) {
6911 if (prc.stableCount == 0) {
6912 if (DEBUG_PROVIDER) Slog.v(TAG,
6913 "releaseProvider: stable ref count already 0, how?");
6914 return false;
6915 }
6916 prc.stableCount -= 1;
6917 if (prc.stableCount == 0) {
6918 // What we do at this point depends on whether there are
6919 // any unstable refs left: if there are, we just tell the
6920 // activity manager to decrement its stable count; if there
6921 // aren't, we need to enqueue this provider to be removed,
6922 // and convert to holding a single unstable ref while
6923 // doing so.
6924 lastRef = prc.unstableCount == 0;
6925 try {
6926 if (DEBUG_PROVIDER) {
6927 Slog.v(TAG, "releaseProvider: No longer stable w/lastRef="
6928 + lastRef + " - " + prc.holder.info.name);
6929 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006930 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006931 prc.holder.connection, -1, lastRef ? 1 : 0);
6932 } catch (RemoteException e) {
6933 //do nothing content provider object is dead any way
6934 }
6935 }
6936 } else {
6937 if (prc.unstableCount == 0) {
6938 if (DEBUG_PROVIDER) Slog.v(TAG,
6939 "releaseProvider: unstable ref count already 0, how?");
6940 return false;
6941 }
6942 prc.unstableCount -= 1;
6943 if (prc.unstableCount == 0) {
6944 // If this is the last reference, we need to enqueue
6945 // this provider to be removed instead of telling the
6946 // activity manager to remove it at this point.
6947 lastRef = prc.stableCount == 0;
6948 if (!lastRef) {
6949 try {
6950 if (DEBUG_PROVIDER) {
6951 Slog.v(TAG, "releaseProvider: No longer unstable - "
6952 + prc.holder.info.name);
6953 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006954 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006955 prc.holder.connection, 0, -1);
6956 } catch (RemoteException e) {
6957 //do nothing content provider object is dead any way
6958 }
6959 }
6960 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006961 }
6962
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006963 if (lastRef) {
6964 if (!prc.removePending) {
6965 // Schedule the actual remove asynchronously, since we don't know the context
6966 // this will be called in.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006967 if (DEBUG_PROVIDER) {
6968 Slog.v(TAG, "releaseProvider: Enqueueing pending removal - "
6969 + prc.holder.info.name);
6970 }
6971 prc.removePending = true;
6972 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, prc);
Riddle Hsu4e8e3b02019-04-12 17:37:10 +08006973 mH.sendMessageDelayed(msg, CONTENT_PROVIDER_RETAIN_TIME);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006974 } else {
6975 Slog.w(TAG, "Duplicate remove pending of provider " + prc.holder.info.name);
6976 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006977 }
6978 return true;
6979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006980 }
6981
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006982 final void completeRemoveProvider(ProviderRefCount prc) {
6983 synchronized (mProviderMap) {
6984 if (!prc.removePending) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006985 // There was a race! Some other client managed to acquire
6986 // the provider before the removal was completed.
6987 // Abort the removal. We will do it later.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006988 if (DEBUG_PROVIDER) Slog.v(TAG, "completeRemoveProvider: lost the race, "
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006989 + "provider still in use");
6990 return;
6991 }
6992
Guobin Zhang9e3e52662013-03-21 13:57:11 +08006993 // More complicated race!! Some client managed to acquire the
6994 // provider and release it before the removal was completed.
6995 // Continue the removal, and abort the next remove message.
6996 prc.removePending = false;
6997
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006998 final IBinder jBinder = prc.holder.provider.asBinder();
6999 ProviderRefCount existingPrc = mProviderRefCountMap.get(jBinder);
7000 if (existingPrc == prc) {
7001 mProviderRefCountMap.remove(jBinder);
7002 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007003
Dianne Hackbornadd005c2013-07-17 18:43:12 -07007004 for (int i=mProviderMap.size()-1; i>=0; i--) {
7005 ProviderClientRecord pr = mProviderMap.valueAt(i);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007006 IBinder myBinder = pr.mProvider.asBinder();
7007 if (myBinder == jBinder) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07007008 mProviderMap.removeAt(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007009 }
7010 }
7011 }
7012
7013 try {
7014 if (DEBUG_PROVIDER) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08007015 Slog.v(TAG, "removeProvider: Invoking ActivityManagerService."
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007016 + "removeContentProvider(" + prc.holder.info.name + ")");
7017 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08007018 ActivityManager.getService().removeContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007019 prc.holder.connection, false);
7020 } catch (RemoteException e) {
7021 //do nothing content provider object is dead any way
7022 }
7023 }
7024
Mathew Inwood61e8ae62018-08-14 14:17:44 +01007025 @UnsupportedAppUsage
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007026 final void handleUnstableProviderDied(IBinder provider, boolean fromClient) {
Dianne Hackbornc428aae2012-10-03 16:38:22 -07007027 synchronized (mProviderMap) {
7028 handleUnstableProviderDiedLocked(provider, fromClient);
7029 }
7030 }
7031
7032 final void handleUnstableProviderDiedLocked(IBinder provider, boolean fromClient) {
7033 ProviderRefCount prc = mProviderRefCountMap.get(provider);
7034 if (prc != null) {
7035 if (DEBUG_PROVIDER) Slog.v(TAG, "Cleaning up dead provider "
7036 + provider + " " + prc.holder.info.name);
7037 mProviderRefCountMap.remove(provider);
You Kimbc74de62013-10-01 00:13:26 +09007038 for (int i=mProviderMap.size()-1; i>=0; i--) {
7039 ProviderClientRecord pr = mProviderMap.valueAt(i);
7040 if (pr != null && pr.mProvider.asBinder() == provider) {
7041 Slog.i(TAG, "Removing dead content provider:" + pr.mProvider.toString());
7042 mProviderMap.removeAt(i);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007043 }
Dianne Hackbornc428aae2012-10-03 16:38:22 -07007044 }
You Kimbc74de62013-10-01 00:13:26 +09007045
Dianne Hackbornc428aae2012-10-03 16:38:22 -07007046 if (fromClient) {
7047 // We found out about this due to execution in our client
7048 // code. Tell the activity manager about it now, to ensure
7049 // that the next time we go to do anything with the provider
7050 // it knows it is dead (so we don't race with its death
7051 // notification).
7052 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08007053 ActivityManager.getService().unstableProviderDied(
Dianne Hackbornc428aae2012-10-03 16:38:22 -07007054 prc.holder.connection);
7055 } catch (RemoteException e) {
7056 //do nothing content provider object is dead any way
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007057 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07007058 }
7059 }
7060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007061
Jeff Sharkey7aa76012013-09-30 14:26:27 -07007062 final void appNotRespondingViaProvider(IBinder provider) {
7063 synchronized (mProviderMap) {
7064 ProviderRefCount prc = mProviderRefCountMap.get(provider);
7065 if (prc != null) {
7066 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08007067 ActivityManager.getService()
Jeff Sharkey7aa76012013-09-30 14:26:27 -07007068 .appNotRespondingViaProvider(prc.holder.connection);
7069 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07007070 throw e.rethrowFromSystemServer();
Jeff Sharkey7aa76012013-09-30 14:26:27 -07007071 }
7072 }
7073 }
7074 }
7075
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007076 private ProviderClientRecord installProviderAuthoritiesLocked(IContentProvider provider,
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07007077 ContentProvider localProvider, ContentProviderHolder holder) {
Andreas Gampe18e99c12015-03-06 15:29:06 -08007078 final String auths[] = holder.info.authority.split(";");
Jeff Sharkey6d515712012-09-20 16:06:08 -07007079 final int userId = UserHandle.getUserId(holder.info.applicationInfo.uid);
7080
Jeff Sharkey0a17db12016-11-04 11:23:46 -06007081 if (provider != null) {
7082 // If this provider is hosted by the core OS and cannot be upgraded,
7083 // then I guess we're okay doing blocking calls to it.
7084 for (String auth : auths) {
7085 switch (auth) {
7086 case ContactsContract.AUTHORITY:
7087 case CallLog.AUTHORITY:
7088 case CallLog.SHADOW_AUTHORITY:
7089 case BlockedNumberContract.AUTHORITY:
7090 case CalendarContract.AUTHORITY:
7091 case Downloads.Impl.AUTHORITY:
Jeff Sharkeycb621622016-11-11 14:04:32 -07007092 case "telephony":
Jeff Sharkey0a17db12016-11-04 11:23:46 -06007093 Binder.allowBlocking(provider.asBinder());
7094 }
7095 }
7096 }
7097
Jeff Sharkey6d515712012-09-20 16:06:08 -07007098 final ProviderClientRecord pcr = new ProviderClientRecord(
7099 auths, provider, localProvider, holder);
7100 for (String auth : auths) {
7101 final ProviderKey key = new ProviderKey(auth, userId);
7102 final ProviderClientRecord existing = mProviderMap.get(key);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007103 if (existing != null) {
7104 Slog.w(TAG, "Content provider " + pcr.mHolder.info.name
Jeff Sharkey6d515712012-09-20 16:06:08 -07007105 + " already published as " + auth);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007106 } else {
Jeff Sharkey6d515712012-09-20 16:06:08 -07007107 mProviderMap.put(key, pcr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007108 }
7109 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007110 return pcr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007111 }
7112
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007113 /**
7114 * Installs the provider.
7115 *
7116 * Providers that are local to the process or that come from the system server
7117 * may be installed permanently which is indicated by setting noReleaseNeeded to true.
7118 * Other remote providers are reference counted. The initial reference count
7119 * for all reference counted providers is one. Providers that are not reference
7120 * counted do not have a reference count (at all).
7121 *
7122 * This method detects when a provider has already been installed. When this happens,
7123 * it increments the reference count of the existing provider (if appropriate)
7124 * and returns the existing provider. This can happen due to concurrent
7125 * attempts to acquire the same provider.
7126 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01007127 @UnsupportedAppUsage
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07007128 private ContentProviderHolder installProvider(Context context,
7129 ContentProviderHolder holder, ProviderInfo info,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007130 boolean noisy, boolean noReleaseNeeded, boolean stable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007131 ContentProvider localProvider = null;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007132 IContentProvider provider;
Dianne Hackborn5f48fca2012-05-30 11:06:31 -07007133 if (holder == null || holder.provider == null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007134 if (DEBUG_PROVIDER || noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07007135 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007136 + info.name);
7137 }
7138 Context c = null;
7139 ApplicationInfo ai = info.applicationInfo;
7140 if (context.getPackageName().equals(ai.packageName)) {
7141 c = context;
7142 } else if (mInitialApplication != null &&
7143 mInitialApplication.getPackageName().equals(ai.packageName)) {
7144 c = mInitialApplication;
7145 } else {
7146 try {
7147 c = context.createPackageContext(ai.packageName,
7148 Context.CONTEXT_INCLUDE_CODE);
7149 } catch (PackageManager.NameNotFoundException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07007150 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007151 }
7152 }
7153 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08007154 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007155 ai.packageName +
7156 " while loading content provider " +
7157 info.name);
7158 return null;
7159 }
Adam Lesinski4e862812016-11-21 16:02:24 -08007160
7161 if (info.splitName != null) {
7162 try {
7163 c = c.createContextForSplit(info.splitName);
7164 } catch (NameNotFoundException e) {
7165 throw new RuntimeException(e);
7166 }
7167 }
7168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007169 try {
7170 final java.lang.ClassLoader cl = c.getClassLoader();
Todd Kennedy233a0b12018-01-29 20:30:24 +00007171 LoadedApk packageInfo = peekPackageInfo(ai.packageName, true);
7172 if (packageInfo == null) {
Jason Monka80bfb52017-11-16 17:15:37 -05007173 // System startup case.
Todd Kennedy233a0b12018-01-29 20:30:24 +00007174 packageInfo = getSystemContext().mPackageInfo;
Jason Monka80bfb52017-11-16 17:15:37 -05007175 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00007176 localProvider = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05007177 .instantiateProvider(cl, info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007178 provider = localProvider.getIContentProvider();
7179 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08007180 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007181 info.name + " from sourceDir " +
7182 info.applicationInfo.sourceDir);
7183 return null;
7184 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007185 if (DEBUG_PROVIDER) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007186 TAG, "Instantiating local provider " + info.name);
7187 // XXX Need to create the correct context for this provider.
7188 localProvider.attachInfo(c, info);
7189 } catch (java.lang.Exception e) {
7190 if (!mInstrumentation.onException(null, e)) {
7191 throw new RuntimeException(
7192 "Unable to get provider " + info.name
7193 + ": " + e.toString(), e);
7194 }
7195 return null;
7196 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007197 } else {
7198 provider = holder.provider;
7199 if (DEBUG_PROVIDER) Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007200 + info.name);
7201 }
7202
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07007203 ContentProviderHolder retHolder;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007204
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007205 synchronized (mProviderMap) {
7206 if (DEBUG_PROVIDER) Slog.v(TAG, "Checking to add " + provider
7207 + " / " + info.name);
7208 IBinder jBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007209 if (localProvider != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007210 ComponentName cname = new ComponentName(info.packageName, info.name);
7211 ProviderClientRecord pr = mLocalProvidersByName.get(cname);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007212 if (pr != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007213 if (DEBUG_PROVIDER) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007214 Slog.v(TAG, "installProvider: lost the race, "
7215 + "using existing local provider");
7216 }
7217 provider = pr.mProvider;
7218 } else {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07007219 holder = new ContentProviderHolder(info);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007220 holder.provider = provider;
7221 holder.noReleaseNeeded = true;
7222 pr = installProviderAuthoritiesLocked(provider, localProvider, holder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007223 mLocalProviders.put(jBinder, pr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007224 mLocalProvidersByName.put(cname, pr);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007225 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007226 retHolder = pr.mHolder;
7227 } else {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007228 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
7229 if (prc != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007230 if (DEBUG_PROVIDER) {
7231 Slog.v(TAG, "installProvider: lost the race, updating ref count");
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007232 }
Wale Ogunwale1d646122015-04-24 14:45:14 -07007233 // We need to transfer our new reference to the existing
7234 // ref count, releasing the old one... but only if
7235 // release is needed (that is, it is not running in the
7236 // system process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007237 if (!noReleaseNeeded) {
7238 incProviderRefLocked(prc, stable);
Wale Ogunwale1d646122015-04-24 14:45:14 -07007239 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08007240 ActivityManager.getService().removeContentProvider(
Wale Ogunwale1d646122015-04-24 14:45:14 -07007241 holder.connection, stable);
7242 } catch (RemoteException e) {
7243 //do nothing content provider object is dead any way
7244 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007245 }
7246 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007247 ProviderClientRecord client = installProviderAuthoritiesLocked(
7248 provider, localProvider, holder);
7249 if (noReleaseNeeded) {
7250 prc = new ProviderRefCount(holder, client, 1000, 1000);
7251 } else {
7252 prc = stable
7253 ? new ProviderRefCount(holder, client, 1, 0)
7254 : new ProviderRefCount(holder, client, 0, 1);
7255 }
7256 mProviderRefCountMap.put(jBinder, prc);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007257 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007258 retHolder = prc.holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007259 }
7260 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007261 return retHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007262 }
7263
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04007264 private void handleRunIsolatedEntryPoint(String entryPoint, String[] entryPointArgs) {
7265 try {
7266 Method main = Class.forName(entryPoint).getMethod("main", String[].class);
7267 main.invoke(null, new Object[]{entryPointArgs});
7268 } catch (ReflectiveOperationException e) {
7269 throw new AndroidRuntimeException("runIsolatedEntryPoint failed", e);
7270 }
7271 // The process will be empty after this method returns; exit the VM now.
7272 System.exit(0);
7273 }
7274
Mathew Inwood61e8ae62018-08-14 14:17:44 +01007275 @UnsupportedAppUsage
Sudheer Shankaf6690102017-10-16 10:20:32 -07007276 private void attach(boolean system, long startSeq) {
Jeff Sharkey66a017b2013-01-17 18:18:22 -08007277 sCurrentActivityThread = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007278 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007279 if (!system) {
Siva Velusamyd693dfa2012-09-10 14:36:58 -07007280 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
7281 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007282 RuntimeInit.setApplicationObject(mAppThread.asBinder());
Sudheer Shankadc589ac2016-11-10 15:30:17 -08007283 final IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007284 try {
Sudheer Shankaf6690102017-10-16 10:20:32 -07007285 mgr.attachApplication(mAppThread, startSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007286 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07007287 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007288 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07007289 // Watch for getting close to heap limit.
7290 BinderInternal.addGcWatcher(new Runnable() {
7291 @Override public void run() {
7292 if (!mSomeActivitiesChanged) {
7293 return;
7294 }
7295 Runtime runtime = Runtime.getRuntime();
7296 long dalvikMax = runtime.maxMemory();
7297 long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
7298 if (dalvikUsed > ((3*dalvikMax)/4)) {
7299 if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
7300 + " total=" + (runtime.totalMemory()/1024)
7301 + " used=" + (dalvikUsed/1024));
7302 mSomeActivitiesChanged = false;
7303 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07007304 ActivityTaskManager.getService().releaseSomeActivities(mAppThread);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07007305 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07007306 throw e.rethrowFromSystemServer();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07007307 }
7308 }
7309 }
7310 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007311 } else {
7312 // Don't set application object here -- if the system crashes,
7313 // we can't display an alert, we just want to die die die.
Siva Velusamyd693dfa2012-09-10 14:36:58 -07007314 android.ddm.DdmHandleAppName.setAppName("system_process",
Dianne Hackborn89ad4562014-08-24 16:45:38 -07007315 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007316 try {
7317 mInstrumentation = new Instrumentation();
Jason Monka80bfb52017-11-16 17:15:37 -05007318 mInstrumentation.basicInit(this);
Jeff Browndefd4a62014-03-10 21:24:37 -07007319 ContextImpl context = ContextImpl.createAppContext(
Todd Kennedy233a0b12018-01-29 20:30:24 +00007320 this, getSystemContext().mPackageInfo);
7321 mInitialApplication = context.mPackageInfo.makeApplication(true, null);
Jeff Brown7fc8e352014-09-16 18:06:47 -07007322 mInitialApplication.onCreate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007323 } catch (Exception e) {
7324 throw new RuntimeException(
7325 "Unable to instantiate Application():" + e.toString(), e);
7326 }
7327 }
Geremy Condrab7faaf42012-09-19 18:07:42 -07007328
Andrii Kulian44607962017-03-16 11:06:24 -07007329 ViewRootImpl.ConfigChangedCallback configChangedCallback
7330 = (Configuration globalConfig) -> {
7331 synchronized (mResourcesManager) {
lumarkddc77fb2019-06-27 22:22:23 +08007332 // TODO (b/135719017): Temporary log for debugging IME service.
7333 if (Build.IS_DEBUGGABLE && mHasImeComponent) {
7334 Log.d(TAG, "ViewRootImpl.ConfigChangedCallback for IME, "
7335 + "config=" + globalConfig);
7336 }
7337
Andrii Kulian44607962017-03-16 11:06:24 -07007338 // We need to apply this change to the resources immediately, because upon returning
7339 // the view hierarchy will be informed about it.
7340 if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,
7341 null /* compat */)) {
7342 updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
7343 mResourcesManager.getConfiguration().getLocales());
Adam Lesinskib61e4052016-05-19 18:23:05 -07007344
Andrii Kulian44607962017-03-16 11:06:24 -07007345 // This actually changed the resources! Tell everyone about it.
7346 if (mPendingConfiguration == null
7347 || mPendingConfiguration.isOtherSeqNewer(globalConfig)) {
7348 mPendingConfiguration = globalConfig;
7349 sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08007350 }
7351 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08007352 }
Andrii Kulian44607962017-03-16 11:06:24 -07007353 };
7354 ViewRootImpl.addConfigCallback(configChangedCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007355 }
7356
Mathew Inwood61e8ae62018-08-14 14:17:44 +01007357 @UnsupportedAppUsage
Romain Guy5e9120d2012-01-30 12:17:22 -08007358 public static ActivityThread systemMain() {
Alan Viverette5e1565e2014-07-29 16:14:25 -07007359 // The system process on low-memory devices do not get to use hardware
7360 // accelerated drawing, since this can add too much overhead to the
7361 // process.
7362 if (!ActivityManager.isHighEndGfx()) {
John Reck51aaf902015-12-02 15:08:07 -08007363 ThreadedRenderer.disable(true);
John Reck73840ea2014-09-22 07:39:18 -07007364 } else {
John Reck51aaf902015-12-02 15:08:07 -08007365 ThreadedRenderer.enableForegroundTrimming();
Alan Viverette5e1565e2014-07-29 16:14:25 -07007366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007367 ActivityThread thread = new ActivityThread();
Sudheer Shankaf6690102017-10-16 10:20:32 -07007368 thread.attach(true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007369 return thread;
7370 }
7371
Irina Dumitrescu34a27c42019-04-15 19:20:38 +01007372 public static void updateHttpProxy(@NonNull Context context) {
7373 final ConnectivityManager cm = ConnectivityManager.from(context);
7374 Proxy.setHttpProxySystemProperty(cm.getDefaultProxy());
7375 }
7376
Mathew Inwood61e8ae62018-08-14 14:17:44 +01007377 @UnsupportedAppUsage
Jeff Brown10e89712011-07-08 18:52:57 -07007378 public final void installSystemProviders(List<ProviderInfo> providers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007379 if (providers != null) {
Jeff Brown10e89712011-07-08 18:52:57 -07007380 installContentProviders(mInitialApplication, providers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007381 }
7382 }
7383
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08007384 public int getIntCoreSetting(String key, int defaultValue) {
Craig Mautner88c05892013-06-28 09:47:45 -07007385 synchronized (mResourcesManager) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08007386 if (mCoreSettings != null) {
7387 return mCoreSettings.getInt(key, defaultValue);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08007388 }
Craig Mautner88c05892013-06-28 09:47:45 -07007389 return defaultValue;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08007390 }
7391 }
7392
Shu Chen9d744e52020-01-22 14:28:08 +08007393 float getFloatCoreSetting(String key, float defaultValue) {
7394 synchronized (mResourcesManager) {
7395 if (mCoreSettings != null) {
7396 return mCoreSettings.getFloat(key, defaultValue);
7397 }
7398 return defaultValue;
7399 }
7400 }
7401
Jeff Sharkeybc2ae002018-07-31 10:45:37 -06007402 private static class AndroidOs extends ForwardingOs {
7403 /**
7404 * Install selective syscall interception. For example, this is used to
7405 * implement special filesystem paths that will be redirected to
7406 * {@link ContentResolver#openFileDescriptor(Uri, String)}.
7407 */
7408 public static void install() {
7409 // If feature is disabled, we don't need to install
7410 if (!DEPRECATE_DATA_COLUMNS) return;
7411
Jeff Sharkeybc2ae002018-07-31 10:45:37 -06007412 // Install interception and make sure it sticks!
7413 Os def = null;
7414 do {
7415 def = Os.getDefault();
7416 } while (!Os.compareAndSetDefault(def, new AndroidOs(def)));
7417 }
7418
7419 private AndroidOs(Os os) {
7420 super(os);
7421 }
7422
7423 private FileDescriptor openDeprecatedDataPath(String path, int mode) throws ErrnoException {
7424 final Uri uri = ContentResolver.translateDeprecatedDataPath(path);
7425 Log.v(TAG, "Redirecting " + path + " to " + uri);
7426
7427 final ContentResolver cr = currentActivityThread().getApplication()
7428 .getContentResolver();
7429 try {
7430 final FileDescriptor fd = new FileDescriptor();
7431 fd.setInt$(cr.openFileDescriptor(uri,
7432 FileUtils.translateModePosixToString(mode)).detachFd());
7433 return fd;
Jeff Sharkeyb50f51e2019-02-27 13:55:38 -07007434 } catch (SecurityException e) {
7435 throw new ErrnoException(e.getMessage(), OsConstants.EACCES);
Jeff Sharkeybc2ae002018-07-31 10:45:37 -06007436 } catch (FileNotFoundException e) {
7437 throw new ErrnoException(e.getMessage(), OsConstants.ENOENT);
7438 }
7439 }
7440
Jeff Sharkey416d4622019-02-27 22:14:16 -07007441 private void deleteDeprecatedDataPath(String path) throws ErrnoException {
7442 final Uri uri = ContentResolver.translateDeprecatedDataPath(path);
7443 Log.v(TAG, "Redirecting " + path + " to " + uri);
7444
7445 final ContentResolver cr = currentActivityThread().getApplication()
7446 .getContentResolver();
7447 try {
7448 if (cr.delete(uri, null, null) == 0) {
7449 throw new FileNotFoundException();
7450 }
7451 } catch (SecurityException e) {
7452 throw new ErrnoException(e.getMessage(), OsConstants.EACCES);
7453 } catch (FileNotFoundException e) {
7454 throw new ErrnoException(e.getMessage(), OsConstants.ENOENT);
7455 }
7456 }
7457
Jeff Sharkeybc2ae002018-07-31 10:45:37 -06007458 @Override
7459 public boolean access(String path, int mode) throws ErrnoException {
7460 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7461 // If we opened it okay, then access check succeeded
7462 IoUtils.closeQuietly(
7463 openDeprecatedDataPath(path, FileUtils.translateModeAccessToPosix(mode)));
7464 return true;
7465 } else {
7466 return super.access(path, mode);
7467 }
7468 }
7469
7470 @Override
7471 public FileDescriptor open(String path, int flags, int mode) throws ErrnoException {
7472 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7473 return openDeprecatedDataPath(path, mode);
7474 } else {
7475 return super.open(path, flags, mode);
7476 }
7477 }
7478
7479 @Override
7480 public StructStat stat(String path) throws ErrnoException {
7481 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7482 final FileDescriptor fd = openDeprecatedDataPath(path, OsConstants.O_RDONLY);
7483 try {
7484 return android.system.Os.fstat(fd);
7485 } finally {
7486 IoUtils.closeQuietly(fd);
7487 }
7488 } else {
7489 return super.stat(path);
Narayan Kamath7f062242015-04-08 13:24:13 +01007490 }
7491 }
Jeff Sharkey416d4622019-02-27 22:14:16 -07007492
7493 @Override
7494 public void unlink(String path) throws ErrnoException {
7495 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7496 deleteDeprecatedDataPath(path);
7497 } else {
7498 super.unlink(path);
7499 }
7500 }
7501
7502 @Override
7503 public void remove(String path) throws ErrnoException {
7504 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7505 deleteDeprecatedDataPath(path);
7506 } else {
7507 super.remove(path);
7508 }
7509 }
Zime59cb732019-12-12 10:54:45 +00007510
7511 @Override
7512 public void rename(String oldPath, String newPath) throws ErrnoException {
7513 try {
7514 super.rename(oldPath, newPath);
7515 } catch (ErrnoException e) {
Martijn Coenen76ce2cc2020-05-12 10:11:38 +02007516 // On emulated volumes, we have bind mounts for /Android/data and
7517 // /Android/obb, which prevents move from working across those directories
7518 // and other directories on the filesystem. To work around that, try to
7519 // recover by doing a copy instead.
7520 // Note that we only do this for "/storage/emulated", because public volumes
7521 // don't have these bind mounts, neither do private volumes that are not
7522 // the primary storage.
7523 if (e.errno == OsConstants.EXDEV && oldPath.startsWith("/storage/emulated")
7524 && newPath.startsWith("/storage/emulated")) {
Zime59cb732019-12-12 10:54:45 +00007525 Log.v(TAG, "Recovering failed rename " + oldPath + " to " + newPath);
7526 try {
Martijn Coenen13885b72020-03-11 13:38:19 +01007527 Files.move(new File(oldPath).toPath(), new File(newPath).toPath(),
7528 StandardCopyOption.REPLACE_EXISTING);
Zime59cb732019-12-12 10:54:45 +00007529 } catch (IOException e2) {
Martijn Coenen13885b72020-03-11 13:38:19 +01007530 Log.e(TAG, "Rename recovery failed ", e);
Zime59cb732019-12-12 10:54:45 +00007531 throw e;
7532 }
7533 } else {
7534 throw e;
7535 }
7536 }
7537 }
Geremy Condrab7faaf42012-09-19 18:07:42 -07007538 }
7539
Romain Guy65b345f2011-07-27 18:51:50 -07007540 public static void main(String[] args) {
Narayan Kamathfbb32f62015-06-12 15:34:35 +01007541 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
Bob Leee5408332009-09-04 18:31:17 -07007542
Jeff Sharkeybc2ae002018-07-31 10:45:37 -06007543 // Install selective syscall interception
7544 AndroidOs.install();
7545
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08007546 // CloseGuard defaults to true and can be quite spammy. We
7547 // disable it here, but selectively enable it later (via
7548 // StrictMode) on debug builds, but using DropBox, not logs.
7549 CloseGuard.setEnabled(false);
7550
Andreas Gamped281b422016-07-08 03:50:27 +00007551 Environment.initForCurrentUser();
Jeff Sharkeyb049e212012-09-07 23:16:01 -07007552
Robin Lee3d076af2014-04-25 14:57:49 +01007553 // Make sure TrustedCertificateStore looks in the right place for CA certificates
7554 final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
7555 TrustedCertificateStore.setDefaultUserDirectory(configDir);
7556
Makoto Onuki6b0a7b82019-10-18 15:44:53 -07007557 // Call per-process mainline module initialization.
7558 initializeMainlineModules();
7559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007560 Process.setArgV0("<pre-initialized>");
7561
7562 Looper.prepareMainLooper();
7563
Sudheer Shankaf6690102017-10-16 10:20:32 -07007564 // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
7565 // It will be in the format "seq=114"
7566 long startSeq = 0;
7567 if (args != null) {
7568 for (int i = args.length - 1; i >= 0; --i) {
7569 if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
7570 startSeq = Long.parseLong(
7571 args[i].substring(PROC_START_SEQ_IDENT.length()));
7572 }
7573 }
7574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007575 ActivityThread thread = new ActivityThread();
Sudheer Shankaf6690102017-10-16 10:20:32 -07007576 thread.attach(false, startSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007577
Vairavan Srinivasan7335cfd2012-08-18 18:36:03 -07007578 if (sMainThreadHandler == null) {
7579 sMainThreadHandler = thread.getHandler();
7580 }
7581
Dianne Hackborn287952c2010-09-22 22:34:31 -07007582 if (false) {
7583 Looper.myLooper().setMessageLogging(new
7584 LogPrinter(Log.DEBUG, "ActivityThread"));
7585 }
7586
Narayan Kamathfbb32f62015-06-12 15:34:35 +01007587 // End of event ActivityThreadMain.
7588 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007589 Looper.loop();
7590
Jeff Brown10e89712011-07-08 18:52:57 -07007591 throw new RuntimeException("Main thread loop unexpectedly exited");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007592 }
Chris Craikfc294242016-12-13 18:10:46 -08007593
Makoto Onuki6b0a7b82019-10-18 15:44:53 -07007594 /**
7595 * Call various initializer APIs in mainline modules that need to be called when each process
7596 * starts.
7597 */
7598 public static void initializeMainlineModules() {
7599 TelephonyFrameworkInitializer.setTelephonyServiceManager(new TelephonyServiceManager());
Jeffrey Huangf58800b2020-01-23 13:22:10 -08007600 StatsFrameworkInitializer.setStatsServiceManager(new StatsServiceManager());
Makoto Onuki6b0a7b82019-10-18 15:44:53 -07007601 }
7602
Makoto Onuki0a9ee1a2019-06-19 08:58:02 -07007603 private void purgePendingResources() {
7604 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "purgePendingResources");
7605 nPurgePendingResources();
7606 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
7607 }
7608
Chris Craikfc294242016-12-13 18:10:46 -08007609 // ------------------ Regular JNI ------------------------
Tim Murray59f3dc12018-10-22 15:26:08 -07007610 private native void nPurgePendingResources();
Chris Craikfc294242016-12-13 18:10:46 -08007611 private native void nDumpGraphicsInfo(FileDescriptor fd);
Ryan Savitskicfdc1512018-12-14 16:20:52 +00007612 private native void nInitZygoteChildHeapProfiling();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007613}