blob: d90e81f098009bddff9c18a3c3b9feeb5c19d61a [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
Riddle Hsu50e34002019-04-12 20:42:05 +080019import static android.app.ActivityManager.PROCESS_STATE_UNKNOWN;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080020import static android.app.servertransaction.ActivityLifecycleItem.ON_CREATE;
21import static android.app.servertransaction.ActivityLifecycleItem.ON_DESTROY;
22import static android.app.servertransaction.ActivityLifecycleItem.ON_PAUSE;
23import static android.app.servertransaction.ActivityLifecycleItem.ON_RESUME;
24import static android.app.servertransaction.ActivityLifecycleItem.ON_START;
25import static android.app.servertransaction.ActivityLifecycleItem.ON_STOP;
26import static android.app.servertransaction.ActivityLifecycleItem.PRE_ON_CREATE;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -060027import static android.content.ContentResolver.DEPRECATE_DATA_COLUMNS;
28import static android.content.ContentResolver.DEPRECATE_DATA_PREFIX;
Andrii Kulianb047b8b2017-02-08 18:38:26 -080029import static android.view.Display.INVALID_DISPLAY;
30
Adrian Roos03dd48c2019-03-19 17:17:37 -040031import static com.android.internal.annotations.VisibleForTesting.Visibility.PACKAGE;
32
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -070033import android.annotation.NonNull;
34import android.annotation.Nullable;
Dianne Hackborn69c6adc2015-06-02 10:52:59 -070035import android.app.assist.AssistContent;
36import android.app.assist.AssistStructure;
Christopher Tate45281862010-03-05 15:46:30 -080037import android.app.backup.BackupAgent;
Andrii Kulian914aa7d2018-03-19 21:51:53 -070038import android.app.servertransaction.ActivityLifecycleItem;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080039import android.app.servertransaction.ActivityLifecycleItem.LifecycleState;
Andrii Kulian914aa7d2018-03-19 21:51:53 -070040import android.app.servertransaction.ActivityRelaunchItem;
Andrii Kulian446e8242017-10-26 15:17:29 -070041import android.app.servertransaction.ActivityResultItem;
42import android.app.servertransaction.ClientTransaction;
Riddle Hsud3062cb2018-06-30 02:06:42 +080043import android.app.servertransaction.ClientTransactionItem;
jorgegil@google.com06bc3232019-10-31 14:51:22 -070044import android.app.servertransaction.PauseActivityItem;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080045import android.app.servertransaction.PendingTransactionActions;
46import android.app.servertransaction.PendingTransactionActions.StopInfo;
jorgegil@google.com06bc3232019-10-31 14:51:22 -070047import android.app.servertransaction.ResumeActivityItem;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080048import android.app.servertransaction.TransactionExecutor;
Andrii Kulian914aa7d2018-03-19 21:51:53 -070049import android.app.servertransaction.TransactionExecutorHelper;
Artur Satayevc895b1b2019-12-10 17:47:51 +000050import android.compat.annotation.UnsupportedAppUsage;
Felipe Lemea4f39cd2019-02-19 15:08:59 -080051import android.content.AutofillOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.content.BroadcastReceiver;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070053import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.content.ComponentName;
Felipe Leme326f15a2019-02-19 09:42:24 -080055import android.content.ContentCaptureOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.ContentProvider;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -060057import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.content.Context;
59import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070060import android.content.IIntentReceiver;
Jesse Hall317fa5a2017-05-23 15:46:55 -070061import android.content.Intent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.content.pm.ActivityInfo;
63import android.content.pm.ApplicationInfo;
64import android.content.pm.IPackageManager;
65import android.content.pm.InstrumentationInfo;
Christopher Tate346acb12012-10-15 19:20:25 -070066import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.content.pm.PackageManager;
Sen Hubde75702010-05-28 01:54:03 -070068import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070069import android.content.pm.ParceledListSlice;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.content.pm.ProviderInfo;
71import android.content.pm.ServiceInfo;
72import android.content.res.AssetManager;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -070073import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.content.res.Configuration;
75import android.content.res.Resources;
Alan Viverettee54d2452015-05-06 10:41:43 -070076import android.content.res.Resources.Theme;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.database.sqlite.SQLiteDatabase;
78import android.database.sqlite.SQLiteDebug;
Vasu Noric3849202010-03-09 10:47:25 -080079import android.database.sqlite.SQLiteDebug.DbStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.graphics.Bitmap;
81import android.graphics.Canvas;
John Reck8785ceb2018-10-29 16:45:58 -070082import android.graphics.HardwareRenderer;
Leon Scroggins III8290eab2018-03-19 10:51:44 -040083import android.graphics.ImageDecoder;
Jeff Brownbd6e1502012-08-28 03:27:37 -070084import android.hardware.display.DisplayManagerGlobal;
lumarkddc77fb2019-06-27 22:22:23 +080085import android.inputmethodservice.InputMethodService;
Paul Jensene0bef712014-12-10 15:12:18 -050086import android.net.ConnectivityManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070087import android.net.IConnectivityManager;
88import android.net.Proxy;
Jason Monk83520b92014-05-09 15:16:06 -040089import android.net.Uri;
Joe Onoratod630f102011-03-17 18:42:26 -070090import android.os.AsyncTask;
Amith Yamasani742a6712011-05-04 14:49:28 -070091import android.os.Binder;
Jeff Sharkey344744b2016-01-28 19:03:30 -070092import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import android.os.Bundle;
Sunny Goyald40c3452019-03-20 12:46:55 -070094import android.os.CancellationSignal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.os.Debug;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070096import android.os.Environment;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -060097import android.os.FileUtils;
Jesse Hallb12249b2016-12-12 12:53:02 -080098import android.os.GraphicsEnvironment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import android.os.Handler;
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700100import android.os.HandlerExecutor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import android.os.IBinder;
Sunny Goyald40c3452019-03-20 12:46:55 -0700102import android.os.ICancellationSignal;
Adam Lesinskib61e4052016-05-19 18:23:05 -0700103import android.os.LocaleList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import android.os.Looper;
105import android.os.Message;
106import android.os.MessageQueue;
Dianne Hackbornfabb70b2014-11-11 12:22:36 -0800107import android.os.Parcel;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700108import android.os.ParcelFileDescriptor;
Craig Mautnera0026042014-04-23 11:45:37 -0700109import android.os.PersistableBundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.os.Process;
Makoto Onuki2c6657f2018-06-06 15:24:02 -0700111import android.os.RemoteCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.os.RemoteException;
113import android.os.ServiceManager;
Jeffrey Huangf58800b2020-01-23 13:22:10 -0800114import android.os.StatsFrameworkInitializer;
115import android.os.StatsServiceManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700116import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import android.os.SystemClock;
Jeff Brownefd43bd2012-09-21 17:02:35 -0700118import android.os.SystemProperties;
Makoto Onuki6b0a7b82019-10-18 15:44:53 -0700119import android.os.TelephonyServiceManager;
Dianne Hackborn1ded0b12012-04-26 14:14:50 -0700120import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700121import android.os.UserHandle;
Todd Kennedy8f135982019-07-02 07:35:15 -0700122import android.permission.IPermissionManager;
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600123import android.provider.BlockedNumberContract;
124import android.provider.CalendarContract;
125import android.provider.CallLog;
126import android.provider.ContactsContract;
127import android.provider.Downloads;
Seigo Nonaka54084b62017-04-24 14:46:23 -0700128import android.provider.FontsContract;
Narayan Kamathccb2a0862013-12-19 14:49:36 +0000129import android.provider.Settings;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700130import android.renderscript.RenderScriptCacheDir;
Chad Brubakerc72875b2016-04-27 16:35:11 -0700131import android.security.NetworkSecurityPolicy;
Chad Brubaker78d47122015-11-17 22:26:58 -0800132import android.security.net.config.NetworkSecurityConfigProvider;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -0600133import android.system.ErrnoException;
134import android.system.OsConstants;
135import android.system.StructStat;
Makoto Onuki6b0a7b82019-10-18 15:44:53 -0700136import android.telephony.TelephonyFrameworkInitializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import android.util.AndroidRuntimeException;
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700138import android.util.ArrayMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139import android.util.DisplayMetrics;
140import android.util.EventLog;
141import android.util.Log;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700142import android.util.LogPrinter;
Andrii Kulianb372da62018-01-18 10:46:24 -0800143import android.util.MergedConfiguration;
Craig Mautnereb8abf72014-07-02 15:04:09 -0700144import android.util.Pair;
Jeff Brown6754ba22011-12-14 20:20:01 -0800145import android.util.PrintWriterPrinter;
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800146import android.util.Slog;
Annie Mengd5827872019-01-30 20:28:57 +0000147import android.util.SparseArray;
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -0700148import android.util.SparseIntArray;
Adam Powell14874662013-07-18 19:42:41 -0700149import android.util.SuperNotCalledException;
Kweku Adams4be0b1a2019-04-25 16:16:34 -0700150import android.util.UtilConfig;
Kweku Adams598e9a22017-11-02 17:12:20 -0700151import android.util.proto.ProtoOutputStream;
Jorim Jaggib29e3182018-04-30 18:51:56 +0200152import android.view.Choreographer;
Adam Lesinski3ad1b482016-04-01 16:41:41 -0700153import android.view.ContextThemeWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154import android.view.Display;
John Reck51aaf902015-12-02 15:08:07 -0800155import android.view.ThreadedRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156import android.view.View;
157import android.view.ViewDebug;
158import android.view.ViewManager;
Dianne Hackborn6dd005b2011-07-18 13:22:50 -0700159import android.view.ViewRootImpl;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160import android.view.Window;
161import android.view.WindowManager;
Jeff Brown98365d72012-08-19 20:30:52 -0700162import android.view.WindowManagerGlobal;
Richard Uhler2c036192016-09-14 09:48:31 +0100163import android.webkit.WebView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700165import com.android.internal.annotations.GuardedBy;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800166import com.android.internal.annotations.VisibleForTesting;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700167import com.android.internal.app.IVoiceInteractor;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800168import com.android.internal.content.ReferrerIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169import com.android.internal.os.BinderInternal;
170import com.android.internal.os.RuntimeInit;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700171import com.android.internal.os.SomeArgs;
Jeff Sharkey3e195892016-03-05 19:48:59 -0700172import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -0700173import com.android.internal.util.FastPrintWriter;
Sunny Goyald40c3452019-03-20 12:46:55 -0700174import com.android.internal.util.Preconditions;
Jorim Jaggib29e3182018-04-30 18:51:56 +0200175import com.android.internal.util.function.pooled.PooledLambda;
Kenny Root12e75222013-04-23 22:34:24 -0700176import com.android.org.conscrypt.OpenSSLSocketImpl;
Robin Lee3d076af2014-04-25 14:57:49 +0100177import com.android.org.conscrypt.TrustedCertificateStore;
Yi Jin6c6e9ca2018-03-20 16:53:35 -0700178import com.android.server.am.MemInfoDumpProto;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700179
Jesse Hall317fa5a2017-05-23 15:46:55 -0700180import dalvik.system.CloseGuard;
181import dalvik.system.VMDebug;
182import dalvik.system.VMRuntime;
183
Jeff Sharkeybc2ae002018-07-31 10:45:37 -0600184import libcore.io.ForwardingOs;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700185import libcore.io.IoUtils;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -0600186import libcore.io.Os;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700187import libcore.net.event.NetworkEventDispatcher;
188
189import org.apache.harmony.dalvik.ddmc.DdmVmInternal;
190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191import java.io.File;
192import java.io.FileDescriptor;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -0600193import java.io.FileNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700195import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196import java.io.PrintWriter;
197import java.lang.ref.WeakReference;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -0400198import java.lang.reflect.Method;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700199import java.net.InetAddress;
Alex Light330e8be2019-08-12 10:58:29 -0700200import java.nio.file.Files;
201import java.nio.file.Path;
Narayan Kamathccb2a0862013-12-19 14:49:36 +0000202import java.text.DateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203import java.util.ArrayList;
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -0600204import java.util.Arrays;
Riddle Hsud3062cb2018-06-30 02:06:42 +0800205import java.util.Collections;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206import java.util.List;
Adam Lesinskib61e4052016-05-19 18:23:05 -0700207import java.util.Locale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208import java.util.Map;
Kenny Roote6585b32013-12-13 12:00:26 -0800209import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210import java.util.TimeZone;
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700211import java.util.concurrent.Executor;
Riddle Hsu50e34002019-04-12 20:42:05 +0800212import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700214final class RemoteServiceException extends AndroidRuntimeException {
215 public RemoteServiceException(String msg) {
216 super(msg);
217 }
218}
219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220/**
221 * This manages the execution of the main thread in an
222 * application process, scheduling and executing activities,
223 * broadcasts, and other operations on it as the activity
224 * manager requests.
225 *
226 * {@hide}
227 */
Andrii Kulian446e8242017-10-26 15:17:29 -0700228public final class ActivityThread extends ClientTransactionHandler {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700229 /** @hide */
230 public static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700231 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
Joe Onorato43a17652011-04-06 19:22:23 -0700232 static final boolean localLOGV = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700233 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborne829fef2010-10-26 17:44:01 -0700234 /** @hide */
235 public static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700236 private static final boolean DEBUG_RESULTS = false;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700237 private static final boolean DEBUG_BACKUP = false;
Craig Mautner88c05892013-06-28 09:47:45 -0700238 public static final boolean DEBUG_CONFIGURATION = false;
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800239 private static final boolean DEBUG_SERVICE = false;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800240 public static final boolean DEBUG_MEMORY_TRIM = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700241 private static final boolean DEBUG_PROVIDER = false;
Andrii Kulianb372da62018-01-18 10:46:24 -0800242 public static final boolean DEBUG_ORDER = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
Riddle Hsu4e8e3b02019-04-12 17:37:10 +0800244 /**
Riddle Hsu50e34002019-04-12 20:42:05 +0800245 * If the activity doesn't become idle in time, the timeout will ensure to apply the pending top
246 * process state.
247 */
248 private static final long PENDING_TOP_PROCESS_STATE_TIMEOUT = 1000;
249 /**
Riddle Hsu4e8e3b02019-04-12 17:37:10 +0800250 * The delay to release the provider when it has no more references. It reduces the number of
251 * transactions for acquiring and releasing provider if the client accesses the provider
252 * frequently in a short time.
253 */
254 private static final long CONTENT_PROVIDER_RETAIN_TIME = 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256
Dianne Hackborn455625e2015-01-21 09:55:13 -0800257 /** Type for IActivityManager.serviceDoneExecuting: anonymous operation */
258 public static final int SERVICE_DONE_EXECUTING_ANON = 0;
259 /** Type for IActivityManager.serviceDoneExecuting: done with an onStart call */
260 public static final int SERVICE_DONE_EXECUTING_START = 1;
261 /** Type for IActivityManager.serviceDoneExecuting: done stopping (destroying) service */
262 public static final int SERVICE_DONE_EXECUTING_STOP = 2;
263
Filip Gruszczynskica664812015-12-04 12:43:36 -0800264 // Whether to invoke an activity callback after delivering new configuration.
265 private static final boolean REPORT_TO_ACTIVITY = true;
266
Riddle Hsu50e34002019-04-12 20:42:05 +0800267 /** Use foreground GC policy (less pause time) and higher JIT weight. */
268 private static final int VM_PROCESS_STATE_JANK_PERCEPTIBLE = 0;
269 /** Use background GC policy and default JIT threshold. */
270 private static final int VM_PROCESS_STATE_JANK_IMPERCEPTIBLE = 1;
271
Sudheer Shanka84a48952017-03-08 18:19:01 -0800272 /**
273 * Denotes an invalid sequence number corresponding to a process state change.
274 */
275 public static final long INVALID_PROC_STATE_SEQ = -1;
276
Sudheer Shankaf6690102017-10-16 10:20:32 -0700277 /**
278 * Identifier for the sequence no. associated with this process start. It will be provided
279 * as one of the arguments when the process starts.
280 */
281 public static final String PROC_START_SEQ_IDENT = "seq=";
282
Sudheer Shanka84a48952017-03-08 18:19:01 -0800283 private final Object mNetworkPolicyLock = new Object();
284
285 /**
286 * Denotes the sequence number of the process state change for which the main thread needs
287 * to block until the network rules are updated for it.
288 *
289 * Value of {@link #INVALID_PROC_STATE_SEQ} indicates there is no need for blocking.
290 */
291 @GuardedBy("mNetworkPolicyLock")
292 private long mNetworkBlockSeq = INVALID_PROC_STATE_SEQ;
293
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100294 @UnsupportedAppUsage
Jeff Browndefd4a62014-03-10 21:24:37 -0700295 private ContextImpl mSystemContext;
Adam Lesinskia82b6262017-03-21 16:56:17 -0700296 private ContextImpl mSystemUiContext;
Bob Leee5408332009-09-04 18:31:17 -0700297
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100298 @UnsupportedAppUsage
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700299 static volatile IPackageManager sPackageManager;
Todd Kennedy8f135982019-07-02 07:35:15 -0700300 private static volatile IPermissionManager sPermissionManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100302 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700303 final ApplicationThread mAppThread = new ApplicationThread();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100304 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700305 final Looper mLooper = Looper.myLooper();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100306 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700307 final H mH = new H();
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700308 final Executor mExecutor = new HandlerExecutor(mH);
Garfield Tan0443b372019-01-04 15:00:13 -0800309 /**
310 * Maps from activity token to local record of running activities in this process.
311 *
312 * This variable is readable if the code is running in activity thread or holding {@link
313 * #mResourcesManager}. It's only writable if the code is running in activity thread and holding
314 * {@link #mResourcesManager}.
315 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100316 @UnsupportedAppUsage
Dianne Hackborn782d4982015-07-08 17:36:37 -0700317 final ArrayMap<IBinder, ActivityClientRecord> mActivities = new ArrayMap<>();
Riddle Hsu66b74a82018-07-26 00:20:12 +0800318 /** The activities to be truly destroyed (not include relaunch). */
Riddle Hsud3062cb2018-06-30 02:06:42 +0800319 final Map<IBinder, ClientTransactionItem> mActivitiesToBeDestroyed =
320 Collections.synchronizedMap(new ArrayMap<IBinder, ClientTransactionItem>());
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700321 // List of new activities (via ActivityRecord.nextIdle) that should
322 // be reported when next we idle.
323 ActivityClientRecord mNewActivities = null;
324 // Number of activities that are currently visible on-screen.
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100325 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700326 int mNumVisibleActivities = 0;
Riddle Hsu50e34002019-04-12 20:42:05 +0800327 private final AtomicInteger mNumLaunchingActivities = new AtomicInteger();
328 @GuardedBy("mAppThread")
329 private int mLastProcessState = PROCESS_STATE_UNKNOWN;
330 @GuardedBy("mAppThread")
331 private int mPendingProcessState = PROCESS_STATE_UNKNOWN;
Amith Yamasani4f128e42016-05-10 11:44:12 -0700332 ArrayList<WeakReference<AssistStructure>> mLastAssistStructures = new ArrayList<>();
333 private int mLastSessionId;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100334 @UnsupportedAppUsage
Dianne Hackborn782d4982015-07-08 17:36:37 -0700335 final ArrayMap<IBinder, Service> mServices = new ArrayMap<>();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100336 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700337 AppBindData mBoundApplication;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700338 Profiler mProfiler;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100339 @UnsupportedAppUsage
Dianne Hackborn908aecc2012-07-31 16:37:34 -0700340 int mCurDefaultDisplayDpi;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100341 @UnsupportedAppUsage
Dianne Hackborndde331c2012-08-03 14:01:57 -0700342 boolean mDensityCompatMode;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100343 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700344 Configuration mConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700345 Configuration mCompatConfiguration;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100346 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700347 Application mInitialApplication;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100348 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700349 final ArrayList<Application> mAllApplications
350 = new ArrayList<Application>();
Annie Mengd5827872019-01-30 20:28:57 +0000351 /**
352 * Bookkeeping of instantiated backup agents indexed first by user id, then by package name.
353 * Indexing by user id supports parallel backups across users on system packages as they run in
354 * the same process with the same package name. Indexing by package name supports multiple
355 * distinct applications running in the same process.
356 */
357 private final SparseArray<ArrayMap<String, BackupAgent>> mBackupAgentsByUser =
358 new SparseArray<>();
Jeff Sharkey66a017b2013-01-17 18:18:22 -0800359 /** Reference to singleton {@link ActivityThread} */
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100360 @UnsupportedAppUsage
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700361 private static volatile ActivityThread sCurrentActivityThread;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100362 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700363 Instrumentation mInstrumentation;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700364 String mInstrumentationPackageName = null;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100365 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700366 String mInstrumentationAppDir = null;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700367 String[] mInstrumentationSplitAppDirs = null;
368 String mInstrumentationLibDir = null;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100369 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700370 String mInstrumentedAppDir = null;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700371 String[] mInstrumentedSplitAppDirs = null;
372 String mInstrumentedLibDir = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700373 boolean mSystemThread = false;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700374 boolean mSomeActivitiesChanged = false;
Chong Zhang4951f9d2016-06-23 13:15:08 -0700375 boolean mUpdatingSystemConfig = false;
David Brazdild960cc42018-01-31 07:59:17 +0000376 /* package */ boolean mHiddenApiWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100378 // These can be accessed by multiple threads; mResourcesManager is the lock.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700379 // XXX For now we keep around information about all packages we have
380 // seen, not removing entries from this map.
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800381 // NOTE: The activity and window managers need to call in to
Dianne Hackborn2f0b1752011-05-31 17:59:49 -0700382 // ActivityThread to do things like update resource configurations,
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800383 // which means this lock gets held while the activity and window managers
384 // holds their own lock. Thus you MUST NEVER call back into the activity manager
385 // or window manager or anything that depends on them while holding this lock.
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700386 // These LoadedApk are only valid for the userId that we're running as.
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100387 @GuardedBy("mResourcesManager")
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100388 @UnsupportedAppUsage
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100389 final ArrayMap<String, WeakReference<LoadedApk>> mPackages = new ArrayMap<>();
390 @GuardedBy("mResourcesManager")
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100391 @UnsupportedAppUsage
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100392 final ArrayMap<String, WeakReference<LoadedApk>> mResourcePackages = new ArrayMap<>();
393 @GuardedBy("mResourcesManager")
394 final ArrayList<ActivityClientRecord> mRelaunchingActivities = new ArrayList<>();
395 @GuardedBy("mResourcesManager")
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100396 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700397 Configuration mPendingConfiguration = null;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800398 // An executor that performs multi-step transactions.
399 private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800400
Mathew Inwood8c854f82018-09-14 12:35:36 +0100401 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Craig Mautner88c05892013-06-28 09:47:45 -0700402 private final ResourcesManager mResourcesManager;
403
Svet Ganov3b6be082019-04-28 10:21:01 -0700404 // Registry of remote cancellation transports pending a reply with reply handles.
405 @GuardedBy("this")
406 private @Nullable Map<SafeCancellationTransport, CancellationSignal> mRemoteCancellations;
407
Jeff Sharkey6d515712012-09-20 16:06:08 -0700408 private static final class ProviderKey {
409 final String authority;
410 final int userId;
411
412 public ProviderKey(String authority, int userId) {
413 this.authority = authority;
414 this.userId = userId;
415 }
416
417 @Override
418 public boolean equals(Object o) {
419 if (o instanceof ProviderKey) {
420 final ProviderKey other = (ProviderKey) o;
Kenny Roote6585b32013-12-13 12:00:26 -0800421 return Objects.equals(authority, other.authority) && userId == other.userId;
Jeff Sharkey6d515712012-09-20 16:06:08 -0700422 }
423 return false;
424 }
425
426 @Override
427 public int hashCode() {
428 return ((authority != null) ? authority.hashCode() : 0) ^ userId;
429 }
430 }
431
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700432 // The lock of mProviderMap protects the following variables.
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100433 @UnsupportedAppUsage
Wale Ogunwale1d646122015-04-24 14:45:14 -0700434 final ArrayMap<ProviderKey, ProviderClientRecord> mProviderMap
435 = new ArrayMap<ProviderKey, ProviderClientRecord>();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100436 @UnsupportedAppUsage
Wale Ogunwale1d646122015-04-24 14:45:14 -0700437 final ArrayMap<IBinder, ProviderRefCount> mProviderRefCountMap
438 = new ArrayMap<IBinder, ProviderRefCount>();
Mathew Inwood8c854f82018-09-14 12:35:36 +0100439 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Wale Ogunwale1d646122015-04-24 14:45:14 -0700440 final ArrayMap<IBinder, ProviderClientRecord> mLocalProviders
441 = new ArrayMap<IBinder, ProviderClientRecord>();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100442 @UnsupportedAppUsage
Wale Ogunwale1d646122015-04-24 14:45:14 -0700443 final ArrayMap<ComponentName, ProviderClientRecord> mLocalProvidersByName
444 = new ArrayMap<ComponentName, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445
Makoto Onukib6c79ea2018-05-31 11:03:56 -0700446 // Mitigation for b/74523247: Used to serialize calls to AM.getContentProvider().
447 // Note we never removes items from this map but that's okay because there are only so many
448 // users and so many authorities.
449 // TODO Remove it once we move CPR.wait() from AMS to the client side.
450 @GuardedBy("mGetProviderLocks")
451 final ArrayMap<ProviderKey, Object> mGetProviderLocks = new ArrayMap<>();
452
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700453 final ArrayMap<Activity, ArrayList<OnActivityPausedListener>> mOnPauseListeners
Wale Ogunwale1d646122015-04-24 14:45:14 -0700454 = new ArrayMap<Activity, ArrayList<OnActivityPausedListener>>();
Jeff Hamilton52d32032011-01-08 15:31:26 -0600455
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700456 final GcIdler mGcIdler = new GcIdler();
Tim Murray59f3dc12018-10-22 15:26:08 -0700457 final PurgeIdler mPurgeIdler = new PurgeIdler();
458
459 boolean mPurgeIdlerScheduled = false;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700460 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461
Mathew Inwood8c854f82018-09-14 12:35:36 +0100462 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700463 static volatile Handler sMainThreadHandler; // set once in main()
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700464
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800465 Bundle mCoreSettings = null;
466
lumarkddc77fb2019-06-27 22:22:23 +0800467 boolean mHasImeComponent = false;
468
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800469 /** Activity client record, used for bookkeeping for the real {@link Activity} instance. */
470 public static final class ActivityClientRecord {
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100471 @UnsupportedAppUsage
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800472 public IBinder token;
Sunny Goyald40c3452019-03-20 12:46:55 -0700473 public IBinder assistToken;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700474 int ident;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100475 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 Intent intent;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800477 String referrer;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700478 IVoiceInteractor voiceInteractor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 Bundle state;
Craig Mautnera0026042014-04-23 11:45:37 -0700480 PersistableBundle persistentState;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100481 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 Activity activity;
483 Window window;
484 Activity parent;
485 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700486 Activity.NonConfigurationInstances lastNonConfigurationInstances;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800487 // TODO(lifecycler): Use mLifecycleState instead.
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100488 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 boolean paused;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100490 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 boolean stopped;
492 boolean hideForNow;
493 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700494 Configuration createdConfig;
Wale Ogunwale60454db2015-01-23 16:05:07 -0800495 Configuration overrideConfig;
Garfield Tan0443b372019-01-04 15:00:13 -0800496 // Used to save the last reported configuration from server side so that activity
497 // configuration transactions can always use the latest configuration.
498 @GuardedBy("this")
499 private Configuration mPendingOverrideConfig;
Wale Ogunwalec2607b42015-02-07 16:16:59 -0800500 // Used for consolidating configs before sending on to Activity.
501 private Configuration tmpConfig = new Configuration();
Andrii Kulian44607962017-03-16 11:06:24 -0700502 // Callback used for updating activity override config.
503 ViewRootImpl.ActivityConfigCallback configCallback;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700504 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505
Andrii Kuliand70cdb92019-01-08 15:03:50 -0800506 // Indicates whether this activity is currently the topmost resumed one in the system.
507 // This holds the last reported value from server.
508 boolean isTopResumedActivity;
509 // This holds the value last sent to the activity. This is needed, because an update from
510 // server may come at random time, but we always need to report changes between ON_RESUME
511 // and ON_PAUSE to the app.
512 boolean lastReportedTopResumedState;
513
Jeff Hao1b012d32014-08-20 10:35:34 -0700514 ProfilerInfo profilerInfo;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700515
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100516 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 ActivityInfo activityInfo;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100518 @UnsupportedAppUsage
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400519 CompatibilityInfo compatInfo;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100520 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +0000521 public LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522
523 List<ResultInfo> pendingResults;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800524 List<ReferrerIntent> pendingIntents;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525
526 boolean startsNotResumed;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800527 public final boolean isForward;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800528 int pendingConfigChanges;
jorgegil@google.com06bc3232019-10-31 14:51:22 -0700529 // Whether we are in the process of performing on user leaving.
530 boolean mIsUserLeaving;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800531
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700532 Window mPendingRemoveWindow;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800533 WindowManager mPendingRemoveWindowManager;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100534 @UnsupportedAppUsage
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700535 boolean mPreserveWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800537 @LifecycleState
538 private int mLifecycleState = PRE_ON_CREATE;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700539
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800540 @VisibleForTesting
Mathew Inwood8c854f82018-09-14 12:35:36 +0100541 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800542 public ActivityClientRecord() {
543 this.isForward = false;
544 init();
545 }
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700546
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800547 public ActivityClientRecord(IBinder token, Intent intent, int ident,
548 ActivityInfo info, Configuration overrideConfig, CompatibilityInfo compatInfo,
549 String referrer, IVoiceInteractor voiceInteractor, Bundle state,
550 PersistableBundle persistentState, List<ResultInfo> pendingResults,
551 List<ReferrerIntent> pendingNewIntents, boolean isForward,
Sunny Goyald40c3452019-03-20 12:46:55 -0700552 ProfilerInfo profilerInfo, ClientTransactionHandler client,
553 IBinder assistToken) {
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800554 this.token = token;
Sunny Goyald40c3452019-03-20 12:46:55 -0700555 this.assistToken = assistToken;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800556 this.ident = ident;
557 this.intent = intent;
558 this.referrer = referrer;
559 this.voiceInteractor = voiceInteractor;
560 this.activityInfo = info;
561 this.compatInfo = compatInfo;
562 this.state = state;
563 this.persistentState = persistentState;
564 this.pendingResults = pendingResults;
565 this.pendingIntents = pendingNewIntents;
566 this.isForward = isForward;
567 this.profilerInfo = profilerInfo;
568 this.overrideConfig = overrideConfig;
Todd Kennedy233a0b12018-01-29 20:30:24 +0000569 this.packageInfo = client.getPackageInfoNoCheck(activityInfo.applicationInfo,
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800570 compatInfo);
571 init();
572 }
573
574 /** Common initializer for all constructors. */
575 private void init() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 parent = null;
577 embeddedID = null;
578 paused = false;
579 stopped = false;
580 hideForNow = false;
581 nextIdle = null;
Andrii Kulian44607962017-03-16 11:06:24 -0700582 configCallback = (Configuration overrideConfig, int newDisplayId) -> {
583 if (activity == null) {
584 throw new IllegalStateException(
585 "Received config update for non-existing activity");
586 }
Andrii Kulian446e8242017-10-26 15:17:29 -0700587 activity.mMainThread.handleActivityConfigurationChanged(token, overrideConfig,
588 newDisplayId);
Andrii Kulian44607962017-03-16 11:06:24 -0700589 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 }
591
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800592 /** Get the current lifecycle state. */
593 public int getLifecycleState() {
594 return mLifecycleState;
595 }
596
597 /** Update the current lifecycle state for internal bookkeeping. */
598 public void setState(@LifecycleState int newLifecycleState) {
599 mLifecycleState = newLifecycleState;
600 switch (mLifecycleState) {
601 case ON_CREATE:
602 paused = true;
603 stopped = true;
604 break;
605 case ON_START:
606 paused = true;
607 stopped = false;
608 break;
609 case ON_RESUME:
610 paused = false;
611 stopped = false;
612 break;
613 case ON_PAUSE:
614 paused = true;
615 stopped = false;
616 break;
617 case ON_STOP:
618 paused = true;
619 stopped = true;
620 break;
621 }
622 }
623
Andrii Kulian391161f2018-01-29 10:50:02 -0800624 private boolean isPreHoneycomb() {
625 return activity != null && activity.getApplicationInfo().targetSdkVersion
626 < android.os.Build.VERSION_CODES.HONEYCOMB;
627 }
628
629 private boolean isPreP() {
630 return activity != null && activity.getApplicationInfo().targetSdkVersion
631 < android.os.Build.VERSION_CODES.P;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800632 }
633
Craig Mautnera0026042014-04-23 11:45:37 -0700634 public boolean isPersistable() {
Craig Mautner43e52ed2014-06-16 17:18:52 -0700635 return activityInfo.persistableMode == ActivityInfo.PERSIST_ACROSS_REBOOTS;
Craig Mautnera0026042014-04-23 11:45:37 -0700636 }
637
Andrii Kulian914aa7d2018-03-19 21:51:53 -0700638 public boolean isVisibleFromServer() {
639 return activity != null && activity.mVisibleFromServer;
640 }
641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 public String toString() {
Dianne Hackbornb61a0262012-05-14 17:19:18 -0700643 ComponentName componentName = intent != null ? intent.getComponent() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 return "ActivityRecord{"
645 + Integer.toHexString(System.identityHashCode(this))
646 + " token=" + token + " " + (componentName == null
647 ? "no component name" : componentName.toShortString())
648 + "}";
649 }
Andrii Kulian58178f22016-03-16 13:44:56 -0700650
651 public String getStateString() {
652 StringBuilder sb = new StringBuilder();
653 sb.append("ActivityClientRecord{");
654 sb.append("paused=").append(paused);
655 sb.append(", stopped=").append(stopped);
656 sb.append(", hideForNow=").append(hideForNow);
657 sb.append(", startsNotResumed=").append(startsNotResumed);
658 sb.append(", isForward=").append(isForward);
659 sb.append(", pendingConfigChanges=").append(pendingConfigChanges);
Andrii Kulian58178f22016-03-16 13:44:56 -0700660 sb.append(", preserveWindow=").append(mPreserveWindow);
661 if (activity != null) {
662 sb.append(", Activity{");
663 sb.append("resumed=").append(activity.mResumed);
664 sb.append(", stopped=").append(activity.mStopped);
665 sb.append(", finished=").append(activity.isFinishing());
666 sb.append(", destroyed=").append(activity.isDestroyed());
667 sb.append(", startedActivity=").append(activity.mStartedActivity);
Andrii Kulian58178f22016-03-16 13:44:56 -0700668 sb.append(", changingConfigurations=").append(activity.mChangingConfigurations);
Andrii Kulian58178f22016-03-16 13:44:56 -0700669 sb.append("}");
670 }
671 sb.append("}");
672 return sb.toString();
673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 }
675
Wale Ogunwale1d646122015-04-24 14:45:14 -0700676 final class ProviderClientRecord {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700677 final String[] mNames;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100678 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 final IContentProvider mProvider;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100680 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 final ContentProvider mLocalProvider;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100682 @UnsupportedAppUsage
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700683 final ContentProviderHolder mHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700685 ProviderClientRecord(String[] names, IContentProvider provider,
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700686 ContentProvider localProvider, ContentProviderHolder holder) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700687 mNames = names;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 mProvider = provider;
689 mLocalProvider = localProvider;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700690 mHolder = holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 }
692 }
693
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400694 static final class ReceiverData extends BroadcastReceiver.PendingResult {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700695 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700696 boolean ordered, boolean sticky, IBinder token, int sendingUser) {
697 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky,
riddle_hsu1f5ac4d2015-01-03 15:38:21 +0800698 token, sendingUser, intent.getFlags());
Dianne Hackborne829fef2010-10-26 17:44:01 -0700699 this.intent = intent;
700 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700701
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100702 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 Intent intent;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100704 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 ActivityInfo info;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100706 @UnsupportedAppUsage
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400707 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 public String toString() {
709 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700710 info.packageName + " resultCode=" + getResultCode()
711 + " resultData=" + getResultData() + " resultExtras="
712 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 }
714 }
715
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400716 static final class CreateBackupAgentData {
Christopher Tate181fafa2009-05-14 11:12:14 -0700717 ApplicationInfo appInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400718 CompatibilityInfo compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700719 int backupMode;
Ruslan Tkhakokhov063180f2019-01-28 20:29:46 +0000720 int userId;
Christopher Tate181fafa2009-05-14 11:12:14 -0700721 public String toString() {
722 return "CreateBackupAgentData{appInfo=" + appInfo
723 + " backupAgent=" + appInfo.backupAgentName
Ruslan Tkhakokhov063180f2019-01-28 20:29:46 +0000724 + " mode=" + backupMode + " userId=" + userId + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700725 }
726 }
Bob Leee5408332009-09-04 18:31:17 -0700727
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400728 static final class CreateServiceData {
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100729 @UnsupportedAppUsage
Artur Satayev751e5512019-11-15 19:12:49 +0000730 CreateServiceData() {
731 }
732 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 IBinder token;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100734 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 ServiceInfo info;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100736 @UnsupportedAppUsage
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400737 CompatibilityInfo compatInfo;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100738 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 Intent intent;
740 public String toString() {
741 return "CreateServiceData{token=" + token + " className="
742 + info.name + " packageName=" + info.packageName
743 + " intent=" + intent + "}";
744 }
745 }
746
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400747 static final class BindServiceData {
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100748 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 IBinder token;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100750 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 Intent intent;
752 boolean rebind;
753 public String toString() {
754 return "BindServiceData{token=" + token + " intent=" + intent + "}";
755 }
756 }
757
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400758 static final class ServiceArgsData {
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100759 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 IBinder token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700761 boolean taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700763 int flags;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100764 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 Intent args;
766 public String toString() {
767 return "ServiceArgsData{token=" + token + " startId=" + startId
768 + " args=" + args + "}";
769 }
770 }
771
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400772 static final class AppBindData {
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100773 @UnsupportedAppUsage
Artur Satayev751e5512019-11-15 19:12:49 +0000774 AppBindData() {
775 }
776 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +0000777 LoadedApk info;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100778 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 String processName;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100780 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 ApplicationInfo appInfo;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100782 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 List<ProviderInfo> providers;
784 ComponentName instrumentationName;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100785 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 Bundle instrumentationArgs;
787 IInstrumentationWatcher instrumentationWatcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800788 IUiAutomationConnection instrumentationUiAutomationConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 int debugMode;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400790 boolean enableBinderTracking;
Man Caocfa78b22015-06-11 20:14:34 -0700791 boolean trackAllocation;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100792 @UnsupportedAppUsage
Christopher Tate181fafa2009-05-14 11:12:14 -0700793 boolean restrictedBackupMode;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100794 @UnsupportedAppUsage
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700795 boolean persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 Configuration config;
Mathew Inwood8c854f82018-09-14 12:35:36 +0100797 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400798 CompatibilityInfo compatInfo;
Svet Ganov37e43272016-09-09 16:01:32 -0700799 String buildSerial;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700800
801 /** Initial values for {@link Profiler}. */
Jeff Hao1b012d32014-08-20 10:35:34 -0700802 ProfilerInfo initProfilerInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700803
Felipe Lemea4f39cd2019-02-19 15:08:59 -0800804 AutofillOptions autofillOptions;
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800805
Felipe Leme326f15a2019-02-19 09:42:24 -0800806 /**
807 * Content capture options for the application - when null, it means ContentCapture is not
808 * enabled for the package.
809 */
810 @Nullable
811 ContentCaptureOptions contentCaptureOptions;
812
Mathew Inwood80652db2019-06-24 12:07:22 +0100813 long[] disabledCompatChanges;
814
Felipe Leme326f15a2019-02-19 09:42:24 -0800815 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 public String toString() {
817 return "AppBindData{appInfo=" + appInfo + "}";
818 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700819 }
820
821 static final class Profiler {
822 String profileFile;
823 ParcelFileDescriptor profileFd;
Jeff Hao1b012d32014-08-20 10:35:34 -0700824 int samplingInterval;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700825 boolean autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800826 boolean streamingOutput;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700827 boolean profiling;
828 boolean handlingProfiling;
Jeff Hao1b012d32014-08-20 10:35:34 -0700829 public void setProfiler(ProfilerInfo profilerInfo) {
830 ParcelFileDescriptor fd = profilerInfo.profileFd;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700831 if (profiling) {
832 if (fd != null) {
833 try {
834 fd.close();
835 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700836 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700837 }
838 }
839 return;
840 }
841 if (profileFd != null) {
842 try {
843 profileFd.close();
844 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700845 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700846 }
847 }
Jeff Hao1b012d32014-08-20 10:35:34 -0700848 profileFile = profilerInfo.profileFile;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700849 profileFd = fd;
Jeff Hao1b012d32014-08-20 10:35:34 -0700850 samplingInterval = profilerInfo.samplingInterval;
851 autoStopProfiler = profilerInfo.autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800852 streamingOutput = profilerInfo.streamingOutput;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700853 }
854 public void startProfiling() {
855 if (profileFd == null || profiling) {
856 return;
857 }
858 try {
Andreas Gampeeff06392016-05-10 12:51:45 -0700859 int bufferSize = SystemProperties.getInt("debug.traceview-buffer-size-mb", 8);
Jeff Hao1b012d32014-08-20 10:35:34 -0700860 VMDebug.startMethodTracing(profileFile, profileFd.getFileDescriptor(),
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800861 bufferSize * 1024 * 1024, 0, samplingInterval != 0, samplingInterval,
862 streamingOutput);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700863 profiling = true;
864 } catch (RuntimeException e) {
Andreas Gampe4f689242018-03-14 23:13:28 -0700865 Slog.w(TAG, "Profiling failed on path " + profileFile, e);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700866 try {
867 profileFd.close();
868 profileFd = null;
869 } catch (IOException e2) {
870 Slog.w(TAG, "Failure closing profile fd", e2);
871 }
872 }
873 }
874 public void stopProfiling() {
875 if (profiling) {
876 profiling = false;
877 Debug.stopMethodTracing();
878 if (profileFd != null) {
879 try {
880 profileFd.close();
881 } catch (IOException e) {
882 }
883 }
884 profileFd = null;
885 profileFile = null;
886 }
887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 }
889
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400890 static final class DumpComponentInfo {
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700891 ParcelFileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700892 IBinder token;
Dianne Hackborn30d71892010-12-11 10:37:55 -0800893 String prefix;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 String[] args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 }
896
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400897 static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800898 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 String what;
900 String who;
901 }
902
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400903 static final class DumpHeapData {
Kweku Adams4af1b502019-05-23 16:23:48 -0700904 // Whether to dump the native or managed heap.
Christopher Ferris8d652f82017-04-11 16:29:18 -0700905 public boolean managed;
906 public boolean mallocInfo;
Makoto Onuki4556b7b2017-07-07 14:58:58 -0700907 public boolean runGc;
Andy McFadden824c5102010-07-09 16:26:57 -0700908 String path;
909 ParcelFileDescriptor fd;
Makoto Onuki2c6657f2018-06-06 15:24:02 -0700910 RemoteCallback finishCallback;
Andy McFadden824c5102010-07-09 16:26:57 -0700911 }
912
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400913 static final class UpdateCompatibilityData {
914 String pkg;
915 CompatibilityInfo info;
916 }
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800917
Adam Skorydfc7fd72013-08-05 19:23:41 -0700918 static final class RequestAssistContextExtras {
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800919 IBinder activityToken;
920 IBinder requestToken;
921 int requestType;
Amith Yamasani4f128e42016-05-10 11:44:12 -0700922 int sessionId;
Svet Ganovfd31f852017-04-26 15:54:27 -0700923 int flags;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800924 }
Anwar Ghuloum3a8ce1b2013-04-26 16:18:28 -0700925
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700926 private class ApplicationThread extends IApplicationThread.Stub {
Vasu Nori3c7131f2010-09-21 14:36:57 -0700927 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 public final void scheduleReceiver(Intent intent, ActivityInfo info,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400930 CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700931 boolean sync, int sendingUser, int processState) {
932 updateProcessState(processState, false);
Dianne Hackborne829fef2010-10-26 17:44:01 -0700933 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700934 sync, false, mAppThread.asBinder(), sendingUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 r.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400936 r.compatInfo = compatInfo;
Jeff Brown9ef09972013-10-15 20:49:59 -0700937 sendMessage(H.RECEIVER, r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 }
939
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400940 public final void scheduleCreateBackupAgent(ApplicationInfo app,
Ruslan Tkhakokhov063180f2019-01-28 20:29:46 +0000941 CompatibilityInfo compatInfo, int backupMode, int userId) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700942 CreateBackupAgentData d = new CreateBackupAgentData();
943 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400944 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700945 d.backupMode = backupMode;
Ruslan Tkhakokhov063180f2019-01-28 20:29:46 +0000946 d.userId = userId;
Christopher Tate181fafa2009-05-14 11:12:14 -0700947
Jeff Brown9ef09972013-10-15 20:49:59 -0700948 sendMessage(H.CREATE_BACKUP_AGENT, d);
Christopher Tate181fafa2009-05-14 11:12:14 -0700949 }
950
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400951 public final void scheduleDestroyBackupAgent(ApplicationInfo app,
Annie Mengd5827872019-01-30 20:28:57 +0000952 CompatibilityInfo compatInfo, int userId) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700953 CreateBackupAgentData d = new CreateBackupAgentData();
954 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400955 d.compatInfo = compatInfo;
Annie Mengd5827872019-01-30 20:28:57 +0000956 d.userId = userId;
Christopher Tate181fafa2009-05-14 11:12:14 -0700957
Jeff Brown9ef09972013-10-15 20:49:59 -0700958 sendMessage(H.DESTROY_BACKUP_AGENT, d);
Christopher Tate181fafa2009-05-14 11:12:14 -0700959 }
960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 public final void scheduleCreateService(IBinder token,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700962 ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
963 updateProcessState(processState, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 CreateServiceData s = new CreateServiceData();
965 s.token = token;
966 s.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400967 s.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968
Jeff Brown9ef09972013-10-15 20:49:59 -0700969 sendMessage(H.CREATE_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 }
971
972 public final void scheduleBindService(IBinder token, Intent intent,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700973 boolean rebind, int processState) {
974 updateProcessState(processState, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 BindServiceData s = new BindServiceData();
976 s.token = token;
977 s.intent = intent;
978 s.rebind = rebind;
979
Amith Yamasani742a6712011-05-04 14:49:28 -0700980 if (DEBUG_SERVICE)
981 Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
982 + Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
Jeff Brown9ef09972013-10-15 20:49:59 -0700983 sendMessage(H.BIND_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 }
985
986 public final void scheduleUnbindService(IBinder token, Intent intent) {
987 BindServiceData s = new BindServiceData();
988 s.token = token;
989 s.intent = intent;
990
Jeff Brown9ef09972013-10-15 20:49:59 -0700991 sendMessage(H.UNBIND_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 }
993
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -0700994 public final void scheduleServiceArgs(IBinder token, ParceledListSlice args) {
995 List<ServiceStartArgs> list = args.getList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -0700997 for (int i = 0; i < list.size(); i++) {
998 ServiceStartArgs ssa = list.get(i);
999 ServiceArgsData s = new ServiceArgsData();
1000 s.token = token;
1001 s.taskRemoved = ssa.taskRemoved;
1002 s.startId = ssa.startId;
1003 s.flags = ssa.flags;
1004 s.args = ssa.args;
1005
1006 sendMessage(H.SERVICE_ARGS, s);
1007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 }
1009
1010 public final void scheduleStopService(IBinder token) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001011 sendMessage(H.STOP_SERVICE, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 }
1013
Jeff Hao1b012d32014-08-20 10:35:34 -07001014 public final void bindApplication(String processName, ApplicationInfo appInfo,
1015 List<ProviderInfo> providers, ComponentName instrumentationName,
1016 ProfilerInfo profilerInfo, Bundle instrumentationArgs,
1017 IInstrumentationWatcher instrumentationWatcher,
Svetoslav Ganov80943d82013-01-02 10:25:37 -08001018 IUiAutomationConnection instrumentationUiConnection, int debugMode,
Pablo Ceballosa4d4e822015-10-05 10:27:52 -07001019 boolean enableBinderTracking, boolean trackAllocation,
1020 boolean isRestrictedBackupMode, boolean persistent, Configuration config,
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001021 CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
Felipe Lemea4f39cd2019-02-19 15:08:59 -08001022 String buildSerial, AutofillOptions autofillOptions,
Mathew Inwood80652db2019-06-24 12:07:22 +01001023 ContentCaptureOptions contentCaptureOptions, long[] disabledCompatChanges) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 if (services != null) {
Makoto Onuki45895652018-05-07 14:43:05 -07001025 if (false) {
1026 // Test code to make sure the app could see the passed-in services.
1027 for (Object oname : services.keySet()) {
1028 if (services.get(oname) == null) {
1029 continue; // AM just passed in a null service.
1030 }
1031 String name = (String) oname;
1032
1033 // See b/79378449 about the following exemption.
1034 switch (name) {
1035 case "package":
1036 case Context.WINDOW_SERVICE:
1037 continue;
1038 }
1039
1040 if (ServiceManager.getService(name) == null) {
1041 Log.wtf(TAG, "Service " + name + " should be accessible by this app");
1042 }
1043 }
1044 }
1045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 // Setup the service cache in the ServiceManager
1047 ServiceManager.initServiceCache(services);
1048 }
1049
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08001050 setCoreSettings(coreSettings);
1051
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 AppBindData data = new AppBindData();
1053 data.processName = processName;
1054 data.appInfo = appInfo;
1055 data.providers = providers;
1056 data.instrumentationName = instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 data.instrumentationArgs = instrumentationArgs;
1058 data.instrumentationWatcher = instrumentationWatcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -08001059 data.instrumentationUiAutomationConnection = instrumentationUiConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 data.debugMode = debugMode;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001061 data.enableBinderTracking = enableBinderTracking;
Man Caocfa78b22015-06-11 20:14:34 -07001062 data.trackAllocation = trackAllocation;
Christopher Tate181fafa2009-05-14 11:12:14 -07001063 data.restrictedBackupMode = isRestrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -07001064 data.persistent = persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 data.config = config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001066 data.compatInfo = compatInfo;
Jeff Hao1b012d32014-08-20 10:35:34 -07001067 data.initProfilerInfo = profilerInfo;
Svet Ganov37e43272016-09-09 16:01:32 -07001068 data.buildSerial = buildSerial;
Felipe Lemea4f39cd2019-02-19 15:08:59 -08001069 data.autofillOptions = autofillOptions;
Felipe Leme326f15a2019-02-19 09:42:24 -08001070 data.contentCaptureOptions = contentCaptureOptions;
Mathew Inwood80652db2019-06-24 12:07:22 +01001071 data.disabledCompatChanges = disabledCompatChanges;
Jeff Brown9ef09972013-10-15 20:49:59 -07001072 sendMessage(H.BIND_APPLICATION, data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 }
1074
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001075 public final void runIsolatedEntryPoint(String entryPoint, String[] entryPointArgs) {
1076 SomeArgs args = SomeArgs.obtain();
1077 args.arg1 = entryPoint;
1078 args.arg2 = entryPointArgs;
1079 sendMessage(H.RUN_ISOLATED_ENTRY_POINT, args);
1080 }
1081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 public final void scheduleExit() {
Jeff Brown9ef09972013-10-15 20:49:59 -07001083 sendMessage(H.EXIT_APPLICATION, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 }
1085
Christopher Tate5e1ab332009-09-01 20:32:49 -07001086 public final void scheduleSuicide() {
Jeff Brown9ef09972013-10-15 20:49:59 -07001087 sendMessage(H.SUICIDE, null);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001088 }
1089
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001090 public void scheduleApplicationInfoChanged(ApplicationInfo ai) {
Winson Chung6ee17422019-05-07 13:22:15 -07001091 mH.removeMessages(H.APPLICATION_INFO_CHANGED, ai);
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001092 sendMessage(H.APPLICATION_INFO_CHANGED, ai);
1093 }
1094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 public void updateTimeZone() {
1096 TimeZone.setDefault(null);
1097 }
1098
Robert Greenwalt03595d02010-11-02 14:08:23 -07001099 public void clearDnsCache() {
1100 // a non-standard API to get this to libcore
1101 InetAddress.clearDnsCache();
Paul Jensene401d172014-09-12 10:47:39 -04001102 // Allow libcore to perform the necessary actions as it sees fit upon a network
1103 // configuration change.
1104 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Robert Greenwalt03595d02010-11-02 14:08:23 -07001105 }
1106
Irina Dumitrescu18622d32018-12-05 16:19:47 +00001107 public void updateHttpProxy() {
Irina Dumitrescu34a27c42019-04-15 19:20:38 +01001108 ActivityThread.updateHttpProxy(
Chalard Jean100df0a2018-05-15 23:11:45 +09001109 getApplication() != null ? getApplication() : getSystemContext());
Robert Greenwalt434203a2010-10-11 16:00:27 -07001110 }
1111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 public void processInBackground() {
1113 mH.removeMessages(H.GC_WHEN_IDLE);
1114 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
1115 }
1116
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001117 public void dumpService(ParcelFileDescriptor pfd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07001118 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001119 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001120 data.fd = pfd.dup();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001121 data.token = servicetoken;
1122 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001123 sendMessage(H.DUMP_SERVICE, data, 0, 0, true /*async*/);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001124 } catch (IOException e) {
1125 Slog.w(TAG, "dumpService failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001126 } finally {
1127 IoUtils.closeQuietly(pfd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 }
1129 }
1130
1131 // This function exists to make sure all receiver dispatching is
1132 // correctly ordered, since these are one-way calls and the binder driver
1133 // applies transaction ordering per object for such calls.
1134 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07001135 int resultCode, String dataStr, Bundle extras, boolean ordered,
Dianne Hackborna413dc02013-07-12 12:02:55 -07001136 boolean sticky, int sendingUser, int processState) throws RemoteException {
1137 updateProcessState(processState, false);
Dianne Hackborn20e80982012-08-31 19:00:44 -07001138 receiver.performReceive(intent, resultCode, dataStr, extras, ordered,
1139 sticky, sendingUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 }
Bob Leee5408332009-09-04 18:31:17 -07001141
Wale Ogunwalec2607b42015-02-07 16:16:59 -08001142 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 public void scheduleLowMemory() {
Jeff Brown9ef09972013-10-15 20:49:59 -07001144 sendMessage(H.LOW_MEMORY, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 }
1146
Wale Ogunwale60454db2015-01-23 16:05:07 -08001147 @Override
Jeff Hao1b012d32014-08-20 10:35:34 -07001148 public void profilerControl(boolean start, ProfilerInfo profilerInfo, int profileType) {
1149 sendMessage(H.PROFILER_CONTROL, profilerInfo, start ? 1 : 0, profileType);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001150 }
1151
Makoto Onuki4556b7b2017-07-07 14:58:58 -07001152 @Override
Christopher Ferris8d652f82017-04-11 16:29:18 -07001153 public void dumpHeap(boolean managed, boolean mallocInfo, boolean runGc, String path,
Makoto Onuki2c6657f2018-06-06 15:24:02 -07001154 ParcelFileDescriptor fd, RemoteCallback finishCallback) {
Andy McFadden824c5102010-07-09 16:26:57 -07001155 DumpHeapData dhd = new DumpHeapData();
Christopher Ferris8d652f82017-04-11 16:29:18 -07001156 dhd.managed = managed;
1157 dhd.mallocInfo = mallocInfo;
Makoto Onuki4556b7b2017-07-07 14:58:58 -07001158 dhd.runGc = runGc;
Andy McFadden824c5102010-07-09 16:26:57 -07001159 dhd.path = path;
Kweku Adams4af1b502019-05-23 16:23:48 -07001160 try {
1161 // Since we're going to dump the heap asynchronously, dup the file descriptor before
1162 // it's closed on returning from the IPC call.
1163 dhd.fd = fd.dup();
1164 } catch (IOException e) {
1165 Slog.e(TAG, "Failed to duplicate heap dump file descriptor", e);
1166 return;
1167 }
Makoto Onuki2c6657f2018-06-06 15:24:02 -07001168 dhd.finishCallback = finishCallback;
Christopher Ferris8d652f82017-04-11 16:29:18 -07001169 sendMessage(H.DUMP_HEAP, dhd, 0, 0, true /*async*/);
Andy McFadden824c5102010-07-09 16:26:57 -07001170 }
1171
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001172 public void attachAgent(String agent) {
1173 sendMessage(H.ATTACH_AGENT, agent);
1174 }
1175
Alex Light2d0691c2019-10-03 14:36:57 -07001176 public void attachStartupAgents(String dataDir) {
1177 sendMessage(H.ATTACH_STARTUP_AGENTS, dataDir);
1178 }
1179
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001180 public void setSchedulingGroup(int group) {
1181 // Note: do this immediately, since going into the foreground
1182 // should happen regardless of what pending work we have to do
1183 // and the activity manager will wait for us to report back that
1184 // we are done before sending us to the background.
1185 try {
1186 Process.setProcessGroup(Process.myPid(), group);
1187 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001188 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001189 }
1190 }
Bob Leee5408332009-09-04 18:31:17 -07001191
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001192 public void dispatchPackageBroadcast(int cmd, String[] packages) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001193 sendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001194 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001195
1196 public void scheduleCrash(String msg) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001197 sendMessage(H.SCHEDULE_CRASH, msg);
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001198 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07001199
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001200 public void dumpActivity(ParcelFileDescriptor pfd, IBinder activitytoken,
Dianne Hackborn30d71892010-12-11 10:37:55 -08001201 String prefix, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07001202 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001203 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001204 data.fd = pfd.dup();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001205 data.token = activitytoken;
1206 data.prefix = prefix;
1207 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001208 sendMessage(H.DUMP_ACTIVITY, data, 0, 0, true /*async*/);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001209 } catch (IOException e) {
1210 Slog.w(TAG, "dumpActivity failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001211 } finally {
1212 IoUtils.closeQuietly(pfd);
Dianne Hackborn625ac272010-09-17 18:29:22 -07001213 }
1214 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07001215
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001216 public void dumpProvider(ParcelFileDescriptor pfd, IBinder providertoken,
Marco Nelissen18cb2872011-11-15 11:19:53 -08001217 String[] args) {
1218 DumpComponentInfo data = new DumpComponentInfo();
1219 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001220 data.fd = pfd.dup();
Marco Nelissen18cb2872011-11-15 11:19:53 -08001221 data.token = providertoken;
1222 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001223 sendMessage(H.DUMP_PROVIDER, data, 0, 0, true /*async*/);
Marco Nelissen18cb2872011-11-15 11:19:53 -08001224 } catch (IOException e) {
1225 Slog.w(TAG, "dumpProvider failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001226 } finally {
1227 IoUtils.closeQuietly(pfd);
Marco Nelissen18cb2872011-11-15 11:19:53 -08001228 }
1229 }
1230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001232 public void dumpMemInfo(ParcelFileDescriptor pfd, Debug.MemoryInfo mem, boolean checkin,
Colin Crossc4fb5f92016-02-02 16:51:15 -08001233 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
1234 boolean dumpUnreachable, String[] args) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001235 FileOutputStream fout = new FileOutputStream(pfd.getFileDescriptor());
Dianne Hackborn8c841092013-06-24 13:46:13 -07001236 PrintWriter pw = new FastPrintWriter(fout);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001237 try {
Colin Crossc4fb5f92016-02-02 16:51:15 -08001238 dumpMemInfo(pw, mem, checkin, dumpFullInfo, dumpDalvik, dumpSummaryOnly, dumpUnreachable);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001239 } finally {
Chet Haase9c1e23b2011-03-24 10:51:31 -07001240 pw.flush();
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001241 IoUtils.closeQuietly(pfd);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001242 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001243 }
1244
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001245 private void dumpMemInfo(PrintWriter pw, Debug.MemoryInfo memInfo, boolean checkin,
Colin Crossc4fb5f92016-02-02 16:51:15 -08001246 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly, boolean dumpUnreachable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 long nativeMax = Debug.getNativeHeapSize() / 1024;
1248 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1249 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 Runtime runtime = Runtime.getRuntime();
Mathieu Chartierd288a262015-07-10 13:44:42 -07001252 runtime.gc(); // Do GC since countInstancesOfClass counts unreachable objects.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 long dalvikMax = runtime.totalMemory() / 1024;
1254 long dalvikFree = runtime.freeMemory() / 1024;
1255 long dalvikAllocated = dalvikMax - dalvikFree;
Richard Uhler2c036192016-09-14 09:48:31 +01001256
1257 Class[] classesToCount = new Class[] {
1258 ContextImpl.class,
1259 Activity.class,
1260 WebView.class,
1261 OpenSSLSocketImpl.class
1262 };
1263 long[] instanceCounts = VMDebug.countInstancesOfClasses(classesToCount, true);
1264 long appContextInstanceCount = instanceCounts[0];
1265 long activityInstanceCount = instanceCounts[1];
1266 long webviewInstanceCount = instanceCounts[2];
1267 long openSslSocketCount = instanceCounts[3];
1268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 long viewInstanceCount = ViewDebug.getViewInstanceCount();
Romain Guy65b345f2011-07-27 18:51:50 -07001270 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 int globalAssetCount = AssetManager.getGlobalAssetCount();
1272 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1273 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1274 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1275 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Dianne Hackbornfabb70b2014-11-11 12:22:36 -08001276 long parcelSize = Parcel.getGlobalAllocSize();
1277 long parcelCount = Parcel.getGlobalAllocCount();
Vasu Noric3849202010-03-09 10:47:25 -08001278 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -07001279
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07001280 dumpMemInfoTable(pw, memInfo, checkin, dumpFullInfo, dumpDalvik, dumpSummaryOnly,
1281 Process.myPid(),
Dianne Hackborne77187d2013-10-25 16:32:41 -07001282 (mBoundApplication != null) ? mBoundApplication.processName : "unknown",
1283 nativeMax, nativeAllocated, nativeFree,
1284 dalvikMax, dalvikAllocated, dalvikFree);
1285
Dianne Hackbornb437e092011-08-05 17:50:29 -07001286 if (checkin) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 // NOTE: if you change anything significant below, also consider changing
1288 // ACTIVITY_THREAD_CHECKIN_VERSION.
Anwar Ghuloum3c615062013-05-13 14:18:02 -07001289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 // Object counts
1291 pw.print(viewInstanceCount); pw.print(',');
1292 pw.print(viewRootInstanceCount); pw.print(',');
1293 pw.print(appContextInstanceCount); pw.print(',');
1294 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 pw.print(globalAssetCount); pw.print(',');
1297 pw.print(globalAssetManagerCount); pw.print(',');
1298 pw.print(binderLocalObjectCount); pw.print(',');
1299 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 pw.print(binderDeathObjectCount); pw.print(',');
1302 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 // SQL
Vasu Noric3849202010-03-09 10:47:25 -08001305 pw.print(stats.memoryUsed / 1024); pw.print(',');
Jeff Brown2a293b62012-01-19 14:02:22 -08001306 pw.print(stats.memoryUsed / 1024); pw.print(',');
1307 pw.print(stats.pageCacheOverflow / 1024); pw.print(',');
Dianne Hackbornb437e092011-08-05 17:50:29 -07001308 pw.print(stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001309 for (int i = 0; i < stats.dbStats.size(); i++) {
1310 DbStats dbStats = stats.dbStats.get(i);
Dianne Hackbornb437e092011-08-05 17:50:29 -07001311 pw.print(','); pw.print(dbStats.dbName);
1312 pw.print(','); pw.print(dbStats.pageSize);
1313 pw.print(','); pw.print(dbStats.dbSize);
1314 pw.print(','); pw.print(dbStats.lookaside);
1315 pw.print(','); pw.print(dbStats.cache);
1316 pw.print(','); pw.print(dbStats.cache);
Vasu Noric3849202010-03-09 10:47:25 -08001317 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07001318 pw.println();
Bob Leee5408332009-09-04 18:31:17 -07001319
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001320 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 }
Bob Leee5408332009-09-04 18:31:17 -07001322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 pw.println(" ");
1324 pw.println(" Objects");
Romain Guy65b345f2011-07-27 18:51:50 -07001325 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRootImpl:",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 viewRootInstanceCount);
1327
1328 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
1329 "Activities:", activityInstanceCount);
1330
1331 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
1332 "AssetManagers:", globalAssetManagerCount);
1333
1334 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
1335 "Proxy Binders:", binderProxyObjectCount);
Dianne Hackbornfabb70b2014-11-11 12:22:36 -08001336 printRow(pw, TWO_COUNT_COLUMNS, "Parcel memory:", parcelSize/1024,
1337 "Parcel count:", parcelCount);
1338 printRow(pw, TWO_COUNT_COLUMNS, "Death Recipients:", binderDeathObjectCount,
1339 "OpenSSL Sockets:", openSslSocketCount);
Richard Uhler2c036192016-09-14 09:48:31 +01001340 printRow(pw, ONE_COUNT_COLUMN, "WebViews:", webviewInstanceCount);
Bob Leee5408332009-09-04 18:31:17 -07001341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 // SQLite mem info
1343 pw.println(" ");
1344 pw.println(" SQL");
Jeff Brown2a293b62012-01-19 14:02:22 -08001345 printRow(pw, ONE_COUNT_COLUMN, "MEMORY_USED:", stats.memoryUsed / 1024);
1346 printRow(pw, TWO_COUNT_COLUMNS, "PAGECACHE_OVERFLOW:",
1347 stats.pageCacheOverflow / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001348 pw.println(" ");
1349 int N = stats.dbStats.size();
1350 if (N > 0) {
1351 pw.println(" DATABASES");
Kweku Adams983829f2017-12-06 14:53:50 -08001352 printRow(pw, DB_INFO_FORMAT, "pgsz", "dbsz", "Lookaside(b)", "cache",
Vasu Nori3c7131f2010-09-21 14:36:57 -07001353 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -08001354 for (int i = 0; i < N; i++) {
1355 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -07001356 printRow(pw, DB_INFO_FORMAT,
1357 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
1358 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
1359 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
1360 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -08001361 }
1362 }
Bob Leee5408332009-09-04 18:31:17 -07001363
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001364 // Asset details.
1365 String assetAlloc = AssetManager.getAssetAllocations();
1366 if (assetAlloc != null) {
1367 pw.println(" ");
1368 pw.println(" Asset Allocations");
1369 pw.print(assetAlloc);
1370 }
Colin Crossc4fb5f92016-02-02 16:51:15 -08001371
1372 // Unreachable native memory
1373 if (dumpUnreachable) {
1374 boolean showContents = ((mBoundApplication != null)
1375 && ((mBoundApplication.appInfo.flags&ApplicationInfo.FLAG_DEBUGGABLE) != 0))
1376 || android.os.Build.IS_DEBUGGABLE;
1377 pw.println(" ");
1378 pw.println(" Unreachable memory");
1379 pw.print(Debug.getUnreachableMemory(100, showContents));
1380 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001381 }
1382
1383 @Override
Kweku Adams983829f2017-12-06 14:53:50 -08001384 public void dumpMemInfoProto(ParcelFileDescriptor pfd, Debug.MemoryInfo mem,
1385 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
1386 boolean dumpUnreachable, String[] args) {
1387 ProtoOutputStream proto = new ProtoOutputStream(pfd.getFileDescriptor());
1388 try {
1389 dumpMemInfo(proto, mem, dumpFullInfo, dumpDalvik, dumpSummaryOnly, dumpUnreachable);
1390 } finally {
1391 proto.flush();
1392 IoUtils.closeQuietly(pfd);
1393 }
1394 }
1395
1396 private void dumpMemInfo(ProtoOutputStream proto, Debug.MemoryInfo memInfo,
1397 boolean dumpFullInfo, boolean dumpDalvik,
1398 boolean dumpSummaryOnly, boolean dumpUnreachable) {
1399 long nativeMax = Debug.getNativeHeapSize() / 1024;
1400 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1401 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1402
1403 Runtime runtime = Runtime.getRuntime();
1404 runtime.gc(); // Do GC since countInstancesOfClass counts unreachable objects.
1405 long dalvikMax = runtime.totalMemory() / 1024;
1406 long dalvikFree = runtime.freeMemory() / 1024;
1407 long dalvikAllocated = dalvikMax - dalvikFree;
1408
1409 Class[] classesToCount = new Class[] {
1410 ContextImpl.class,
1411 Activity.class,
1412 WebView.class,
1413 OpenSSLSocketImpl.class
1414 };
1415 long[] instanceCounts = VMDebug.countInstancesOfClasses(classesToCount, true);
1416 long appContextInstanceCount = instanceCounts[0];
1417 long activityInstanceCount = instanceCounts[1];
1418 long webviewInstanceCount = instanceCounts[2];
1419 long openSslSocketCount = instanceCounts[3];
1420
1421 long viewInstanceCount = ViewDebug.getViewInstanceCount();
1422 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
1423 int globalAssetCount = AssetManager.getGlobalAssetCount();
1424 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1425 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1426 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1427 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
1428 long parcelSize = Parcel.getGlobalAllocSize();
1429 long parcelCount = Parcel.getGlobalAllocCount();
1430 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
1431
Yi Jin2b30f322018-02-20 15:41:47 -08001432 final long mToken = proto.start(MemInfoDumpProto.AppData.PROCESS_MEMORY);
1433 proto.write(MemInfoDumpProto.ProcessMemory.PID, Process.myPid());
1434 proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME,
Kweku Adams983829f2017-12-06 14:53:50 -08001435 (mBoundApplication != null) ? mBoundApplication.processName : "unknown");
1436 dumpMemInfoTable(proto, memInfo, dumpDalvik, dumpSummaryOnly,
1437 nativeMax, nativeAllocated, nativeFree,
1438 dalvikMax, dalvikAllocated, dalvikFree);
1439 proto.end(mToken);
1440
Yi Jin2b30f322018-02-20 15:41:47 -08001441 final long oToken = proto.start(MemInfoDumpProto.AppData.OBJECTS);
1442 proto.write(MemInfoDumpProto.AppData.ObjectStats.VIEW_INSTANCE_COUNT,
1443 viewInstanceCount);
1444 proto.write(MemInfoDumpProto.AppData.ObjectStats.VIEW_ROOT_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001445 viewRootInstanceCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001446 proto.write(MemInfoDumpProto.AppData.ObjectStats.APP_CONTEXT_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001447 appContextInstanceCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001448 proto.write(MemInfoDumpProto.AppData.ObjectStats.ACTIVITY_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001449 activityInstanceCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001450 proto.write(MemInfoDumpProto.AppData.ObjectStats.GLOBAL_ASSET_COUNT,
1451 globalAssetCount);
1452 proto.write(MemInfoDumpProto.AppData.ObjectStats.GLOBAL_ASSET_MANAGER_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001453 globalAssetManagerCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001454 proto.write(MemInfoDumpProto.AppData.ObjectStats.LOCAL_BINDER_OBJECT_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001455 binderLocalObjectCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001456 proto.write(MemInfoDumpProto.AppData.ObjectStats.PROXY_BINDER_OBJECT_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001457 binderProxyObjectCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001458 proto.write(MemInfoDumpProto.AppData.ObjectStats.PARCEL_MEMORY_KB,
1459 parcelSize / 1024);
1460 proto.write(MemInfoDumpProto.AppData.ObjectStats.PARCEL_COUNT, parcelCount);
1461 proto.write(MemInfoDumpProto.AppData.ObjectStats.BINDER_OBJECT_DEATH_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001462 binderDeathObjectCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001463 proto.write(MemInfoDumpProto.AppData.ObjectStats.OPEN_SSL_SOCKET_COUNT,
1464 openSslSocketCount);
1465 proto.write(MemInfoDumpProto.AppData.ObjectStats.WEBVIEW_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001466 webviewInstanceCount);
1467 proto.end(oToken);
1468
1469 // SQLite mem info
Yi Jin2b30f322018-02-20 15:41:47 -08001470 final long sToken = proto.start(MemInfoDumpProto.AppData.SQL);
1471 proto.write(MemInfoDumpProto.AppData.SqlStats.MEMORY_USED_KB,
1472 stats.memoryUsed / 1024);
1473 proto.write(MemInfoDumpProto.AppData.SqlStats.PAGECACHE_OVERFLOW_KB,
Kweku Adams983829f2017-12-06 14:53:50 -08001474 stats.pageCacheOverflow / 1024);
Yi Jin2b30f322018-02-20 15:41:47 -08001475 proto.write(MemInfoDumpProto.AppData.SqlStats.MALLOC_SIZE_KB,
1476 stats.largestMemAlloc / 1024);
Kweku Adams983829f2017-12-06 14:53:50 -08001477 int n = stats.dbStats.size();
1478 for (int i = 0; i < n; i++) {
1479 DbStats dbStats = stats.dbStats.get(i);
1480
Yi Jin2b30f322018-02-20 15:41:47 -08001481 final long dToken = proto.start(MemInfoDumpProto.AppData.SqlStats.DATABASES);
1482 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.NAME, dbStats.dbName);
1483 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.PAGE_SIZE, dbStats.pageSize);
1484 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.DB_SIZE, dbStats.dbSize);
1485 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.LOOKASIDE_B,
1486 dbStats.lookaside);
1487 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.CACHE, dbStats.cache);
Kweku Adams983829f2017-12-06 14:53:50 -08001488 proto.end(dToken);
1489 }
1490 proto.end(sToken);
1491
1492 // Asset details.
1493 String assetAlloc = AssetManager.getAssetAllocations();
1494 if (assetAlloc != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08001495 proto.write(MemInfoDumpProto.AppData.ASSET_ALLOCATIONS, assetAlloc);
Kweku Adams983829f2017-12-06 14:53:50 -08001496 }
1497
1498 // Unreachable native memory
1499 if (dumpUnreachable) {
1500 int flags = mBoundApplication == null ? 0 : mBoundApplication.appInfo.flags;
1501 boolean showContents = (flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0
1502 || android.os.Build.IS_DEBUGGABLE;
Yi Jin2b30f322018-02-20 15:41:47 -08001503 proto.write(MemInfoDumpProto.AppData.UNREACHABLE_MEMORY,
Kweku Adams983829f2017-12-06 14:53:50 -08001504 Debug.getUnreachableMemory(100, showContents));
1505 }
1506 }
1507
1508 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001509 public void dumpGfxInfo(ParcelFileDescriptor pfd, String[] args) {
Chris Craikfc294242016-12-13 18:10:46 -08001510 nDumpGraphicsInfo(pfd.getFileDescriptor());
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001511 WindowManagerGlobal.getInstance().dumpGfxInfo(pfd.getFileDescriptor(), args);
1512 IoUtils.closeQuietly(pfd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 }
1514
Makoto Onuki016dc592018-08-14 12:26:45 -07001515 private File getDatabasesDir(Context context) {
1516 // There's no simple way to get the databases/ path, so do it this way.
1517 return context.getDatabasePath("a").getParentFile();
1518 }
1519
1520 private void dumpDatabaseInfo(ParcelFileDescriptor pfd, String[] args, boolean isSystem) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001521 PrintWriter pw = new FastPrintWriter(
1522 new FileOutputStream(pfd.getFileDescriptor()));
Jeff Brown6754ba22011-12-14 20:20:01 -08001523 PrintWriterPrinter printer = new PrintWriterPrinter(pw);
Makoto Onukiee93ad22018-10-18 16:24:13 -07001524 SQLiteDebug.dump(printer, args, isSystem);
Jeff Brown6754ba22011-12-14 20:20:01 -08001525 pw.flush();
1526 }
1527
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001528 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001529 public void dumpDbInfo(final ParcelFileDescriptor pfd, final String[] args) {
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001530 if (mSystemThread) {
Felipe Leme29de4922016-06-07 16:14:07 -07001531 // Ensure this invocation is asynchronous to prevent writer waiting if buffer cannot
1532 // be consumed. But it must duplicate the file descriptor first, since caller might
1533 // be closing it.
1534 final ParcelFileDescriptor dup;
1535 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001536 dup = pfd.dup();
Felipe Leme29de4922016-06-07 16:14:07 -07001537 } catch (IOException e) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001538 Log.w(TAG, "Could not dup FD " + pfd.getFileDescriptor().getInt$());
Felipe Leme29de4922016-06-07 16:14:07 -07001539 return;
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001540 } finally {
1541 IoUtils.closeQuietly(pfd);
Felipe Leme29de4922016-06-07 16:14:07 -07001542 }
1543
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001544 AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
1545 @Override
1546 public void run() {
Felipe Lemec74972f2016-06-08 09:12:37 -07001547 try {
Makoto Onuki016dc592018-08-14 12:26:45 -07001548 dumpDatabaseInfo(dup, args, true);
Felipe Lemec74972f2016-06-08 09:12:37 -07001549 } finally {
1550 IoUtils.closeQuietly(dup);
1551 }
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001552 }
1553 });
1554 } else {
Makoto Onuki016dc592018-08-14 12:26:45 -07001555 dumpDatabaseInfo(pfd, args, false);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001556 IoUtils.closeQuietly(pfd);
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001557 }
1558 }
1559
1560 @Override
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001561 public void unstableProviderDied(IBinder provider) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001562 sendMessage(H.UNSTABLE_PROVIDER_DIED, provider);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001563 }
1564
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001565 @Override
Adam Skorydfc7fd72013-08-05 19:23:41 -07001566 public void requestAssistContextExtras(IBinder activityToken, IBinder requestToken,
Svet Ganovfd31f852017-04-26 15:54:27 -07001567 int requestType, int sessionId, int flags) {
Adam Skorydfc7fd72013-08-05 19:23:41 -07001568 RequestAssistContextExtras cmd = new RequestAssistContextExtras();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001569 cmd.activityToken = activityToken;
1570 cmd.requestToken = requestToken;
1571 cmd.requestType = requestType;
Amith Yamasani4f128e42016-05-10 11:44:12 -07001572 cmd.sessionId = sessionId;
Svet Ganovfd31f852017-04-26 15:54:27 -07001573 cmd.flags = flags;
Jeff Brown9ef09972013-10-15 20:49:59 -07001574 sendMessage(H.REQUEST_ASSIST_CONTEXT_EXTRAS, cmd);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001575 }
1576
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08001577 public void setCoreSettings(Bundle coreSettings) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001578 sendMessage(H.SET_CORE_SETTINGS, coreSettings);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001579 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001580
1581 public void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) {
1582 UpdateCompatibilityData ucd = new UpdateCompatibilityData();
1583 ucd.pkg = pkg;
1584 ucd.info = info;
Jeff Brown9ef09972013-10-15 20:49:59 -07001585 sendMessage(H.UPDATE_PACKAGE_COMPATIBILITY_INFO, ucd);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001586 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001587
1588 public void scheduleTrimMemory(int level) {
Jorim Jaggib29e3182018-04-30 18:51:56 +02001589 final Runnable r = PooledLambda.obtainRunnable(ActivityThread::handleTrimMemory,
Yohei Yukawae2fa39e2018-09-22 13:13:10 -07001590 ActivityThread.this, level).recycleOnUse();
Jorim Jaggib29e3182018-04-30 18:51:56 +02001591 // Schedule trimming memory after drawing the frame to minimize jank-risk.
1592 Choreographer choreographer = Choreographer.getMainThreadInstance();
1593 if (choreographer != null) {
1594 choreographer.postCallback(Choreographer.CALLBACK_COMMIT, r, null);
1595 } else {
1596 mH.post(r);
1597 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001598 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001599
Craig Mautner5eda9b32013-07-02 11:58:16 -07001600 public void scheduleTranslucentConversionComplete(IBinder token, boolean drawComplete) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001601 sendMessage(H.TRANSLUCENT_CONVERSION_COMPLETE, token, drawComplete ? 1 : 0);
Craig Mautner5eda9b32013-07-02 11:58:16 -07001602 }
Dianne Hackborna413dc02013-07-12 12:02:55 -07001603
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001604 public void scheduleOnNewActivityOptions(IBinder token, Bundle options) {
Craig Mautnereb8abf72014-07-02 15:04:09 -07001605 sendMessage(H.ON_NEW_ACTIVITY_OPTIONS,
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001606 new Pair<IBinder, ActivityOptions>(token, ActivityOptions.fromBundle(options)));
Craig Mautnereb8abf72014-07-02 15:04:09 -07001607 }
1608
Dianne Hackborna413dc02013-07-12 12:02:55 -07001609 public void setProcessState(int state) {
1610 updateProcessState(state, true);
1611 }
1612
Sudheer Shanka84a48952017-03-08 18:19:01 -08001613 /**
1614 * Updates {@link #mNetworkBlockSeq}. This is used by ActivityManagerService to inform
1615 * the main thread that it needs to wait for the network rules to get updated before
1616 * launching an activity.
1617 */
1618 @Override
1619 public void setNetworkBlockSeq(long procStateSeq) {
1620 synchronized (mNetworkPolicyLock) {
1621 mNetworkBlockSeq = procStateSeq;
1622 }
1623 }
1624
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001625 @Override
1626 public void scheduleInstallProvider(ProviderInfo provider) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001627 sendMessage(H.INSTALL_PROVIDER, provider);
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001628 }
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001629
1630 @Override
Neil Fullerb7146fe2016-11-15 16:52:15 +00001631 public final void updateTimePrefs(int timeFormatPreference) {
1632 final Boolean timeFormatPreferenceBool;
1633 // For convenience we are using the Intent extra values.
1634 if (timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_12_HOUR) {
1635 timeFormatPreferenceBool = Boolean.FALSE;
1636 } else if (timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_24_HOUR) {
1637 timeFormatPreferenceBool = Boolean.TRUE;
1638 } else {
1639 // timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_LOCALE_DEFAULT
1640 // (or unknown).
1641 timeFormatPreferenceBool = null;
1642 }
1643 DateFormat.set24HourTimePref(timeFormatPreferenceBool);
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001644 }
Craig Mautneree2e45a2014-06-27 12:10:03 -07001645
1646 @Override
Craig Mautner8746a472014-07-24 15:12:54 -07001647 public void scheduleEnterAnimationComplete(IBinder token) {
1648 sendMessage(H.ENTER_ANIMATION_COMPLETE, token);
1649 }
Jeff Sharkey605eb792014-11-04 13:34:06 -08001650
1651 @Override
1652 public void notifyCleartextNetwork(byte[] firstPacket) {
1653 if (StrictMode.vmCleartextNetworkEnabled()) {
1654 StrictMode.onCleartextNetworkDetected(firstPacket);
1655 }
1656 }
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001657
1658 @Override
1659 public void startBinderTracking() {
1660 sendMessage(H.START_BINDER_TRACKING, null);
1661 }
1662
1663 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001664 public void stopBinderTrackingAndDump(ParcelFileDescriptor pfd) {
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001665 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001666 sendMessage(H.STOP_BINDER_TRACKING_AND_DUMP, pfd.dup());
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001667 } catch (IOException e) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001668 } finally {
1669 IoUtils.closeQuietly(pfd);
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001670 }
1671 }
Wale Ogunwale5f986092015-12-04 15:35:38 -08001672
1673 @Override
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001674 public void scheduleLocalVoiceInteractionStarted(IBinder token,
1675 IVoiceInteractor voiceInteractor) throws RemoteException {
1676 SomeArgs args = SomeArgs.obtain();
1677 args.arg1 = token;
1678 args.arg2 = voiceInteractor;
1679 sendMessage(H.LOCAL_VOICE_INTERACTION_STARTED, args);
1680 }
Chad Brubakerc72875b2016-04-27 16:35:11 -07001681
1682 @Override
1683 public void handleTrustStorageUpdate() {
1684 NetworkSecurityPolicy.getInstance().handleTrustStorageUpdate();
1685 }
Andrii Kulian446e8242017-10-26 15:17:29 -07001686
1687 @Override
1688 public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
1689 ActivityThread.this.scheduleTransaction(transaction);
1690 }
Sunny Goyald40c3452019-03-20 12:46:55 -07001691
1692 @Override
1693 public void requestDirectActions(@NonNull IBinder activityToken,
Svet Ganov3b6be082019-04-28 10:21:01 -07001694 @NonNull IVoiceInteractor interactor, @Nullable RemoteCallback cancellationCallback,
1695 @NonNull RemoteCallback callback) {
1696 final CancellationSignal cancellationSignal = new CancellationSignal();
Sunny Goyald40c3452019-03-20 12:46:55 -07001697 if (cancellationCallback != null) {
Svet Ganov3b6be082019-04-28 10:21:01 -07001698 final ICancellationSignal transport = createSafeCancellationTransport(
1699 cancellationSignal);
Sunny Goyald40c3452019-03-20 12:46:55 -07001700 final Bundle cancellationResult = new Bundle();
1701 cancellationResult.putBinder(VoiceInteractor.KEY_CANCELLATION_SIGNAL,
1702 transport.asBinder());
1703 cancellationCallback.sendResult(cancellationResult);
Sunny Goyald40c3452019-03-20 12:46:55 -07001704 }
Svet Ganov3b6be082019-04-28 10:21:01 -07001705 mH.sendMessage(PooledLambda.obtainMessage(ActivityThread::handleRequestDirectActions,
1706 ActivityThread.this, activityToken, interactor, cancellationSignal, callback));
1707 }
Sunny Goyald40c3452019-03-20 12:46:55 -07001708
Svet Ganov3b6be082019-04-28 10:21:01 -07001709 @Override
1710 public void performDirectAction(@NonNull IBinder activityToken, @NonNull String actionId,
1711 @Nullable Bundle arguments, @Nullable RemoteCallback cancellationCallback,
1712 @NonNull RemoteCallback resultCallback) {
1713 final CancellationSignal cancellationSignal = new CancellationSignal();
1714 if (cancellationCallback != null) {
1715 final ICancellationSignal transport = createSafeCancellationTransport(
1716 cancellationSignal);
1717 final Bundle cancellationResult = new Bundle();
1718 cancellationResult.putBinder(VoiceInteractor.KEY_CANCELLATION_SIGNAL,
1719 transport.asBinder());
1720 cancellationCallback.sendResult(cancellationResult);
1721 }
Sunny Goyald40c3452019-03-20 12:46:55 -07001722 mH.sendMessage(PooledLambda.obtainMessage(ActivityThread::handlePerformDirectAction,
1723 ActivityThread.this, activityToken, actionId, arguments,
1724 cancellationSignal, resultCallback));
1725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 }
1727
Svet Ganov3b6be082019-04-28 10:21:01 -07001728 private @NonNull SafeCancellationTransport createSafeCancellationTransport(
1729 @NonNull CancellationSignal cancellationSignal) {
1730 synchronized (ActivityThread.this) {
1731 if (mRemoteCancellations == null) {
1732 mRemoteCancellations = new ArrayMap<>();
1733 }
1734 final SafeCancellationTransport transport = new SafeCancellationTransport(
1735 this, cancellationSignal);
1736 mRemoteCancellations.put(transport, cancellationSignal);
1737 return transport;
1738 }
1739 }
1740
1741 private @NonNull CancellationSignal removeSafeCancellationTransport(
1742 @NonNull SafeCancellationTransport transport) {
1743 synchronized (ActivityThread.this) {
1744 final CancellationSignal cancellation = mRemoteCancellations.remove(transport);
1745 if (mRemoteCancellations.isEmpty()) {
1746 mRemoteCancellations = null;
1747 }
1748 return cancellation;
1749 }
1750 }
1751
1752 private static final class SafeCancellationTransport extends ICancellationSignal.Stub {
1753 private final @NonNull WeakReference<ActivityThread> mWeakActivityThread;
1754
1755 SafeCancellationTransport(@NonNull ActivityThread activityThread,
1756 @NonNull CancellationSignal cancellation) {
1757 mWeakActivityThread = new WeakReference<>(activityThread);
1758 }
1759
1760 @Override
1761 public void cancel() {
1762 final ActivityThread activityThread = mWeakActivityThread.get();
1763 if (activityThread != null) {
1764 final CancellationSignal cancellation = activityThread
1765 .removeSafeCancellationTransport(this);
1766 if (cancellation != null) {
1767 cancellation.cancel();
1768 }
1769 }
1770 }
1771 }
1772
Andrii Kulian446e8242017-10-26 15:17:29 -07001773 class H extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 public static final int BIND_APPLICATION = 110;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001775 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 public static final int EXIT_APPLICATION = 111;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001777 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 public static final int RECEIVER = 113;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001779 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 public static final int CREATE_SERVICE = 114;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001781 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 public static final int SERVICE_ARGS = 115;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001783 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 public static final int STOP_SERVICE = 116;
Dianne Hackborn09233282014-04-30 11:33:59 -07001785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 public static final int CONFIGURATION_CHANGED = 118;
1787 public static final int CLEAN_UP_CONTEXT = 119;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001788 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 public static final int GC_WHEN_IDLE = 120;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001790 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 public static final int BIND_SERVICE = 121;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001792 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 public static final int UNBIND_SERVICE = 122;
1794 public static final int DUMP_SERVICE = 123;
1795 public static final int LOW_MEMORY = 124;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001796 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001797 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001798 public static final int DESTROY_BACKUP_AGENT = 129;
1799 public static final int SUICIDE = 130;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001800 @UnsupportedAppUsage
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001801 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001802 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001803 @UnsupportedAppUsage
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001804 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -07001805 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001806 public static final int DUMP_ACTIVITY = 136;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001807 public static final int SLEEPING = 137;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001808 public static final int SET_CORE_SETTINGS = 138;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001809 public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001810 @UnsupportedAppUsage
Marco Nelissen18cb2872011-11-15 11:19:53 -08001811 public static final int DUMP_PROVIDER = 141;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001812 public static final int UNSTABLE_PROVIDER_DIED = 142;
Adam Skorydfc7fd72013-08-05 19:23:41 -07001813 public static final int REQUEST_ASSIST_CONTEXT_EXTRAS = 143;
Craig Mautner5eda9b32013-07-02 11:58:16 -07001814 public static final int TRANSLUCENT_CONVERSION_COMPLETE = 144;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001815 @UnsupportedAppUsage
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001816 public static final int INSTALL_PROVIDER = 145;
Craig Mautnereb8abf72014-07-02 15:04:09 -07001817 public static final int ON_NEW_ACTIVITY_OPTIONS = 146;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001818 @UnsupportedAppUsage
Craig Mautner8746a472014-07-24 15:12:54 -07001819 public static final int ENTER_ANIMATION_COMPLETE = 149;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001820 public static final int START_BINDER_TRACKING = 150;
1821 public static final int STOP_BINDER_TRACKING_AND_DUMP = 151;
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001822 public static final int LOCAL_VOICE_INTERACTION_STARTED = 154;
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001823 public static final int ATTACH_AGENT = 155;
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001824 public static final int APPLICATION_INFO_CHANGED = 156;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001825 public static final int RUN_ISOLATED_ENTRY_POINT = 158;
Andrii Kulian446e8242017-10-26 15:17:29 -07001826 public static final int EXECUTE_TRANSACTION = 159;
Andrii Kulian320e3b52018-05-03 16:26:25 -07001827 public static final int RELAUNCH_ACTIVITY = 160;
Tim Murray59f3dc12018-10-22 15:26:08 -07001828 public static final int PURGE_RESOURCES = 161;
Alex Light2d0691c2019-10-03 14:36:57 -07001829 public static final int ATTACH_STARTUP_AGENTS = 162;
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001832 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 switch (code) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 case BIND_APPLICATION: return "BIND_APPLICATION";
1835 case EXIT_APPLICATION: return "EXIT_APPLICATION";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 case RECEIVER: return "RECEIVER";
1837 case CREATE_SERVICE: return "CREATE_SERVICE";
1838 case SERVICE_ARGS: return "SERVICE_ARGS";
1839 case STOP_SERVICE: return "STOP_SERVICE";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1841 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1842 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1843 case BIND_SERVICE: return "BIND_SERVICE";
1844 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1845 case DUMP_SERVICE: return "DUMP_SERVICE";
1846 case LOW_MEMORY: return "LOW_MEMORY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001847 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001848 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1849 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001850 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001851 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001852 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001853 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -07001854 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -07001855 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001856 case SET_CORE_SETTINGS: return "SET_CORE_SETTINGS";
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001857 case UPDATE_PACKAGE_COMPATIBILITY_INFO: return "UPDATE_PACKAGE_COMPATIBILITY_INFO";
Marco Nelissen18cb2872011-11-15 11:19:53 -08001858 case DUMP_PROVIDER: return "DUMP_PROVIDER";
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001859 case UNSTABLE_PROVIDER_DIED: return "UNSTABLE_PROVIDER_DIED";
Adam Skorydfc7fd72013-08-05 19:23:41 -07001860 case REQUEST_ASSIST_CONTEXT_EXTRAS: return "REQUEST_ASSIST_CONTEXT_EXTRAS";
Craig Mautner5eda9b32013-07-02 11:58:16 -07001861 case TRANSLUCENT_CONVERSION_COMPLETE: return "TRANSLUCENT_CONVERSION_COMPLETE";
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001862 case INSTALL_PROVIDER: return "INSTALL_PROVIDER";
Craig Mautnereb8abf72014-07-02 15:04:09 -07001863 case ON_NEW_ACTIVITY_OPTIONS: return "ON_NEW_ACTIVITY_OPTIONS";
Craig Mautner8746a472014-07-24 15:12:54 -07001864 case ENTER_ANIMATION_COMPLETE: return "ENTER_ANIMATION_COMPLETE";
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001865 case LOCAL_VOICE_INTERACTION_STARTED: return "LOCAL_VOICE_INTERACTION_STARTED";
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001866 case ATTACH_AGENT: return "ATTACH_AGENT";
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001867 case APPLICATION_INFO_CHANGED: return "APPLICATION_INFO_CHANGED";
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001868 case RUN_ISOLATED_ENTRY_POINT: return "RUN_ISOLATED_ENTRY_POINT";
Andrii Kulian446e8242017-10-26 15:17:29 -07001869 case EXECUTE_TRANSACTION: return "EXECUTE_TRANSACTION";
Andrii Kulian320e3b52018-05-03 16:26:25 -07001870 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
Tim Murray59f3dc12018-10-22 15:26:08 -07001871 case PURGE_RESOURCES: return "PURGE_RESOURCES";
Alex Light2d0691c2019-10-03 14:36:57 -07001872 case ATTACH_STARTUP_AGENTS: return "ATTACH_STARTUP_AGENTS";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 }
1874 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001875 return Integer.toString(code);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 }
1877 public void handleMessage(Message msg) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001878 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 switch (msg.what) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 case BIND_APPLICATION:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001881 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 AppBindData data = (AppBindData)msg.obj;
1883 handleBindApplication(data);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001884 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 break;
1886 case EXIT_APPLICATION:
1887 if (mInitialApplication != null) {
1888 mInitialApplication.onTerminate();
1889 }
1890 Looper.myLooper().quit();
1891 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 case RECEIVER:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001893 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveComp");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 handleReceiver((ReceiverData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001895 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 break;
1897 case CREATE_SERVICE:
John Recke48e6da2019-06-20 14:59:51 -07001898 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1899 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1900 ("serviceCreate: " + String.valueOf(msg.obj)));
1901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 handleCreateService((CreateServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001903 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 break;
1905 case BIND_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001906 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 handleBindService((BindServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001908 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 break;
1910 case UNBIND_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001911 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceUnbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 handleUnbindService((BindServiceData)msg.obj);
Tim Murray59f3dc12018-10-22 15:26:08 -07001913 schedulePurgeIdler();
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001914 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 break;
1916 case SERVICE_ARGS:
John Recke48e6da2019-06-20 14:59:51 -07001917 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1918 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1919 ("serviceStart: " + String.valueOf(msg.obj)));
1920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 handleServiceArgs((ServiceArgsData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001922 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 break;
1924 case STOP_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001925 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 handleStopService((IBinder)msg.obj);
Tim Murray59f3dc12018-10-22 15:26:08 -07001927 schedulePurgeIdler();
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001928 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 case CONFIGURATION_CHANGED:
Andrii Kulian446e8242017-10-26 15:17:29 -07001931 handleConfigurationChanged((Configuration) msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 break;
1933 case CLEAN_UP_CONTEXT:
1934 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1935 cci.context.performFinalCleanup(cci.who, cci.what);
1936 break;
1937 case GC_WHEN_IDLE:
1938 scheduleGcIdler();
1939 break;
1940 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001941 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 break;
1943 case LOW_MEMORY:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001944 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "lowMemory");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 handleLowMemory();
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001946 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001948 case PROFILER_CONTROL:
Jeff Hao1b012d32014-08-20 10:35:34 -07001949 handleProfilerControl(msg.arg1 != 0, (ProfilerInfo)msg.obj, msg.arg2);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001950 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001951 case CREATE_BACKUP_AGENT:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001952 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupCreateAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001953 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001954 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate181fafa2009-05-14 11:12:14 -07001955 break;
1956 case DESTROY_BACKUP_AGENT:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001957 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupDestroyAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001958 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001959 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate181fafa2009-05-14 11:12:14 -07001960 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001961 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001962 Process.killProcess(Process.myPid());
1963 break;
1964 case REMOVE_PROVIDER:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001965 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "providerRemove");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001966 completeRemoveProvider((ProviderRefCount)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001967 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001968 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001969 case DISPATCH_PACKAGE_BROADCAST:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001970 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastPackage");
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001971 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001972 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001973 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001974 case SCHEDULE_CRASH:
1975 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001976 case DUMP_HEAP:
Christopher Ferris8d652f82017-04-11 16:29:18 -07001977 handleDumpHeap((DumpHeapData) msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001978 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001979 case DUMP_ACTIVITY:
1980 handleDumpActivity((DumpComponentInfo)msg.obj);
1981 break;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001982 case DUMP_PROVIDER:
1983 handleDumpProvider((DumpComponentInfo)msg.obj);
1984 break;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001985 case SET_CORE_SETTINGS:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001986 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setCoreSettings");
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001987 handleSetCoreSettings((Bundle) msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001988 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001989 break;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001990 case UPDATE_PACKAGE_COMPATIBILITY_INFO:
1991 handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001992 break;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001993 case UNSTABLE_PROVIDER_DIED:
1994 handleUnstableProviderDied((IBinder)msg.obj, false);
1995 break;
Adam Skorydfc7fd72013-08-05 19:23:41 -07001996 case REQUEST_ASSIST_CONTEXT_EXTRAS:
1997 handleRequestAssistContextExtras((RequestAssistContextExtras)msg.obj);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001998 break;
Craig Mautner5eda9b32013-07-02 11:58:16 -07001999 case TRANSLUCENT_CONVERSION_COMPLETE:
2000 handleTranslucentConversionComplete((IBinder)msg.obj, msg.arg1 == 1);
2001 break;
Jeff Sharkeydd97f422013-10-08 17:01:30 -07002002 case INSTALL_PROVIDER:
2003 handleInstallProvider((ProviderInfo) msg.obj);
2004 break;
Craig Mautnereb8abf72014-07-02 15:04:09 -07002005 case ON_NEW_ACTIVITY_OPTIONS:
2006 Pair<IBinder, ActivityOptions> pair = (Pair<IBinder, ActivityOptions>) msg.obj;
2007 onNewActivityOptions(pair.first, pair.second);
Dake Gu7ef70b02014-07-08 18:37:12 -07002008 break;
Craig Mautner8746a472014-07-24 15:12:54 -07002009 case ENTER_ANIMATION_COMPLETE:
2010 handleEnterAnimationComplete((IBinder) msg.obj);
2011 break;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04002012 case START_BINDER_TRACKING:
2013 handleStartBinderTracking();
2014 break;
2015 case STOP_BINDER_TRACKING_AND_DUMP:
2016 handleStopBinderTrackingAndDump((ParcelFileDescriptor) msg.obj);
2017 break;
Amith Yamasani0af6fa72016-01-17 15:36:19 -08002018 case LOCAL_VOICE_INTERACTION_STARTED:
2019 handleLocalVoiceInteractionStarted((IBinder) ((SomeArgs) msg.obj).arg1,
2020 (IVoiceInteractor) ((SomeArgs) msg.obj).arg2);
Amith Yamasani61019112017-01-10 15:05:00 -08002021 break;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08002022 case ATTACH_AGENT: {
2023 Application app = getApplication();
2024 handleAttachAgent((String) msg.obj, app != null ? app.mLoadedApk : null);
Amith Yamasani0af6fa72016-01-17 15:36:19 -08002025 break;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08002026 }
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01002027 case APPLICATION_INFO_CHANGED:
2028 mUpdatingSystemConfig = true;
2029 try {
2030 handleApplicationInfoChanged((ApplicationInfo) msg.obj);
2031 } finally {
2032 mUpdatingSystemConfig = false;
2033 }
2034 break;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04002035 case RUN_ISOLATED_ENTRY_POINT:
2036 handleRunIsolatedEntryPoint((String) ((SomeArgs) msg.obj).arg1,
2037 (String[]) ((SomeArgs) msg.obj).arg2);
2038 break;
Andrii Kulian446e8242017-10-26 15:17:29 -07002039 case EXECUTE_TRANSACTION:
Andrii Kulian04470682018-01-10 15:32:31 -08002040 final ClientTransaction transaction = (ClientTransaction) msg.obj;
2041 mTransactionExecutor.execute(transaction);
2042 if (isSystem()) {
2043 // Client transactions inside system process are recycled on the client side
2044 // instead of ClientLifecycleManager to avoid being cleared before this
2045 // message is handled.
2046 transaction.recycle();
2047 }
Andrii Kulian914aa7d2018-03-19 21:51:53 -07002048 // TODO(lifecycler): Recycle locally scheduled transactions.
Andrii Kulian446e8242017-10-26 15:17:29 -07002049 break;
Andrii Kulian320e3b52018-05-03 16:26:25 -07002050 case RELAUNCH_ACTIVITY:
2051 handleRelaunchActivityLocally((IBinder) msg.obj);
2052 break;
Tim Murray59f3dc12018-10-22 15:26:08 -07002053 case PURGE_RESOURCES:
2054 schedulePurgeIdler();
2055 break;
Alex Light2d0691c2019-10-03 14:36:57 -07002056 case ATTACH_STARTUP_AGENTS:
2057 handleAttachStartupAgents((String) msg.obj);
2058 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 }
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07002060 Object obj = msg.obj;
2061 if (obj instanceof SomeArgs) {
2062 ((SomeArgs) obj).recycle();
2063 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07002064 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 }
2066 }
2067
Romain Guy65b345f2011-07-27 18:51:50 -07002068 private class Idler implements MessageQueue.IdleHandler {
Craig Mautner48d0d182013-06-11 07:53:06 -07002069 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002071 ActivityClientRecord a = mNewActivities;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002072 boolean stopProfiling = false;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002073 if (mBoundApplication != null && mProfiler.profileFd != null
2074 && mProfiler.autoStopProfiler) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002075 stopProfiling = true;
2076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 if (a != null) {
2078 mNewActivities = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002079 IActivityTaskManager am = ActivityTaskManager.getService();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002080 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002082 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 TAG, "Reporting idle of " + a +
2084 " finished=" +
Romain Guy65b345f2011-07-27 18:51:50 -07002085 (a.activity != null && a.activity.mFinished));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 if (a.activity != null && !a.activity.mFinished) {
2087 try {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002088 am.activityIdle(a.token, a.createdConfig, stopProfiling);
Dianne Hackborne88846e2009-09-30 21:34:25 -07002089 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002091 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 }
2093 }
2094 prev = a;
2095 a = a.nextIdle;
2096 prev.nextIdle = null;
2097 } while (a != null);
2098 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002099 if (stopProfiling) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002100 mProfiler.stopProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002101 }
Riddle Hsu50e34002019-04-12 20:42:05 +08002102 applyPendingProcessState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 return false;
2104 }
2105 }
2106
2107 final class GcIdler implements MessageQueue.IdleHandler {
Craig Mautner48d0d182013-06-11 07:53:06 -07002108 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 public final boolean queueIdle() {
2110 doGcIfNeeded();
Makoto Onuki0a9ee1a2019-06-19 08:58:02 -07002111 purgePendingResources();
Tim Murray59f3dc12018-10-22 15:26:08 -07002112 return false;
2113 }
2114 }
2115
2116 final class PurgeIdler implements MessageQueue.IdleHandler {
2117 @Override
2118 public boolean queueIdle() {
Makoto Onuki0a9ee1a2019-06-19 08:58:02 -07002119 purgePendingResources();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 return false;
2121 }
2122 }
2123
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002124 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07002125 public static ActivityThread currentActivityThread() {
Jeff Sharkey66a017b2013-01-17 18:18:22 -08002126 return sCurrentActivityThread;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128
Wale Ogunwale9a6ef1e2015-06-02 13:41:00 -07002129 public static boolean isSystem() {
2130 return (sCurrentActivityThread != null) ? sCurrentActivityThread.mSystemThread : false;
2131 }
2132
Svetoslavfbf0eca2015-05-01 16:52:41 -07002133 public static String currentOpPackageName() {
2134 ActivityThread am = currentActivityThread();
2135 return (am != null && am.getApplication() != null)
2136 ? am.getApplication().getOpPackageName() : null;
2137 }
2138
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002139 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07002140 public static String currentPackageName() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002141 ActivityThread am = currentActivityThread();
2142 return (am != null && am.mBoundApplication != null)
Dianne Hackbornb57a50b2013-04-11 17:29:32 -07002143 ? am.mBoundApplication.appInfo.packageName : null;
2144 }
2145
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002146 @UnsupportedAppUsage
Dianne Hackbornb57a50b2013-04-11 17:29:32 -07002147 public static String currentProcessName() {
2148 ActivityThread am = currentActivityThread();
2149 return (am != null && am.mBoundApplication != null)
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002150 ? am.mBoundApplication.processName : null;
2151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002153 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07002154 public static Application currentApplication() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002155 ActivityThread am = currentActivityThread();
2156 return am != null ? am.mInitialApplication : null;
2157 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002158
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002159 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002160 public static IPackageManager getPackageManager() {
2161 if (sPackageManager != null) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002162 return sPackageManager;
2163 }
Todd Kennedy8f135982019-07-02 07:35:15 -07002164 final IBinder b = ServiceManager.getService("package");
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002165 sPackageManager = IPackageManager.Stub.asInterface(b);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002166 return sPackageManager;
2167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002168
Todd Kennedy8f135982019-07-02 07:35:15 -07002169 /** Returns the permission manager */
2170 public static IPermissionManager getPermissionManager() {
2171 if (sPermissionManager != null) {
2172 return sPermissionManager;
2173 }
2174 final IBinder b = ServiceManager.getService("permissionmgr");
2175 sPermissionManager = IPermissionManager.Stub.asInterface(b);
2176 return sPermissionManager;
2177 }
2178
Romain Guy65b345f2011-07-27 18:51:50 -07002179 private Configuration mMainThreadConfig = new Configuration();
Amith Yamasani4f128e42016-05-10 11:44:12 -07002180
Dianne Hackborn908aecc2012-07-31 16:37:34 -07002181 Configuration applyConfigCompatMainThread(int displayDensity, Configuration config,
2182 CompatibilityInfo compat) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002183 if (config == null) {
2184 return null;
2185 }
Craig Mautner48d0d182013-06-11 07:53:06 -07002186 if (!compat.supportsScreen()) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002187 mMainThreadConfig.setTo(config);
2188 config = mMainThreadConfig;
Dianne Hackborn908aecc2012-07-31 16:37:34 -07002189 compat.applyToConfiguration(displayDensity, config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002190 }
2191 return config;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002193
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002194 /**
Todd Kennedy39bfee52016-02-24 10:28:21 -08002195 * Creates the top level resources for the given package. Will return an existing
2196 * Resources if one has already been created.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002197 */
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07002198 Resources getTopLevelResources(String resDir, String[] splitResDirs, String[] overlayDirs,
Adam Lesinski082614c2016-03-04 14:33:47 -08002199 String[] libDirs, int displayId, LoadedApk pkgInfo) {
2200 return mResourcesManager.getResources(null, resDir, splitResDirs, overlayDirs, libDirs,
2201 displayId, null, pkgInfo.getCompatibilityInfo(), pkgInfo.getClassLoader());
Todd Kennedy39bfee52016-02-24 10:28:21 -08002202 }
2203
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002204 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002205 final Handler getHandler() {
2206 return mH;
2207 }
2208
Mathew Inwood8c854f82018-09-14 12:35:36 +01002209 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Todd Kennedy233a0b12018-01-29 20:30:24 +00002210 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
2211 int flags) {
2212 return getPackageInfo(packageName, compatInfo, flags, UserHandle.myUserId());
Amith Yamasani98edc952012-09-25 14:09:27 -07002213 }
2214
Todd Kennedy233a0b12018-01-29 20:30:24 +00002215 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
2216 int flags, int userId) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002217 final boolean differentUser = (UserHandle.myUserId() != userId);
Winson83708c82019-02-19 12:34:17 -08002218 ApplicationInfo ai;
2219 try {
2220 ai = getPackageManager().getApplicationInfo(packageName,
2221 PackageManager.GET_SHARED_LIBRARY_FILES
2222 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2223 (userId < 0) ? UserHandle.myUserId() : userId);
2224 } catch (RemoteException e) {
2225 throw e.rethrowFromSystemServer();
2226 }
2227
Craig Mautner88c05892013-06-28 09:47:45 -07002228 synchronized (mResourcesManager) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002229 WeakReference<LoadedApk> ref;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002230 if (differentUser) {
2231 // Caching not supported across users
2232 ref = null;
2233 } else if ((flags & Context.CONTEXT_INCLUDE_CODE) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 ref = mPackages.get(packageName);
2235 } else {
2236 ref = mResourcePackages.get(packageName);
2237 }
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002238
Todd Kennedy233a0b12018-01-29 20:30:24 +00002239 LoadedApk packageInfo = ref != null ? ref.get() : null;
Winson71cf3502019-04-09 18:00:08 -07002240 if (ai != null && packageInfo != null) {
2241 if (!isLoadedApkResourceDirsUpToDate(packageInfo, ai)) {
2242 packageInfo.updateApplicationInfo(ai, null);
2243 }
2244
Todd Kennedy233a0b12018-01-29 20:30:24 +00002245 if (packageInfo.isSecurityViolation()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002246 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
2247 throw new SecurityException(
2248 "Requesting code from " + packageName
2249 + " to be run in process "
2250 + mBoundApplication.processName
2251 + "/" + mBoundApplication.appInfo.uid);
2252 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00002253 return packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002254 }
2255 }
2256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002257 if (ai != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002258 return getPackageInfo(ai, compatInfo, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002259 }
2260
2261 return null;
2262 }
2263
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002264 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +00002265 public final LoadedApk getPackageInfo(ApplicationInfo ai, CompatibilityInfo compatInfo,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002266 int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
2268 boolean securityViolation = includeCode && ai.uid != 0
2269 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002270 ? !UserHandle.isSameApp(ai.uid, mBoundApplication.appInfo.uid)
Amith Yamasani742a6712011-05-04 14:49:28 -07002271 : true);
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002272 boolean registerPackage = includeCode && (flags&Context.CONTEXT_REGISTER_PACKAGE) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273 if ((flags&(Context.CONTEXT_INCLUDE_CODE
2274 |Context.CONTEXT_IGNORE_SECURITY))
2275 == Context.CONTEXT_INCLUDE_CODE) {
2276 if (securityViolation) {
2277 String msg = "Requesting code from " + ai.packageName
2278 + " (with uid " + ai.uid + ")";
2279 if (mBoundApplication != null) {
2280 msg = msg + " to be run in process "
2281 + mBoundApplication.processName + " (with uid "
2282 + mBoundApplication.appInfo.uid + ")";
2283 }
2284 throw new SecurityException(msg);
2285 }
2286 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00002287 return getPackageInfo(ai, compatInfo, null, securityViolation, includeCode,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002288 registerPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002289 }
2290
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002291 @Override
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002292 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +00002293 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002294 CompatibilityInfo compatInfo) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002295 return getPackageInfo(ai, compatInfo, null, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002296 }
2297
Mathew Inwood8c854f82018-09-14 12:35:36 +01002298 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Todd Kennedy233a0b12018-01-29 20:30:24 +00002299 public final LoadedApk peekPackageInfo(String packageName, boolean includeCode) {
Craig Mautner88c05892013-06-28 09:47:45 -07002300 synchronized (mResourcesManager) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002301 WeakReference<LoadedApk> ref;
2302 if (includeCode) {
2303 ref = mPackages.get(packageName);
2304 } else {
2305 ref = mResourcePackages.get(packageName);
2306 }
2307 return ref != null ? ref.get() : null;
2308 }
2309 }
2310
Todd Kennedy233a0b12018-01-29 20:30:24 +00002311 private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002312 ClassLoader baseLoader, boolean securityViolation, boolean includeCode,
2313 boolean registerPackage) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002314 final boolean differentUser = (UserHandle.myUserId() != UserHandle.getUserId(aInfo.uid));
Craig Mautner88c05892013-06-28 09:47:45 -07002315 synchronized (mResourcesManager) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002316 WeakReference<LoadedApk> ref;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002317 if (differentUser) {
2318 // Caching not supported across users
2319 ref = null;
2320 } else if (includeCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321 ref = mPackages.get(aInfo.packageName);
2322 } else {
2323 ref = mResourcePackages.get(aInfo.packageName);
2324 }
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002325
Todd Kennedy233a0b12018-01-29 20:30:24 +00002326 LoadedApk packageInfo = ref != null ? ref.get() : null;
Winson83708c82019-02-19 12:34:17 -08002327
Winson71cf3502019-04-09 18:00:08 -07002328 if (packageInfo != null) {
2329 if (!isLoadedApkResourceDirsUpToDate(packageInfo, aInfo)) {
2330 packageInfo.updateApplicationInfo(aInfo, null);
2331 }
Winson83708c82019-02-19 12:34:17 -08002332
Winson83708c82019-02-19 12:34:17 -08002333 return packageInfo;
2334 }
2335
2336 if (localLOGV) {
2337 Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338 : "Loading resource-only package ") + aInfo.packageName
2339 + " (in " + (mBoundApplication != null
Winson83708c82019-02-19 12:34:17 -08002340 ? mBoundApplication.processName : null)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002341 + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 }
Winson83708c82019-02-19 12:34:17 -08002343
2344 packageInfo =
2345 new LoadedApk(this, aInfo, compatInfo, baseLoader,
2346 securityViolation, includeCode
2347 && (aInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0, registerPackage);
2348
2349 if (mSystemThread && "android".equals(aInfo.packageName)) {
2350 packageInfo.installSystemApplicationInfo(aInfo,
2351 getSystemContext().mPackageInfo.getClassLoader());
2352 }
2353
2354 if (differentUser) {
2355 // Caching not supported across users
2356 } else if (includeCode) {
2357 mPackages.put(aInfo.packageName,
2358 new WeakReference<LoadedApk>(packageInfo));
2359 } else {
2360 mResourcePackages.put(aInfo.packageName,
2361 new WeakReference<LoadedApk>(packageInfo));
2362 }
2363
Todd Kennedy233a0b12018-01-29 20:30:24 +00002364 return packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 }
2366 }
2367
Winson71cf3502019-04-09 18:00:08 -07002368 private static boolean isLoadedApkResourceDirsUpToDate(LoadedApk loadedApk,
2369 ApplicationInfo appInfo) {
Winson83708c82019-02-19 12:34:17 -08002370 Resources packageResources = loadedApk.mResources;
2371 String[] overlayDirs = ArrayUtils.defeatNullable(loadedApk.getOverlayDirs());
2372 String[] resourceDirs = ArrayUtils.defeatNullable(appInfo.resourceDirs);
2373
2374 return (packageResources == null || packageResources.getAssets().isUpToDate())
2375 && overlayDirs.length == resourceDirs.length
2376 && ArrayUtils.containsAll(overlayDirs, resourceDirs);
2377 }
2378
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002379 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380 ActivityThread() {
Craig Mautner88c05892013-06-28 09:47:45 -07002381 mResourcesManager = ResourcesManager.getInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002382 }
2383
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002384 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 public ApplicationThread getApplicationThread()
2386 {
2387 return mAppThread;
2388 }
2389
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002390 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 public Instrumentation getInstrumentation()
2392 {
2393 return mInstrumentation;
2394 }
2395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396 public boolean isProfiling() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002397 return mProfiler != null && mProfiler.profileFile != null
2398 && mProfiler.profileFd == null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002399 }
2400
2401 public String getProfileFilePath() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002402 return mProfiler.profileFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 }
2404
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002405 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406 public Looper getLooper() {
2407 return mLooper;
2408 }
2409
Jeff Sharkey8439ac02017-12-12 17:26:23 -07002410 public Executor getExecutor() {
2411 return mExecutor;
2412 }
2413
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002414 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415 public Application getApplication() {
2416 return mInitialApplication;
2417 }
Bob Leee5408332009-09-04 18:31:17 -07002418
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002419 @UnsupportedAppUsage
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07002420 public String getProcessName() {
2421 return mBoundApplication.processName;
2422 }
Bob Leee5408332009-09-04 18:31:17 -07002423
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002424 @UnsupportedAppUsage
Dianne Hackborn21556372010-02-04 16:34:40 -08002425 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002426 synchronized (this) {
2427 if (mSystemContext == null) {
Jeff Browndefd4a62014-03-10 21:24:37 -07002428 mSystemContext = ContextImpl.createSystemContext(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 }
Jeff Browndefd4a62014-03-10 21:24:37 -07002430 return mSystemContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 }
2433
Adam Lesinskia82b6262017-03-21 16:56:17 -07002434 public ContextImpl getSystemUiContext() {
2435 synchronized (this) {
2436 if (mSystemUiContext == null) {
Adam Lesinski6f1a9172017-04-10 16:35:19 -07002437 mSystemUiContext = ContextImpl.createSystemUiContext(getSystemContext());
Adam Lesinskia82b6262017-03-21 16:56:17 -07002438 }
2439 return mSystemUiContext;
2440 }
2441 }
2442
lumark0b05f9e2018-11-26 15:09:06 +08002443 /**
2444 * Create the context instance base on system resources & display information which used for UI.
2445 * @param displayId The ID of the display where the UI is shown.
2446 * @see ContextImpl#createSystemUiContext(ContextImpl, int)
2447 */
2448 public ContextImpl createSystemUiContext(int displayId) {
2449 return ContextImpl.createSystemUiContext(getSystemUiContext(), displayId);
2450 }
2451
Narayan Kamath29564cd2014-08-07 10:57:40 +01002452 public void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
Mike Cleron432b7132009-09-24 15:28:29 -07002453 synchronized (this) {
Narayan Kamath29564cd2014-08-07 10:57:40 +01002454 getSystemContext().installSystemApplicationInfo(info, classLoader);
Adam Lesinskia82b6262017-03-21 16:56:17 -07002455 getSystemUiContext().installSystemApplicationInfo(info, classLoader);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002456
2457 // give ourselves a default profiler
2458 mProfiler = new Profiler();
Mike Cleron432b7132009-09-24 15:28:29 -07002459 }
2460 }
2461
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002462 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002463 void scheduleGcIdler() {
2464 if (!mGcIdlerScheduled) {
2465 mGcIdlerScheduled = true;
2466 Looper.myQueue().addIdleHandler(mGcIdler);
2467 }
2468 mH.removeMessages(H.GC_WHEN_IDLE);
2469 }
2470
2471 void unscheduleGcIdler() {
2472 if (mGcIdlerScheduled) {
2473 mGcIdlerScheduled = false;
2474 Looper.myQueue().removeIdleHandler(mGcIdler);
2475 }
2476 mH.removeMessages(H.GC_WHEN_IDLE);
2477 }
2478
Tim Murray59f3dc12018-10-22 15:26:08 -07002479 void schedulePurgeIdler() {
2480 if (!mPurgeIdlerScheduled) {
2481 mPurgeIdlerScheduled = true;
2482 Looper.myQueue().addIdleHandler(mPurgeIdler);
2483 }
2484 mH.removeMessages(H.PURGE_RESOURCES);
2485 }
2486
2487 void unschedulePurgeIdler() {
2488 if (mPurgeIdlerScheduled) {
2489 mPurgeIdlerScheduled = false;
2490 Looper.myQueue().removeIdleHandler(mPurgeIdler);
2491 }
2492 mH.removeMessages(H.PURGE_RESOURCES);
2493 }
2494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 void doGcIfNeeded() {
Makoto Onuki0a9ee1a2019-06-19 08:58:02 -07002496 doGcIfNeeded("bg");
2497 }
2498
2499 void doGcIfNeeded(String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 mGcIdlerScheduled = false;
2501 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002502 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 // + "m now=" + now);
2504 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002505 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
Makoto Onuki0a9ee1a2019-06-19 08:58:02 -07002506 BinderInternal.forceGc(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507 }
2508 }
2509
Jing Jia736da82019-08-06 15:08:02 -07002510 private static final String HEAP_FULL_COLUMN =
2511 "%13s %8s %8s %8s %8s %8s %8s %8s %8s %8s %8s %8s";
2512 private static final String HEAP_COLUMN =
2513 "%13s %8s %8s %8s %8s %8s %8s %8s %8s";
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002514 private static final String ONE_COUNT_COLUMN = "%21s %8d";
2515 private static final String TWO_COUNT_COLUMNS = "%21s %8d %21s %8d";
Jing Jia736da82019-08-06 15:08:02 -07002516 private static final String THREE_COUNT_COLUMNS = "%21s %8d %21s %8s %21s %8d";
2517 private static final String TWO_COUNT_COLUMN_HEADER = "%21s %8s %21s %8s";
2518 private static final String ONE_ALT_COUNT_COLUMN = "%21s %8s %21s %8d";
Dianne Hackborne77187d2013-10-25 16:32:41 -07002519
2520 // Formatting for checkin service - update version if row format changes
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002521 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 4;
Dianne Hackborne77187d2013-10-25 16:32:41 -07002522
2523 static void printRow(PrintWriter pw, String format, Object...objs) {
2524 pw.println(String.format(format, objs));
2525 }
2526
2527 public static void dumpMemInfoTable(PrintWriter pw, Debug.MemoryInfo memInfo, boolean checkin,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002528 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
2529 int pid, String processName,
Dianne Hackborne77187d2013-10-25 16:32:41 -07002530 long nativeMax, long nativeAllocated, long nativeFree,
2531 long dalvikMax, long dalvikAllocated, long dalvikFree) {
2532
2533 // For checkin, we print one long comma-separated list of values
2534 if (checkin) {
2535 // NOTE: if you change anything significant below, also consider changing
2536 // ACTIVITY_THREAD_CHECKIN_VERSION.
2537
2538 // Header
2539 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
2540 pw.print(pid); pw.print(',');
2541 pw.print(processName); pw.print(',');
2542
2543 // Heap info - max
2544 pw.print(nativeMax); pw.print(',');
2545 pw.print(dalvikMax); pw.print(',');
2546 pw.print("N/A,");
2547 pw.print(nativeMax + dalvikMax); pw.print(',');
2548
2549 // Heap info - allocated
2550 pw.print(nativeAllocated); pw.print(',');
2551 pw.print(dalvikAllocated); pw.print(',');
2552 pw.print("N/A,");
2553 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
2554
2555 // Heap info - free
2556 pw.print(nativeFree); pw.print(',');
2557 pw.print(dalvikFree); pw.print(',');
2558 pw.print("N/A,");
2559 pw.print(nativeFree + dalvikFree); pw.print(',');
2560
2561 // Heap info - proportional set size
2562 pw.print(memInfo.nativePss); pw.print(',');
2563 pw.print(memInfo.dalvikPss); pw.print(',');
2564 pw.print(memInfo.otherPss); pw.print(',');
2565 pw.print(memInfo.getTotalPss()); pw.print(',');
2566
2567 // Heap info - swappable set size
2568 pw.print(memInfo.nativeSwappablePss); pw.print(',');
2569 pw.print(memInfo.dalvikSwappablePss); pw.print(',');
2570 pw.print(memInfo.otherSwappablePss); pw.print(',');
2571 pw.print(memInfo.getTotalSwappablePss()); pw.print(',');
2572
2573 // Heap info - shared dirty
2574 pw.print(memInfo.nativeSharedDirty); pw.print(',');
2575 pw.print(memInfo.dalvikSharedDirty); pw.print(',');
2576 pw.print(memInfo.otherSharedDirty); pw.print(',');
2577 pw.print(memInfo.getTotalSharedDirty()); pw.print(',');
2578
2579 // Heap info - shared clean
2580 pw.print(memInfo.nativeSharedClean); pw.print(',');
2581 pw.print(memInfo.dalvikSharedClean); pw.print(',');
2582 pw.print(memInfo.otherSharedClean); pw.print(',');
2583 pw.print(memInfo.getTotalSharedClean()); pw.print(',');
2584
2585 // Heap info - private Dirty
2586 pw.print(memInfo.nativePrivateDirty); pw.print(',');
2587 pw.print(memInfo.dalvikPrivateDirty); pw.print(',');
2588 pw.print(memInfo.otherPrivateDirty); pw.print(',');
2589 pw.print(memInfo.getTotalPrivateDirty()); pw.print(',');
2590
2591 // Heap info - private Clean
2592 pw.print(memInfo.nativePrivateClean); pw.print(',');
2593 pw.print(memInfo.dalvikPrivateClean); pw.print(',');
2594 pw.print(memInfo.otherPrivateClean); pw.print(',');
2595 pw.print(memInfo.getTotalPrivateClean()); pw.print(',');
2596
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002597 // Heap info - swapped out
2598 pw.print(memInfo.nativeSwappedOut); pw.print(',');
2599 pw.print(memInfo.dalvikSwappedOut); pw.print(',');
2600 pw.print(memInfo.otherSwappedOut); pw.print(',');
2601 pw.print(memInfo.getTotalSwappedOut()); pw.print(',');
2602
2603 // Heap info - swapped out pss
2604 if (memInfo.hasSwappedOutPss) {
2605 pw.print(memInfo.nativeSwappedOutPss); pw.print(',');
2606 pw.print(memInfo.dalvikSwappedOutPss); pw.print(',');
2607 pw.print(memInfo.otherSwappedOutPss); pw.print(',');
2608 pw.print(memInfo.getTotalSwappedOutPss()); pw.print(',');
2609 } else {
2610 pw.print("N/A,");
2611 pw.print("N/A,");
2612 pw.print("N/A,");
2613 pw.print("N/A,");
2614 }
2615
Dianne Hackborne77187d2013-10-25 16:32:41 -07002616 // Heap info - other areas
2617 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
2618 pw.print(Debug.MemoryInfo.getOtherLabel(i)); pw.print(',');
2619 pw.print(memInfo.getOtherPss(i)); pw.print(',');
2620 pw.print(memInfo.getOtherSwappablePss(i)); pw.print(',');
2621 pw.print(memInfo.getOtherSharedDirty(i)); pw.print(',');
2622 pw.print(memInfo.getOtherSharedClean(i)); pw.print(',');
2623 pw.print(memInfo.getOtherPrivateDirty(i)); pw.print(',');
2624 pw.print(memInfo.getOtherPrivateClean(i)); pw.print(',');
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002625 pw.print(memInfo.getOtherSwappedOut(i)); pw.print(',');
2626 if (memInfo.hasSwappedOutPss) {
2627 pw.print(memInfo.getOtherSwappedOutPss(i)); pw.print(',');
2628 } else {
2629 pw.print("N/A,");
2630 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002631 }
2632 return;
2633 }
2634
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002635 if (!dumpSummaryOnly) {
2636 if (dumpFullInfo) {
2637 printRow(pw, HEAP_FULL_COLUMN, "", "Pss", "Pss", "Shared", "Private",
Martijn Coenene0764852016-01-07 17:04:22 -08002638 "Shared", "Private", memInfo.hasSwappedOutPss ? "SwapPss" : "Swap",
Jing Jia736da82019-08-06 15:08:02 -07002639 "Rss", "Heap", "Heap", "Heap");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002640 printRow(pw, HEAP_FULL_COLUMN, "", "Total", "Clean", "Dirty", "Dirty",
Jing Jia736da82019-08-06 15:08:02 -07002641 "Clean", "Clean", "Dirty", "Total",
Martijn Coenene0764852016-01-07 17:04:22 -08002642 "Size", "Alloc", "Free");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002643 printRow(pw, HEAP_FULL_COLUMN, "", "------", "------", "------", "------",
Jing Jia736da82019-08-06 15:08:02 -07002644 "------", "------", "------", "------", "------", "------", "------");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002645 printRow(pw, HEAP_FULL_COLUMN, "Native Heap", memInfo.nativePss,
2646 memInfo.nativeSwappablePss, memInfo.nativeSharedDirty,
2647 memInfo.nativePrivateDirty, memInfo.nativeSharedClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002648 memInfo.nativePrivateClean, memInfo.hasSwappedOutPss ?
Richard Uhler91702eb32017-06-23 16:54:25 +01002649 memInfo.nativeSwappedOutPss : memInfo.nativeSwappedOut,
Jing Jia736da82019-08-06 15:08:02 -07002650 memInfo.nativeRss, nativeMax, nativeAllocated, nativeFree);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002651 printRow(pw, HEAP_FULL_COLUMN, "Dalvik Heap", memInfo.dalvikPss,
2652 memInfo.dalvikSwappablePss, memInfo.dalvikSharedDirty,
2653 memInfo.dalvikPrivateDirty, memInfo.dalvikSharedClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002654 memInfo.dalvikPrivateClean, memInfo.hasSwappedOutPss ?
Richard Uhler91702eb32017-06-23 16:54:25 +01002655 memInfo.dalvikSwappedOutPss : memInfo.dalvikSwappedOut,
Jing Jia736da82019-08-06 15:08:02 -07002656 memInfo.dalvikRss, dalvikMax, dalvikAllocated, dalvikFree);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002657 } else {
2658 printRow(pw, HEAP_COLUMN, "", "Pss", "Private",
Martijn Coenene0764852016-01-07 17:04:22 -08002659 "Private", memInfo.hasSwappedOutPss ? "SwapPss" : "Swap",
Jing Jia736da82019-08-06 15:08:02 -07002660 "Rss", "Heap", "Heap", "Heap");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002661 printRow(pw, HEAP_COLUMN, "", "Total", "Dirty",
Jing Jia736da82019-08-06 15:08:02 -07002662 "Clean", "Dirty", "Total", "Size", "Alloc", "Free");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002663 printRow(pw, HEAP_COLUMN, "", "------", "------", "------",
Jing Jia736da82019-08-06 15:08:02 -07002664 "------", "------", "------", "------", "------", "------");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002665 printRow(pw, HEAP_COLUMN, "Native Heap", memInfo.nativePss,
2666 memInfo.nativePrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002667 memInfo.nativePrivateClean,
2668 memInfo.hasSwappedOutPss ? memInfo.nativeSwappedOutPss :
Jing Jia736da82019-08-06 15:08:02 -07002669 memInfo.nativeSwappedOut, memInfo.nativeRss,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002670 nativeMax, nativeAllocated, nativeFree);
2671 printRow(pw, HEAP_COLUMN, "Dalvik Heap", memInfo.dalvikPss,
2672 memInfo.dalvikPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002673 memInfo.dalvikPrivateClean,
2674 memInfo.hasSwappedOutPss ? memInfo.dalvikSwappedOutPss :
Jing Jia736da82019-08-06 15:08:02 -07002675 memInfo.dalvikSwappedOut, memInfo.dalvikRss,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002676 dalvikMax, dalvikAllocated, dalvikFree);
Dianne Hackborne77187d2013-10-25 16:32:41 -07002677 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002678
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002679 int otherPss = memInfo.otherPss;
2680 int otherSwappablePss = memInfo.otherSwappablePss;
2681 int otherSharedDirty = memInfo.otherSharedDirty;
2682 int otherPrivateDirty = memInfo.otherPrivateDirty;
2683 int otherSharedClean = memInfo.otherSharedClean;
2684 int otherPrivateClean = memInfo.otherPrivateClean;
2685 int otherSwappedOut = memInfo.otherSwappedOut;
Martijn Coenene0764852016-01-07 17:04:22 -08002686 int otherSwappedOutPss = memInfo.otherSwappedOutPss;
Jing Jia736da82019-08-06 15:08:02 -07002687 int otherRss = memInfo.otherRss;
Dianne Hackborne77187d2013-10-25 16:32:41 -07002688
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002689 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
Dianne Hackborne77187d2013-10-25 16:32:41 -07002690 final int myPss = memInfo.getOtherPss(i);
2691 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2692 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2693 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2694 final int mySharedClean = memInfo.getOtherSharedClean(i);
2695 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2696 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
Martijn Coenene0764852016-01-07 17:04:22 -08002697 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Jing Jia736da82019-08-06 15:08:02 -07002698 final int myRss = memInfo.getOtherRss(i);
Dianne Hackborne77187d2013-10-25 16:32:41 -07002699 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
Jing Jia736da82019-08-06 15:08:02 -07002700 || mySharedClean != 0 || myPrivateClean != 0 || myRss != 0
Martijn Coenene0764852016-01-07 17:04:22 -08002701 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Dianne Hackborne77187d2013-10-25 16:32:41 -07002702 if (dumpFullInfo) {
2703 printRow(pw, HEAP_FULL_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2704 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002705 mySharedClean, myPrivateClean,
2706 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
Jing Jia736da82019-08-06 15:08:02 -07002707 myRss, "", "", "");
Dianne Hackborne77187d2013-10-25 16:32:41 -07002708 } else {
2709 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2710 myPss, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002711 myPrivateClean,
2712 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
Jing Jia736da82019-08-06 15:08:02 -07002713 myRss, "", "", "");
Dianne Hackborne77187d2013-10-25 16:32:41 -07002714 }
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002715 otherPss -= myPss;
2716 otherSwappablePss -= mySwappablePss;
2717 otherSharedDirty -= mySharedDirty;
2718 otherPrivateDirty -= myPrivateDirty;
2719 otherSharedClean -= mySharedClean;
2720 otherPrivateClean -= myPrivateClean;
2721 otherSwappedOut -= mySwappedOut;
Martijn Coenene0764852016-01-07 17:04:22 -08002722 otherSwappedOutPss -= mySwappedOutPss;
Jing Jia736da82019-08-06 15:08:02 -07002723 otherRss -= myRss;
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002724 }
2725 }
2726
2727 if (dumpFullInfo) {
2728 printRow(pw, HEAP_FULL_COLUMN, "Unknown", otherPss, otherSwappablePss,
2729 otherSharedDirty, otherPrivateDirty, otherSharedClean, otherPrivateClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002730 memInfo.hasSwappedOutPss ? otherSwappedOutPss : otherSwappedOut,
Jing Jia736da82019-08-06 15:08:02 -07002731 otherRss, "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002732 printRow(pw, HEAP_FULL_COLUMN, "TOTAL", memInfo.getTotalPss(),
2733 memInfo.getTotalSwappablePss(),
2734 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
2735 memInfo.getTotalSharedClean(), memInfo.getTotalPrivateClean(),
Thierry Strudel9b511602016-02-25 17:46:38 -08002736 memInfo.hasSwappedOutPss ? memInfo.getTotalSwappedOutPss() :
Jing Jia736da82019-08-06 15:08:02 -07002737 memInfo.getTotalSwappedOut(), memInfo.getTotalRss(),
Martijn Coenene0764852016-01-07 17:04:22 -08002738 nativeMax+dalvikMax, nativeAllocated+dalvikAllocated,
2739 nativeFree+dalvikFree);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002740 } else {
2741 printRow(pw, HEAP_COLUMN, "Unknown", otherPss,
Martijn Coenene0764852016-01-07 17:04:22 -08002742 otherPrivateDirty, otherPrivateClean,
2743 memInfo.hasSwappedOutPss ? otherSwappedOutPss : otherSwappedOut,
Jing Jia736da82019-08-06 15:08:02 -07002744 otherRss, "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002745 printRow(pw, HEAP_COLUMN, "TOTAL", memInfo.getTotalPss(),
2746 memInfo.getTotalPrivateDirty(),
2747 memInfo.getTotalPrivateClean(),
Martijn Coenene0764852016-01-07 17:04:22 -08002748 memInfo.hasSwappedOutPss ? memInfo.getTotalSwappedOutPss() :
Jing Jia736da82019-08-06 15:08:02 -07002749 memInfo.getTotalSwappedOut(), memInfo.getTotalPss(),
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002750 nativeMax+dalvikMax,
2751 nativeAllocated+dalvikAllocated, nativeFree+dalvikFree);
2752 }
2753
2754 if (dumpDalvik) {
2755 pw.println(" ");
2756 pw.println(" Dalvik Details");
2757
2758 for (int i=Debug.MemoryInfo.NUM_OTHER_STATS;
2759 i<Debug.MemoryInfo.NUM_OTHER_STATS + Debug.MemoryInfo.NUM_DVK_STATS; i++) {
2760 final int myPss = memInfo.getOtherPss(i);
2761 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2762 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2763 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2764 final int mySharedClean = memInfo.getOtherSharedClean(i);
2765 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2766 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
Martijn Coenene0764852016-01-07 17:04:22 -08002767 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Jing Jia736da82019-08-06 15:08:02 -07002768 final int myRss = memInfo.getOtherRss(i);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002769 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
Martijn Coenene0764852016-01-07 17:04:22 -08002770 || mySharedClean != 0 || myPrivateClean != 0
2771 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002772 if (dumpFullInfo) {
2773 printRow(pw, HEAP_FULL_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2774 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002775 mySharedClean, myPrivateClean,
2776 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
Jing Jia736da82019-08-06 15:08:02 -07002777 myRss, "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002778 } else {
2779 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2780 myPss, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002781 myPrivateClean,
2782 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
Jing Jia736da82019-08-06 15:08:02 -07002783 myRss, "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002784 }
2785 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002786 }
2787 }
2788 }
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002789
2790 pw.println(" ");
2791 pw.println(" App Summary");
Jing Jia736da82019-08-06 15:08:02 -07002792 printRow(pw, TWO_COUNT_COLUMN_HEADER, "", "Pss(KB)", "", "Rss(KB)");
2793 printRow(pw, TWO_COUNT_COLUMN_HEADER, "", "------", "", "------");
2794 printRow(pw, TWO_COUNT_COLUMNS,
2795 "Java Heap:", memInfo.getSummaryJavaHeap(), "", memInfo.getSummaryJavaHeapRss());
2796 printRow(pw, TWO_COUNT_COLUMNS,
2797 "Native Heap:", memInfo.getSummaryNativeHeap(), "",
2798 memInfo.getSummaryNativeHeapRss());
2799 printRow(pw, TWO_COUNT_COLUMNS,
2800 "Code:", memInfo.getSummaryCode(), "", memInfo.getSummaryCodeRss());
2801 printRow(pw, TWO_COUNT_COLUMNS,
2802 "Stack:", memInfo.getSummaryStack(), "", memInfo.getSummaryStackRss());
2803 printRow(pw, TWO_COUNT_COLUMNS,
2804 "Graphics:", memInfo.getSummaryGraphics(), "", memInfo.getSummaryGraphicsRss());
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002805 printRow(pw, ONE_COUNT_COLUMN,
Jing Jia736da82019-08-06 15:08:02 -07002806 "Private Other:", memInfo.getSummaryPrivateOther());
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002807 printRow(pw, ONE_COUNT_COLUMN,
Jing Jia736da82019-08-06 15:08:02 -07002808 "System:", memInfo.getSummarySystem());
2809 printRow(pw, ONE_ALT_COUNT_COLUMN,
2810 "Unknown:", "", "", memInfo.getSummaryUnknownRss());
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002811 pw.println(" ");
Martijn Coenene0764852016-01-07 17:04:22 -08002812 if (memInfo.hasSwappedOutPss) {
Jing Jia736da82019-08-06 15:08:02 -07002813 printRow(pw, THREE_COUNT_COLUMNS,
2814 "TOTAL PSS:", memInfo.getSummaryTotalPss(),
2815 "TOTAL RSS:", memInfo.getTotalRss(),
2816 "TOTAL SWAP PSS:", memInfo.getSummaryTotalSwapPss());
Martijn Coenene0764852016-01-07 17:04:22 -08002817 } else {
Jing Jia736da82019-08-06 15:08:02 -07002818 printRow(pw, THREE_COUNT_COLUMNS,
2819 "TOTAL PSS:", memInfo.getSummaryTotalPss(),
2820 "TOTAL RSS:", memInfo.getTotalRss(),
2821 "TOTAL SWAP (KB):", memInfo.getSummaryTotalSwap());
Martijn Coenene0764852016-01-07 17:04:22 -08002822 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002823 }
2824
Kweku Adams598e9a22017-11-02 17:12:20 -07002825 /**
2826 * Dump heap info to proto.
2827 *
2828 * @param hasSwappedOutPss determines whether to use dirtySwap or dirtySwapPss
2829 */
Kweku Adams983829f2017-12-06 14:53:50 -08002830 private static void dumpMemoryInfo(ProtoOutputStream proto, long fieldId, String name,
Kweku Adams598e9a22017-11-02 17:12:20 -07002831 int pss, int cleanPss, int sharedDirty, int privateDirty,
2832 int sharedClean, int privateClean,
Jing Jia736da82019-08-06 15:08:02 -07002833 boolean hasSwappedOutPss, int dirtySwap, int dirtySwapPss, int rss) {
Kweku Adams598e9a22017-11-02 17:12:20 -07002834 final long token = proto.start(fieldId);
2835
Yi Jin2b30f322018-02-20 15:41:47 -08002836 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.NAME, name);
2837 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.TOTAL_PSS_KB, pss);
2838 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.CLEAN_PSS_KB, cleanPss);
2839 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.SHARED_DIRTY_KB, sharedDirty);
2840 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.PRIVATE_DIRTY_KB, privateDirty);
2841 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.SHARED_CLEAN_KB, sharedClean);
2842 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.PRIVATE_CLEAN_KB, privateClean);
Kweku Adams598e9a22017-11-02 17:12:20 -07002843 if (hasSwappedOutPss) {
Yi Jin2b30f322018-02-20 15:41:47 -08002844 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.DIRTY_SWAP_PSS_KB, dirtySwapPss);
Kweku Adams598e9a22017-11-02 17:12:20 -07002845 } else {
Yi Jin2b30f322018-02-20 15:41:47 -08002846 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.DIRTY_SWAP_KB, dirtySwap);
Kweku Adams598e9a22017-11-02 17:12:20 -07002847 }
Jing Jia736da82019-08-06 15:08:02 -07002848 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.TOTAL_RSS_KB, rss);
Kweku Adams598e9a22017-11-02 17:12:20 -07002849
2850 proto.end(token);
2851 }
2852
2853 /**
2854 * Dump mem info data to proto.
2855 */
2856 public static void dumpMemInfoTable(ProtoOutputStream proto, Debug.MemoryInfo memInfo,
2857 boolean dumpDalvik, boolean dumpSummaryOnly,
2858 long nativeMax, long nativeAllocated, long nativeFree,
2859 long dalvikMax, long dalvikAllocated, long dalvikFree) {
2860
2861 if (!dumpSummaryOnly) {
Yi Jin2b30f322018-02-20 15:41:47 -08002862 final long nhToken = proto.start(MemInfoDumpProto.ProcessMemory.NATIVE_HEAP);
2863 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "Native Heap",
Kweku Adams598e9a22017-11-02 17:12:20 -07002864 memInfo.nativePss, memInfo.nativeSwappablePss, memInfo.nativeSharedDirty,
2865 memInfo.nativePrivateDirty, memInfo.nativeSharedClean,
2866 memInfo.nativePrivateClean, memInfo.hasSwappedOutPss,
Jing Jia736da82019-08-06 15:08:02 -07002867 memInfo.nativeSwappedOut, memInfo.nativeSwappedOutPss,
2868 memInfo.nativeRss);
Yi Jin2b30f322018-02-20 15:41:47 -08002869 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB, nativeMax);
2870 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB, nativeAllocated);
2871 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB, nativeFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002872 proto.end(nhToken);
2873
Yi Jin2b30f322018-02-20 15:41:47 -08002874 final long dvToken = proto.start(MemInfoDumpProto.ProcessMemory.DALVIK_HEAP);
2875 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "Dalvik Heap",
Kweku Adams598e9a22017-11-02 17:12:20 -07002876 memInfo.dalvikPss, memInfo.dalvikSwappablePss, memInfo.dalvikSharedDirty,
2877 memInfo.dalvikPrivateDirty, memInfo.dalvikSharedClean,
2878 memInfo.dalvikPrivateClean, memInfo.hasSwappedOutPss,
Jing Jia736da82019-08-06 15:08:02 -07002879 memInfo.dalvikSwappedOut, memInfo.dalvikSwappedOutPss,
2880 memInfo.dalvikRss);
Yi Jin2b30f322018-02-20 15:41:47 -08002881 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB, dalvikMax);
2882 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB, dalvikAllocated);
2883 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB, dalvikFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002884 proto.end(dvToken);
2885
2886 int otherPss = memInfo.otherPss;
2887 int otherSwappablePss = memInfo.otherSwappablePss;
2888 int otherSharedDirty = memInfo.otherSharedDirty;
2889 int otherPrivateDirty = memInfo.otherPrivateDirty;
2890 int otherSharedClean = memInfo.otherSharedClean;
2891 int otherPrivateClean = memInfo.otherPrivateClean;
2892 int otherSwappedOut = memInfo.otherSwappedOut;
2893 int otherSwappedOutPss = memInfo.otherSwappedOutPss;
Jing Jia736da82019-08-06 15:08:02 -07002894 int otherRss = memInfo.otherRss;
Kweku Adams598e9a22017-11-02 17:12:20 -07002895
2896 for (int i = 0; i < Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
2897 final int myPss = memInfo.getOtherPss(i);
2898 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2899 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2900 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2901 final int mySharedClean = memInfo.getOtherSharedClean(i);
2902 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2903 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
2904 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Jing Jia736da82019-08-06 15:08:02 -07002905 final int myRss = memInfo.getOtherRss(i);
Kweku Adams598e9a22017-11-02 17:12:20 -07002906 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
Jing Jia736da82019-08-06 15:08:02 -07002907 || mySharedClean != 0 || myPrivateClean != 0 || myRss != 0
Kweku Adams598e9a22017-11-02 17:12:20 -07002908 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Yi Jin2b30f322018-02-20 15:41:47 -08002909 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.OTHER_HEAPS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002910 Debug.MemoryInfo.getOtherLabel(i),
2911 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
2912 mySharedClean, myPrivateClean,
Jing Jia736da82019-08-06 15:08:02 -07002913 memInfo.hasSwappedOutPss, mySwappedOut, mySwappedOutPss, myRss);
Kweku Adams598e9a22017-11-02 17:12:20 -07002914
2915 otherPss -= myPss;
2916 otherSwappablePss -= mySwappablePss;
2917 otherSharedDirty -= mySharedDirty;
2918 otherPrivateDirty -= myPrivateDirty;
2919 otherSharedClean -= mySharedClean;
2920 otherPrivateClean -= myPrivateClean;
2921 otherSwappedOut -= mySwappedOut;
2922 otherSwappedOutPss -= mySwappedOutPss;
Jing Jia736da82019-08-06 15:08:02 -07002923 otherRss -= myRss;
Kweku Adams598e9a22017-11-02 17:12:20 -07002924 }
2925 }
2926
Yi Jin2b30f322018-02-20 15:41:47 -08002927 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.UNKNOWN_HEAP, "Unknown",
Kweku Adams598e9a22017-11-02 17:12:20 -07002928 otherPss, otherSwappablePss,
2929 otherSharedDirty, otherPrivateDirty, otherSharedClean, otherPrivateClean,
Jing Jia736da82019-08-06 15:08:02 -07002930 memInfo.hasSwappedOutPss, otherSwappedOut, otherSwappedOutPss, otherRss);
Yi Jin2b30f322018-02-20 15:41:47 -08002931 final long tToken = proto.start(MemInfoDumpProto.ProcessMemory.TOTAL_HEAP);
2932 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "TOTAL",
Kweku Adams598e9a22017-11-02 17:12:20 -07002933 memInfo.getTotalPss(), memInfo.getTotalSwappablePss(),
2934 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
2935 memInfo.getTotalSharedClean(), memInfo.getTotalPrivateClean(),
2936 memInfo.hasSwappedOutPss, memInfo.getTotalSwappedOut(),
Jing Jia736da82019-08-06 15:08:02 -07002937 memInfo.getTotalSwappedOutPss(), memInfo.getTotalRss());
Yi Jin2b30f322018-02-20 15:41:47 -08002938 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB,
2939 nativeMax + dalvikMax);
2940 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002941 nativeAllocated + dalvikAllocated);
Yi Jin2b30f322018-02-20 15:41:47 -08002942 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB,
2943 nativeFree + dalvikFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002944 proto.end(tToken);
2945
2946 if (dumpDalvik) {
2947 for (int i = Debug.MemoryInfo.NUM_OTHER_STATS;
2948 i < Debug.MemoryInfo.NUM_OTHER_STATS + Debug.MemoryInfo.NUM_DVK_STATS;
2949 i++) {
2950 final int myPss = memInfo.getOtherPss(i);
2951 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2952 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2953 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2954 final int mySharedClean = memInfo.getOtherSharedClean(i);
2955 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2956 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
2957 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Jing Jia736da82019-08-06 15:08:02 -07002958 final int myRss = memInfo.getOtherRss(i);
Kweku Adams598e9a22017-11-02 17:12:20 -07002959 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
2960 || mySharedClean != 0 || myPrivateClean != 0
2961 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Yi Jin2b30f322018-02-20 15:41:47 -08002962 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.DALVIK_DETAILS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002963 Debug.MemoryInfo.getOtherLabel(i),
2964 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
2965 mySharedClean, myPrivateClean,
Jing Jia736da82019-08-06 15:08:02 -07002966 memInfo.hasSwappedOutPss, mySwappedOut, mySwappedOutPss, myRss);
Kweku Adams598e9a22017-11-02 17:12:20 -07002967 }
2968 }
2969 }
2970 }
2971
Yi Jin2b30f322018-02-20 15:41:47 -08002972 final long asToken = proto.start(MemInfoDumpProto.ProcessMemory.APP_SUMMARY);
2973 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.JAVA_HEAP_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002974 memInfo.getSummaryJavaHeap());
Yi Jin2b30f322018-02-20 15:41:47 -08002975 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.NATIVE_HEAP_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002976 memInfo.getSummaryNativeHeap());
Yi Jin2b30f322018-02-20 15:41:47 -08002977 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.CODE_PSS_KB,
2978 memInfo.getSummaryCode());
2979 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.STACK_PSS_KB,
2980 memInfo.getSummaryStack());
2981 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.GRAPHICS_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002982 memInfo.getSummaryGraphics());
Yi Jin2b30f322018-02-20 15:41:47 -08002983 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.PRIVATE_OTHER_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002984 memInfo.getSummaryPrivateOther());
Yi Jin2b30f322018-02-20 15:41:47 -08002985 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.SYSTEM_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002986 memInfo.getSummarySystem());
2987 if (memInfo.hasSwappedOutPss) {
Yi Jin2b30f322018-02-20 15:41:47 -08002988 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.TOTAL_SWAP_PSS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002989 memInfo.getSummaryTotalSwapPss());
2990 } else {
Yi Jin2b30f322018-02-20 15:41:47 -08002991 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.TOTAL_SWAP_PSS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002992 memInfo.getSummaryTotalSwap());
2993 }
Jing Jia736da82019-08-06 15:08:02 -07002994 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.JAVA_HEAP_RSS_KB,
2995 memInfo.getSummaryJavaHeapRss());
2996 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.NATIVE_HEAP_RSS_KB,
2997 memInfo.getSummaryNativeHeapRss());
2998 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.CODE_RSS_KB,
2999 memInfo.getSummaryCodeRss());
3000 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.STACK_RSS_KB,
3001 memInfo.getSummaryStackRss());
3002 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.GRAPHICS_RSS_KB,
3003 memInfo.getSummaryGraphicsRss());
3004 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.UNKNOWN_RSS_KB,
3005 memInfo.getSummaryUnknownRss());
3006
Kweku Adams598e9a22017-11-02 17:12:20 -07003007 proto.end(asToken);
3008 }
3009
Mathew Inwood61e8ae62018-08-14 14:17:44 +01003010 @UnsupportedAppUsage
Jeff Hamilton52d32032011-01-08 15:31:26 -06003011 public void registerOnActivityPausedListener(Activity activity,
3012 OnActivityPausedListener listener) {
3013 synchronized (mOnPauseListeners) {
3014 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
3015 if (list == null) {
3016 list = new ArrayList<OnActivityPausedListener>();
3017 mOnPauseListeners.put(activity, list);
3018 }
3019 list.add(listener);
3020 }
3021 }
3022
Mathew Inwood61e8ae62018-08-14 14:17:44 +01003023 @UnsupportedAppUsage
Jeff Hamiltonce3224c2011-01-17 11:05:03 -08003024 public void unregisterOnActivityPausedListener(Activity activity,
3025 OnActivityPausedListener listener) {
3026 synchronized (mOnPauseListeners) {
3027 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
3028 if (list != null) {
3029 list.remove(listener);
3030 }
3031 }
3032 }
3033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003034 public final ActivityInfo resolveActivityInfo(Intent intent) {
3035 ActivityInfo aInfo = intent.resolveActivityInfo(
3036 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
3037 if (aInfo == null) {
3038 // Throw an exception.
3039 Instrumentation.checkStartActivityResult(
Dianne Hackborna4972e92012-03-14 10:38:05 -07003040 ActivityManager.START_CLASS_NOT_FOUND, intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003041 }
3042 return aInfo;
3043 }
Bob Leee5408332009-09-04 18:31:17 -07003044
Mathew Inwood8c854f82018-09-14 12:35:36 +01003045 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003046 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Sunny Goyald40c3452019-03-20 12:46:55 -07003048 Activity.NonConfigurationInstances lastNonConfigurationInstances, IBinder assistToken) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003049 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003050 r.token = token;
Sunny Goyald40c3452019-03-20 12:46:55 -07003051 r.assistToken = assistToken;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003052 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003053 r.intent = intent;
3054 r.state = state;
3055 r.parent = parent;
3056 r.embeddedID = id;
3057 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003058 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003059 if (localLOGV) {
3060 ComponentName compname = intent.getComponent();
3061 String name;
3062 if (compname != null) {
3063 name = compname.toShortString();
3064 } else {
3065 name = "(Intent " + intent + ").getComponent() returned null";
3066 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003067 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003068 + ", comp=" + name
3069 + ", token=" + token);
3070 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003071 // TODO(lifecycler): Can't switch to use #handleLaunchActivity() because it will try to
3072 // call #reportSizeConfigurations(), but the server might not know anything about the
3073 // activity if it was launched from LocalAcvitivyManager.
Andrii Kulian770c4032018-05-02 18:40:59 -07003074 return performLaunchActivity(r, null /* customIntent */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075 }
3076
Mathew Inwood61e8ae62018-08-14 14:17:44 +01003077 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003078 public final Activity getActivity(IBinder token) {
Andrii Kuliand56ed0c2018-06-14 12:22:18 -07003079 final ActivityClientRecord activityRecord = mActivities.get(token);
3080 return activityRecord != null ? activityRecord.activity : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003081 }
3082
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003083 @Override
3084 public ActivityClientRecord getActivityClient(IBinder token) {
3085 return mActivities.get(token);
3086 }
3087
Riddle Hsu50e34002019-04-12 20:42:05 +08003088 @Override
3089 public void updatePendingConfiguration(Configuration config) {
3090 synchronized (mResourcesManager) {
3091 if (mPendingConfiguration == null || mPendingConfiguration.isOtherSeqNewer(config)) {
3092 mPendingConfiguration = config;
3093 }
3094 }
3095 }
3096
3097 @Override
3098 public void updateProcessState(int processState, boolean fromIpc) {
3099 synchronized (mAppThread) {
3100 if (mLastProcessState == processState) {
3101 return;
3102 }
3103 mLastProcessState = processState;
3104 // Defer the top state for VM to avoid aggressive JIT compilation affecting activity
3105 // launch time.
3106 if (processState == ActivityManager.PROCESS_STATE_TOP
3107 && mNumLaunchingActivities.get() > 0) {
3108 mPendingProcessState = processState;
3109 mH.postDelayed(this::applyPendingProcessState, PENDING_TOP_PROCESS_STATE_TIMEOUT);
3110 } else {
3111 mPendingProcessState = PROCESS_STATE_UNKNOWN;
3112 updateVmProcessState(processState);
3113 }
3114 if (localLOGV) {
3115 Slog.i(TAG, "******************* PROCESS STATE CHANGED TO: " + processState
3116 + (fromIpc ? " (from ipc" : ""));
3117 }
3118 }
3119 }
3120
3121 /** Update VM state based on ActivityManager.PROCESS_STATE_* constants. */
3122 private void updateVmProcessState(int processState) {
3123 // TODO: Tune this since things like gmail sync are important background but not jank
3124 // perceptible.
3125 final int state = processState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
3126 ? VM_PROCESS_STATE_JANK_PERCEPTIBLE
3127 : VM_PROCESS_STATE_JANK_IMPERCEPTIBLE;
3128 VMRuntime.getRuntime().updateProcessState(state);
3129 }
3130
3131 private void applyPendingProcessState() {
3132 synchronized (mAppThread) {
3133 if (mPendingProcessState == PROCESS_STATE_UNKNOWN) {
3134 return;
3135 }
3136 final int pendingState = mPendingProcessState;
3137 mPendingProcessState = PROCESS_STATE_UNKNOWN;
3138 // Only apply the pending state if the last state doesn't change.
3139 if (pendingState == mLastProcessState) {
3140 updateVmProcessState(pendingState);
3141 }
3142 }
3143 }
3144
3145 @Override
3146 public void countLaunchingActivities(int num) {
3147 mNumLaunchingActivities.getAndAdd(num);
3148 }
3149
Mathew Inwood61e8ae62018-08-14 14:17:44 +01003150 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003151 public final void sendActivityResult(
3152 IBinder token, String id, int requestCode,
3153 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003154 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07003155 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3157 list.add(new ResultInfo(id, requestCode, resultCode, data));
Andrii Kulian9c5ea9c2017-12-07 09:31:01 -08003158 final ClientTransaction clientTransaction = ClientTransaction.obtain(mAppThread, token);
3159 clientTransaction.addCallback(ActivityResultItem.obtain(list));
Andrii Kulian446e8242017-10-26 15:17:29 -07003160 try {
3161 mAppThread.scheduleTransaction(clientTransaction);
3162 } catch (RemoteException e) {
3163 // Local scheduling
3164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003165 }
3166
Andrii Kulian914aa7d2018-03-19 21:51:53 -07003167 @Override
3168 TransactionExecutor getTransactionExecutor() {
3169 return mTransactionExecutor;
3170 }
3171
Andrii Kulian446e8242017-10-26 15:17:29 -07003172 void sendMessage(int what, Object obj) {
Jeff Brown9ef09972013-10-15 20:49:59 -07003173 sendMessage(what, obj, 0, 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003174 }
3175
Jeff Brown9ef09972013-10-15 20:49:59 -07003176 private void sendMessage(int what, Object obj, int arg1) {
3177 sendMessage(what, obj, arg1, 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 }
3179
Jeff Brown9ef09972013-10-15 20:49:59 -07003180 private void sendMessage(int what, Object obj, int arg1, int arg2) {
3181 sendMessage(what, obj, arg1, arg2, false);
3182 }
3183
3184 private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
Kweku Adams4af1b502019-05-23 16:23:48 -07003185 if (DEBUG_MESSAGES) {
3186 Slog.v(TAG,
3187 "SCHEDULE " + what + " " + mH.codeToString(what) + ": " + arg1 + " / " + obj);
3188 }
Jeff Brown9ef09972013-10-15 20:49:59 -07003189 Message msg = Message.obtain();
3190 msg.what = what;
3191 msg.obj = obj;
3192 msg.arg1 = arg1;
3193 msg.arg2 = arg2;
3194 if (async) {
3195 msg.setAsynchronous(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196 }
Jeff Brown9ef09972013-10-15 20:49:59 -07003197 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 }
3199
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07003200 private void sendMessage(int what, Object obj, int arg1, int arg2, int seq) {
3201 if (DEBUG_MESSAGES) Slog.v(
3202 TAG, "SCHEDULE " + mH.codeToString(what) + " arg1=" + arg1 + " arg2=" + arg2 +
3203 "seq= " + seq);
3204 Message msg = Message.obtain();
3205 msg.what = what;
3206 SomeArgs args = SomeArgs.obtain();
3207 args.arg1 = obj;
3208 args.argi1 = arg1;
3209 args.argi2 = arg2;
3210 args.argi3 = seq;
3211 msg.obj = args;
3212 mH.sendMessage(msg);
3213 }
3214
Dianne Hackborn21556372010-02-04 16:34:40 -08003215 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003216 String what) {
3217 ContextCleanupInfo cci = new ContextCleanupInfo();
3218 cci.context = context;
3219 cci.who = who;
3220 cci.what = what;
Jeff Brown9ef09972013-10-15 20:49:59 -07003221 sendMessage(H.CLEAN_UP_CONTEXT, cci);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 }
3223
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003224 /** Core implementation of activity launch. */
Andrii Kulian770c4032018-05-02 18:40:59 -07003225 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226 ActivityInfo aInfo = r.activityInfo;
Todd Kennedy233a0b12018-01-29 20:30:24 +00003227 if (r.packageInfo == null) {
3228 r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 Context.CONTEXT_INCLUDE_CODE);
3230 }
Bob Leee5408332009-09-04 18:31:17 -07003231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003232 ComponentName component = r.intent.getComponent();
3233 if (component == null) {
3234 component = r.intent.resolveActivity(
3235 mInitialApplication.getPackageManager());
3236 r.intent.setComponent(component);
3237 }
3238
3239 if (r.activityInfo.targetActivity != null) {
3240 component = new ComponentName(r.activityInfo.packageName,
3241 r.activityInfo.targetActivity);
3242 }
3243
Adam Lesinski4e862812016-11-21 16:02:24 -08003244 ContextImpl appContext = createBaseContextForActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003245 Activity activity = null;
3246 try {
Adam Lesinski4e862812016-11-21 16:02:24 -08003247 java.lang.ClassLoader cl = appContext.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04003248 activity = mInstrumentation.newActivity(
3249 cl, component.getClassName(), r.intent);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003250 StrictMode.incrementExpectedActivityCount(activity.getClass());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003251 r.intent.setExtrasClassLoader(cl);
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003252 r.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003253 if (r.state != null) {
3254 r.state.setClassLoader(cl);
3255 }
3256 } catch (Exception e) {
3257 if (!mInstrumentation.onException(activity, e)) {
3258 throw new RuntimeException(
3259 "Unable to instantiate activity " + component
3260 + ": " + e.toString(), e);
3261 }
3262 }
3263
3264 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00003265 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07003266
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003267 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
3268 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 TAG, r + ": app=" + app
3270 + ", appName=" + app.getPackageName()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003271 + ", pkg=" + r.packageInfo.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003272 + ", comp=" + r.intent.getComponent().toShortString()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003273 + ", dir=" + r.packageInfo.getAppDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274
3275 if (activity != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003277 Configuration config = new Configuration(mCompatConfiguration);
Andrii Kuliand0ad9382016-04-18 20:54:20 -07003278 if (r.overrideConfig != null) {
3279 config.updateFrom(r.overrideConfig);
3280 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003281 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003282 + r.activityInfo.name + " with config " + config);
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003283 Window window = null;
3284 if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
3285 window = r.mPendingRemoveWindow;
3286 r.mPendingRemoveWindow = null;
3287 r.mPendingRemoveWindowManager = null;
3288 }
Adam Lesinski4e862812016-11-21 16:02:24 -08003289 appContext.setOuterContext(activity);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003290 activity.attach(appContext, this, getInstrumentation(), r.token,
3291 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Craig Mautner233ceee2014-05-09 17:05:11 -07003292 r.embeddedID, r.lastNonConfigurationInstances, config,
Sunny Goyald40c3452019-03-20 12:46:55 -07003293 r.referrer, r.voiceInteractor, window, r.configCallback,
3294 r.assistToken);
Bob Leee5408332009-09-04 18:31:17 -07003295
Andrii Kulian770c4032018-05-02 18:40:59 -07003296 if (customIntent != null) {
3297 activity.mIntent = customIntent;
3298 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003299 r.lastNonConfigurationInstances = null;
Sudheer Shanka84a48952017-03-08 18:19:01 -08003300 checkAndBlockForNetworkAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 activity.mStartedActivity = false;
3302 int theme = r.activityInfo.getThemeResource();
3303 if (theme != 0) {
3304 activity.setTheme(theme);
3305 }
3306
3307 activity.mCalled = false;
Craig Mautnera0026042014-04-23 11:45:37 -07003308 if (r.isPersistable()) {
3309 mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
3310 } else {
3311 mInstrumentation.callActivityOnCreate(activity, r.state);
3312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 if (!activity.mCalled) {
3314 throw new SuperNotCalledException(
3315 "Activity " + r.intent.getComponent().toShortString() +
3316 " did not call through to super.onCreate()");
3317 }
3318 r.activity = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003320 r.setState(ON_CREATE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321
Garfield Tan0443b372019-01-04 15:00:13 -08003322 // updatePendingActivityConfiguration() reads from mActivities to update
3323 // ActivityClientRecord which runs in a different thread. Protect modifications to
3324 // mActivities to avoid race.
3325 synchronized (mResourcesManager) {
3326 mActivities.put(r.token, r);
3327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328
3329 } catch (SuperNotCalledException e) {
3330 throw e;
3331
3332 } catch (Exception e) {
3333 if (!mInstrumentation.onException(activity, e)) {
3334 throw new RuntimeException(
3335 "Unable to start activity " + component
3336 + ": " + e.toString(), e);
3337 }
3338 }
3339
3340 return activity;
3341 }
3342
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003343 @Override
Andrii Kulianb9faa032019-10-17 23:11:54 -07003344 public void handleStartActivity(IBinder token, PendingTransactionActions pendingActions) {
3345 final ActivityClientRecord r = mActivities.get(token);
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003346 final Activity activity = r.activity;
3347 if (r.activity == null) {
3348 // TODO(lifecycler): What do we do in this case?
3349 return;
3350 }
3351 if (!r.stopped) {
3352 throw new IllegalStateException("Can't start activity that is not stopped.");
3353 }
Andrii Kulian0f3356c2019-03-18 21:34:40 +00003354 if (r.activity.mFinished) {
3355 // TODO(lifecycler): How can this happen?
3356 return;
3357 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003358
Andrii Kulianb9faa032019-10-17 23:11:54 -07003359 unscheduleGcIdler();
3360
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003361 // Start
Andrii Kuliand25680c2018-02-21 15:16:58 -08003362 activity.performStart("handleStartActivity");
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003363 r.setState(ON_START);
3364
3365 if (pendingActions == null) {
3366 // No more work to do.
3367 return;
3368 }
3369
3370 // Restore instance state
3371 if (pendingActions.shouldRestoreInstanceState()) {
3372 if (r.isPersistable()) {
3373 if (r.state != null || r.persistentState != null) {
3374 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
3375 r.persistentState);
3376 }
3377 } else if (r.state != null) {
3378 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
3379 }
3380 }
3381
3382 // Call postOnCreate()
3383 if (pendingActions.shouldCallOnPostCreate()) {
3384 activity.mCalled = false;
3385 if (r.isPersistable()) {
3386 mInstrumentation.callActivityOnPostCreate(activity, r.state,
3387 r.persistentState);
3388 } else {
3389 mInstrumentation.callActivityOnPostCreate(activity, r.state);
3390 }
3391 if (!activity.mCalled) {
3392 throw new SuperNotCalledException(
3393 "Activity " + r.intent.getComponent().toShortString()
3394 + " did not call through to super.onPostCreate()");
3395 }
3396 }
Andrii Kulianb9faa032019-10-17 23:11:54 -07003397
3398 updateVisibility(r, true /* show */);
3399 mSomeActivitiesChanged = true;
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003400 }
3401
Sudheer Shanka84a48952017-03-08 18:19:01 -08003402 /**
3403 * Checks if {@link #mNetworkBlockSeq} is {@link #INVALID_PROC_STATE_SEQ} and if so, returns
3404 * immediately. Otherwise, makes a blocking call to ActivityManagerService to wait for the
3405 * network rules to get updated.
3406 */
3407 private void checkAndBlockForNetworkAccess() {
3408 synchronized (mNetworkPolicyLock) {
3409 if (mNetworkBlockSeq != INVALID_PROC_STATE_SEQ) {
3410 try {
3411 ActivityManager.getService().waitForNetworkStateUpdate(mNetworkBlockSeq);
3412 mNetworkBlockSeq = INVALID_PROC_STATE_SEQ;
3413 } catch (RemoteException ignored) {}
3414 }
3415 }
3416 }
3417
Adam Lesinski4e862812016-11-21 16:02:24 -08003418 private ContextImpl createBaseContextForActivity(ActivityClientRecord r) {
3419 final int displayId;
Craig Mautnere0a38842013-12-16 16:14:02 -08003420 try {
Louis Chang677921f2019-12-06 16:44:24 +08003421 displayId = ActivityTaskManager.getService().getDisplayId(r.token);
Craig Mautnere0a38842013-12-16 16:14:02 -08003422 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003423 throw e.rethrowFromSystemServer();
Craig Mautnere0a38842013-12-16 16:14:02 -08003424 }
Jeff Brownefd43bd2012-09-21 17:02:35 -07003425
Wale Ogunwale7c726682015-02-06 17:34:28 -08003426 ContextImpl appContext = ContextImpl.createActivityContext(
Todd Kennedy233a0b12018-01-29 20:30:24 +00003427 this, r.packageInfo, r.activityInfo, r.token, displayId, r.overrideConfig);
Wale Ogunwale7c726682015-02-06 17:34:28 -08003428
3429 final DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance();
Jeff Brownefd43bd2012-09-21 17:02:35 -07003430 // For debugging purposes, if the activity's package name contains the value of
3431 // the "debug.use-second-display" system property as a substring, then show
3432 // its content on a secondary display if there is one.
Jeff Brownefd43bd2012-09-21 17:02:35 -07003433 String pkgName = SystemProperties.get("debug.second-display.pkg");
3434 if (pkgName != null && !pkgName.isEmpty()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003435 && r.packageInfo.mPackageName.contains(pkgName)) {
Wale Ogunwale7c726682015-02-06 17:34:28 -08003436 for (int id : dm.getDisplayIds()) {
3437 if (id != Display.DEFAULT_DISPLAY) {
Wale Ogunwale26698512015-06-05 16:55:33 -07003438 Display display =
Bryce Lee609bf652017-02-09 16:50:13 -08003439 dm.getCompatibleDisplay(id, appContext.getResources());
Adam Lesinski4e862812016-11-21 16:02:24 -08003440 appContext = (ContextImpl) appContext.createDisplayContext(display);
Jeff Brownefd43bd2012-09-21 17:02:35 -07003441 break;
3442 }
3443 }
3444 }
Adam Lesinski4e862812016-11-21 16:02:24 -08003445 return appContext;
Jeff Brownefd43bd2012-09-21 17:02:35 -07003446 }
3447
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003448 /**
3449 * Extended implementation of activity launch. Used when server requests a launch or relaunch.
3450 */
Andrii Kulian446e8242017-10-26 15:17:29 -07003451 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003452 public Activity handleLaunchActivity(ActivityClientRecord r,
Andrii Kulian770c4032018-05-02 18:40:59 -07003453 PendingTransactionActions pendingActions, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003454 // If we are getting ready to gc after going to the background, well
3455 // we are back active so skip it.
3456 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003457 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458
Jeff Hao1b012d32014-08-20 10:35:34 -07003459 if (r.profilerInfo != null) {
3460 mProfiler.setProfiler(r.profilerInfo);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003461 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003462 }
3463
Dianne Hackborn58f42a52011-10-10 13:46:34 -07003464 // Make sure we are running with the most recent config.
3465 handleConfigurationChanged(null, null);
3466
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003467 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 TAG, "Handling launch of " + r);
Adam Powellcfbe9be2013-11-06 14:58:58 -08003469
Chet Haase0d1c27a2014-11-03 18:35:16 +00003470 // Initialize before creating the activity
Stan Iliev898123b2019-02-14 14:57:44 -05003471 if (!ThreadedRenderer.sRendererDisabled
3472 && (r.activityInfo.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
3473 HardwareRenderer.preload();
Jesse Hallc37984f2017-05-23 16:55:08 -07003474 }
Chet Haase0d1c27a2014-11-03 18:35:16 +00003475 WindowManagerGlobal.initialize();
3476
Yiwei Zhange54faf52019-05-08 18:43:11 -07003477 // Hint the GraphicsEnvironment that an activity is launching on the process.
3478 GraphicsEnvironment.hintActivityLaunch();
3479
Andrii Kulian770c4032018-05-02 18:40:59 -07003480 final Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481
3482 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003483 r.createdConfig = new Configuration(mConfiguration);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003484 reportSizeConfigurations(r);
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003485 if (!r.activity.mFinished && pendingActions != null) {
3486 pendingActions.setOldState(r.state);
3487 pendingActions.setRestoreInstanceState(true);
3488 pendingActions.setCallOnPostCreate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003489 }
3490 } else {
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07003491 // 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 -08003492 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003493 ActivityTaskManager.getService()
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003494 .finishActivity(r.token, Activity.RESULT_CANCELED, null,
3495 Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003496 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003497 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003498 }
3499 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003500
3501 return a;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003502 }
3503
Filip Gruszczynski23493322015-07-29 17:02:59 -07003504 private void reportSizeConfigurations(ActivityClientRecord r) {
Riddle Hsu66b74a82018-07-26 00:20:12 +08003505 if (mActivitiesToBeDestroyed.containsKey(r.token)) {
3506 // Size configurations of a destroyed activity is meaningless.
3507 return;
3508 }
Filip Gruszczynski23493322015-07-29 17:02:59 -07003509 Configuration[] configurations = r.activity.getResources().getSizeConfigurations();
3510 if (configurations == null) {
3511 return;
3512 }
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003513 SparseIntArray horizontal = new SparseIntArray();
3514 SparseIntArray vertical = new SparseIntArray();
3515 SparseIntArray smallest = new SparseIntArray();
Filip Gruszczynski23493322015-07-29 17:02:59 -07003516 for (int i = configurations.length - 1; i >= 0; i--) {
3517 Configuration config = configurations[i];
3518 if (config.screenHeightDp != Configuration.SCREEN_HEIGHT_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003519 vertical.put(config.screenHeightDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003520 }
3521 if (config.screenWidthDp != Configuration.SCREEN_WIDTH_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003522 horizontal.put(config.screenWidthDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003523 }
3524 if (config.smallestScreenWidthDp != Configuration.SMALLEST_SCREEN_WIDTH_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003525 smallest.put(config.smallestScreenWidthDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003526 }
3527 }
Filip Gruszczynski23493322015-07-29 17:02:59 -07003528 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003529 ActivityTaskManager.getService().reportSizeConfigurations(r.token,
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003530 horizontal.copyKeys(), vertical.copyKeys(), smallest.copyKeys());
Filip Gruszczynski23493322015-07-29 17:02:59 -07003531 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003532 throw ex.rethrowFromSystemServer();
Filip Gruszczynski23493322015-07-29 17:02:59 -07003533 }
Filip Gruszczynski23493322015-07-29 17:02:59 -07003534 }
3535
Dianne Hackborn85d558c2014-11-04 10:31:54 -08003536 private void deliverNewIntents(ActivityClientRecord r, List<ReferrerIntent> intents) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003537 final int N = intents.size();
3538 for (int i=0; i<N; i++) {
Dianne Hackborna01a0fa2014-12-02 10:33:14 -08003539 ReferrerIntent intent = intents.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003540 intent.setExtrasClassLoader(r.activity.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003541 intent.prepareToEnterProcess();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003542 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003543 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
3544 }
3545 }
3546
Louis Chang92d16522019-02-27 12:56:18 +08003547 @Override
3548 public void handleNewIntent(IBinder token, List<ReferrerIntent> intents) {
Wale Ogunwale826c7062016-09-13 08:25:54 -07003549 final ActivityClientRecord r = mActivities.get(token);
3550 if (r == null) {
3551 return;
3552 }
3553
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07003554 checkAndBlockForNetworkAccess();
Wale Ogunwale826c7062016-09-13 08:25:54 -07003555 deliverNewIntents(r, intents);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 }
3557
Adam Skorydfc7fd72013-08-05 19:23:41 -07003558 public void handleRequestAssistContextExtras(RequestAssistContextExtras cmd) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003559 // Filling for autofill has a few differences:
Felipe Leme1ca634a2016-11-28 17:21:21 -08003560 // - it does not need an AssistContent
3561 // - it does not call onProvideAssistData()
3562 // - it needs an IAutoFillCallback
Felipe Leme640f30a2017-03-06 15:44:06 -08003563 boolean forAutofill = cmd.requestType == ActivityManager.ASSIST_CONTEXT_AUTOFILL;
Felipe Leme1ca634a2016-11-28 17:21:21 -08003564
Felipe Leme85d1c2d2017-04-21 08:56:04 -07003565 // TODO: decide if lastSessionId logic applies to autofill sessions
Amith Yamasani4f128e42016-05-10 11:44:12 -07003566 if (mLastSessionId != cmd.sessionId) {
3567 // Clear the existing structures
3568 mLastSessionId = cmd.sessionId;
3569 for (int i = mLastAssistStructures.size() - 1; i >= 0; i--) {
3570 AssistStructure structure = mLastAssistStructures.get(i).get();
3571 if (structure != null) {
3572 structure.clearSendChannel();
3573 }
3574 mLastAssistStructures.remove(i);
Dianne Hackborn782d4982015-07-08 17:36:37 -07003575 }
3576 }
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003577
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003578 Bundle data = new Bundle();
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003579 AssistStructure structure = null;
Felipe Leme640f30a2017-03-06 15:44:06 -08003580 AssistContent content = forAutofill ? null : new AssistContent();
Amith Yamasani858f98d2017-02-22 12:59:53 -08003581 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003582 ActivityClientRecord r = mActivities.get(cmd.activityToken);
Dianne Hackborna3acdb32015-06-08 17:07:40 -07003583 Uri referrer = null;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003584 if (r != null) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003585 if (!forAutofill) {
Felipe Leme1ca634a2016-11-28 17:21:21 -08003586 r.activity.getApplication().dispatchOnProvideAssistData(r.activity, data);
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003587 r.activity.onProvideAssistData(data);
Felipe Leme6d553872016-12-08 17:13:25 -08003588 referrer = r.activity.onProvideReferrer();
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003589 }
Felipe Leme640f30a2017-03-06 15:44:06 -08003590 if (cmd.requestType == ActivityManager.ASSIST_CONTEXT_FULL || forAutofill) {
Svet Ganovfd31f852017-04-26 15:54:27 -07003591 structure = new AssistStructure(r.activity, forAutofill, cmd.flags);
Adam Skory4aaed142015-04-22 11:29:31 -06003592 Intent activityIntent = r.activity.getIntent();
Felipe Leme6d553872016-12-08 17:13:25 -08003593 boolean notSecure = r.window == null ||
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003594 (r.window.getAttributes().flags
Felipe Leme6d553872016-12-08 17:13:25 -08003595 & WindowManager.LayoutParams.FLAG_SECURE) == 0;
3596 if (activityIntent != null && notSecure) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003597 if (!forAutofill) {
Felipe Leme1ca634a2016-11-28 17:21:21 -08003598 Intent intent = new Intent(activityIntent);
3599 intent.setFlags(intent.getFlags() & ~(Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3600 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION));
3601 intent.removeUnsafeExtras();
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003602 content.setDefaultIntent(intent);
3603 }
Adam Skory4aaed142015-04-22 11:29:31 -06003604 } else {
Felipe Leme640f30a2017-03-06 15:44:06 -08003605 if (!forAutofill) {
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003606 content.setDefaultIntent(new Intent());
3607 }
Adam Skory4aaed142015-04-22 11:29:31 -06003608 }
Felipe Leme640f30a2017-03-06 15:44:06 -08003609 if (!forAutofill) {
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003610 r.activity.onProvideAssistContent(content);
3611 }
Dianne Hackborna83ce1d2015-03-11 15:16:13 -07003612 }
Sunny Goyald40c3452019-03-20 12:46:55 -07003613
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003614 }
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003615 if (structure == null) {
3616 structure = new AssistStructure();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003617 }
Felipe Leme0200d9e2017-01-24 15:10:26 -08003618
Felipe Leme85d1c2d2017-04-21 08:56:04 -07003619 // TODO: decide if lastSessionId logic applies to autofill sessions
Amith Yamasani858f98d2017-02-22 12:59:53 -08003620
3621 structure.setAcquisitionStartTime(startTime);
3622 structure.setAcquisitionEndTime(SystemClock.uptimeMillis());
3623
Amith Yamasani4f128e42016-05-10 11:44:12 -07003624 mLastAssistStructures.add(new WeakReference<>(structure));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003625 IActivityTaskManager mgr = ActivityTaskManager.getService();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003626 try {
Dianne Hackborna3acdb32015-06-08 17:07:40 -07003627 mgr.reportAssistContextExtras(cmd.requestToken, data, structure, content, referrer);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003628 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003629 throw e.rethrowFromSystemServer();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003630 }
3631 }
Craig Mautner5eda9b32013-07-02 11:58:16 -07003632
Sunny Goyald40c3452019-03-20 12:46:55 -07003633 /** Fetches the user actions for the corresponding activity */
3634 private void handleRequestDirectActions(@NonNull IBinder activityToken,
Svet Ganov3b6be082019-04-28 10:21:01 -07003635 @NonNull IVoiceInteractor interactor, @NonNull CancellationSignal cancellationSignal,
3636 @NonNull RemoteCallback callback) {
Sunny Goyald40c3452019-03-20 12:46:55 -07003637 final ActivityClientRecord r = mActivities.get(activityToken);
Svet Ganov3b6be082019-04-28 10:21:01 -07003638 if (r == null) {
Felipe Lemeada51842019-05-14 15:19:52 -07003639 Log.w(TAG, "requestDirectActions(): no activity for " + activityToken);
Svet Ganov3b6be082019-04-28 10:21:01 -07003640 callback.sendResult(null);
3641 return;
3642 }
3643 final int lifecycleState = r.getLifecycleState();
3644 if (lifecycleState < ON_START || lifecycleState >= ON_STOP) {
Felipe Lemeada51842019-05-14 15:19:52 -07003645 Log.w(TAG, "requestDirectActions(" + r + "): wrong lifecycle: " + lifecycleState);
Svet Ganov3b6be082019-04-28 10:21:01 -07003646 callback.sendResult(null);
3647 return;
3648 }
3649 if (r.activity.mVoiceInteractor == null
3650 || r.activity.mVoiceInteractor.mInteractor.asBinder()
3651 != interactor.asBinder()) {
3652 if (r.activity.mVoiceInteractor != null) {
3653 r.activity.mVoiceInteractor.destroy();
Sunny Goyald40c3452019-03-20 12:46:55 -07003654 }
Svet Ganov3b6be082019-04-28 10:21:01 -07003655 r.activity.mVoiceInteractor = new VoiceInteractor(interactor, r.activity,
3656 r.activity, Looper.myLooper());
3657 }
3658 r.activity.onGetDirectActions(cancellationSignal, (actions) -> {
Daulet Zhanguzin0af97d62019-12-30 15:41:28 +00003659 Objects.requireNonNull(actions);
Sunny Goyald40c3452019-03-20 12:46:55 -07003660 Preconditions.checkCollectionElementsNotNull(actions, "actions");
Svet Ganov3b6be082019-04-28 10:21:01 -07003661 if (!actions.isEmpty()) {
Sunny Goyald40c3452019-03-20 12:46:55 -07003662 final int actionCount = actions.size();
3663 for (int i = 0; i < actionCount; i++) {
3664 final DirectAction action = actions.get(i);
3665 action.setSource(r.activity.getTaskId(), r.activity.getAssistToken());
3666 }
3667 final Bundle result = new Bundle();
3668 result.putParcelable(DirectAction.KEY_ACTIONS_LIST,
3669 new ParceledListSlice<>(actions));
3670 callback.sendResult(result);
Svet Ganov3b6be082019-04-28 10:21:01 -07003671 } else {
3672 callback.sendResult(null);
Sunny Goyald40c3452019-03-20 12:46:55 -07003673 }
Svet Ganov3b6be082019-04-28 10:21:01 -07003674 });
Sunny Goyald40c3452019-03-20 12:46:55 -07003675 }
3676
3677 /** Performs an actions in the corresponding activity */
3678 private void handlePerformDirectAction(@NonNull IBinder activityToken,
3679 @NonNull String actionId, @Nullable Bundle arguments,
3680 @NonNull CancellationSignal cancellationSignal,
3681 @NonNull RemoteCallback resultCallback) {
3682 final ActivityClientRecord r = mActivities.get(activityToken);
3683 if (r != null) {
3684 final int lifecycleState = r.getLifecycleState();
3685 if (lifecycleState < ON_START || lifecycleState >= ON_STOP) {
3686 resultCallback.sendResult(null);
3687 return;
3688 }
3689 final Bundle nonNullArguments = (arguments != null) ? arguments : Bundle.EMPTY;
Sunny Goyald40c3452019-03-20 12:46:55 -07003690 r.activity.onPerformDirectAction(actionId, nonNullArguments, cancellationSignal,
Svet Ganov3b6be082019-04-28 10:21:01 -07003691 resultCallback::sendResult);
3692 } else {
3693 resultCallback.sendResult(null);
Sunny Goyald40c3452019-03-20 12:46:55 -07003694 }
Sunny Goyald40c3452019-03-20 12:46:55 -07003695 }
3696
Craig Mautner5eda9b32013-07-02 11:58:16 -07003697 public void handleTranslucentConversionComplete(IBinder token, boolean drawComplete) {
3698 ActivityClientRecord r = mActivities.get(token);
3699 if (r != null) {
3700 r.activity.onTranslucentConversionComplete(drawComplete);
3701 }
3702 }
3703
Craig Mautnereb8abf72014-07-02 15:04:09 -07003704 public void onNewActivityOptions(IBinder token, ActivityOptions options) {
3705 ActivityClientRecord r = mActivities.get(token);
3706 if (r != null) {
3707 r.activity.onNewActivityOptions(options);
3708 }
3709 }
3710
Jeff Sharkeydd97f422013-10-08 17:01:30 -07003711 public void handleInstallProvider(ProviderInfo info) {
Jeff Sharkeybb2e2ca2014-10-23 11:42:31 -07003712 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3713 try {
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -06003714 installContentProviders(mInitialApplication, Arrays.asList(info));
Jeff Sharkeybb2e2ca2014-10-23 11:42:31 -07003715 } finally {
3716 StrictMode.setThreadPolicy(oldPolicy);
3717 }
Jeff Sharkeydd97f422013-10-08 17:01:30 -07003718 }
3719
Craig Mautner8746a472014-07-24 15:12:54 -07003720 private void handleEnterAnimationComplete(IBinder token) {
3721 ActivityClientRecord r = mActivities.get(token);
3722 if (r != null) {
Filip Gruszczynski6eafa902014-11-14 14:24:37 -08003723 r.activity.dispatchEnterAnimationComplete();
Craig Mautner8746a472014-07-24 15:12:54 -07003724 }
3725 }
3726
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04003727 private void handleStartBinderTracking() {
3728 Binder.enableTracing();
3729 }
3730
3731 private void handleStopBinderTrackingAndDump(ParcelFileDescriptor fd) {
3732 try {
3733 Binder.disableTracing();
3734 Binder.getTransactionTracker().writeTracesToFile(fd);
3735 } finally {
3736 IoUtils.closeQuietly(fd);
3737 Binder.getTransactionTracker().clearTraces();
3738 }
3739 }
3740
Andrii Kulian446e8242017-10-26 15:17:29 -07003741 @Override
3742 public void handleMultiWindowModeChanged(IBinder token, boolean isInMultiWindowMode,
Winson Chung5af42fc2017-03-24 17:11:33 -07003743 Configuration overrideConfig) {
Wale Ogunwale5f986092015-12-04 15:35:38 -08003744 final ActivityClientRecord r = mActivities.get(token);
3745 if (r != null) {
Winson Chung5af42fc2017-03-24 17:11:33 -07003746 final Configuration newConfig = new Configuration(mConfiguration);
3747 if (overrideConfig != null) {
3748 newConfig.updateFrom(overrideConfig);
3749 }
3750 r.activity.dispatchMultiWindowModeChanged(isInMultiWindowMode, newConfig);
Wale Ogunwale5f986092015-12-04 15:35:38 -08003751 }
3752 }
3753
Andrii Kulian446e8242017-10-26 15:17:29 -07003754 @Override
3755 public void handlePictureInPictureModeChanged(IBinder token, boolean isInPipMode,
Winson Chung5af42fc2017-03-24 17:11:33 -07003756 Configuration overrideConfig) {
Wale Ogunwale5f986092015-12-04 15:35:38 -08003757 final ActivityClientRecord r = mActivities.get(token);
3758 if (r != null) {
Winson Chung5af42fc2017-03-24 17:11:33 -07003759 final Configuration newConfig = new Configuration(mConfiguration);
3760 if (overrideConfig != null) {
3761 newConfig.updateFrom(overrideConfig);
3762 }
3763 r.activity.dispatchPictureInPictureModeChanged(isInPipMode, newConfig);
Wale Ogunwale5f986092015-12-04 15:35:38 -08003764 }
3765 }
3766
jorgegil@google.com06bc3232019-10-31 14:51:22 -07003767 @Override
3768 public void handlePictureInPictureRequested(IBinder token) {
3769 final ActivityClientRecord r = mActivities.get(token);
3770 if (r == null) {
3771 Log.w(TAG, "Activity to request PIP to no longer exists");
3772 return;
3773 }
3774
3775 r.activity.onPictureInPictureRequested();
3776 }
3777
3778 /**
3779 * Cycle activity through onPause and onUserLeaveHint so that PIP is entered if supported, then
3780 * return to its previous state. This allows activities that rely on onUserLeaveHint instead of
3781 * onPictureInPictureRequested to enter picture-in-picture.
3782 */
3783 public void schedulePauseAndReturnToCurrentState(IBinder token) {
3784 final ActivityClientRecord r = mActivities.get(token);
3785 if (r == null) {
3786 Log.w(TAG, "Activity to request pause with user leaving hint to no longer exists");
3787 return;
3788 }
3789
3790 if (r.mIsUserLeaving) {
3791 // The activity is about to perform user leaving, so there's no need to cycle ourselves.
3792 return;
3793 }
3794
3795 final int prevState = r.getLifecycleState();
3796 if (prevState != ON_RESUME && prevState != ON_PAUSE) {
3797 return;
3798 }
3799
3800 switch (prevState) {
3801 case ON_RESUME:
3802 // Schedule a PAUSE then return to RESUME.
3803 schedulePauseWithUserLeavingHint(r);
3804 scheduleResume(r);
3805 break;
3806 case ON_PAUSE:
3807 // Schedule a RESUME then return to PAUSE.
3808 scheduleResume(r);
3809 schedulePauseWithUserLeavingHint(r);
3810 break;
3811 }
3812 }
3813
3814 private void schedulePauseWithUserLeavingHint(ActivityClientRecord r) {
3815 final ClientTransaction transaction = ClientTransaction.obtain(this.mAppThread, r.token);
3816 transaction.setLifecycleStateRequest(PauseActivityItem.obtain(r.activity.isFinishing(),
3817 /* userLeaving */ true, r.activity.mConfigChangeFlags, /* dontReport */ false));
3818 executeTransaction(transaction);
3819 }
3820
3821 private void scheduleResume(ActivityClientRecord r) {
3822 final ClientTransaction transaction = ClientTransaction.obtain(this.mAppThread, r.token);
3823 transaction.setLifecycleStateRequest(ResumeActivityItem.obtain(/* isForward */ false));
3824 executeTransaction(transaction);
3825 }
3826
Amith Yamasani0af6fa72016-01-17 15:36:19 -08003827 private void handleLocalVoiceInteractionStarted(IBinder token, IVoiceInteractor interactor) {
3828 final ActivityClientRecord r = mActivities.get(token);
3829 if (r != null) {
3830 r.voiceInteractor = interactor;
3831 r.activity.setVoiceInteractor(interactor);
3832 if (interactor == null) {
3833 r.activity.onLocalVoiceInteractionStopped();
3834 } else {
3835 r.activity.onLocalVoiceInteractionStarted();
3836 }
3837 }
3838 }
3839
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003840 private static boolean attemptAttachAgent(String agent, ClassLoader classLoader) {
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003841 try {
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003842 VMDebug.attachAgent(agent, classLoader);
3843 return true;
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003844 } catch (IOException e) {
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003845 Slog.e(TAG, "Attaching agent with " + classLoader + " failed: " + agent);
3846 return false;
3847 }
3848 }
3849
3850 static void handleAttachAgent(String agent, LoadedApk loadedApk) {
3851 ClassLoader classLoader = loadedApk != null ? loadedApk.getClassLoader() : null;
3852 if (attemptAttachAgent(agent, classLoader)) {
3853 return;
3854 }
3855 if (classLoader != null) {
3856 attemptAttachAgent(agent, null);
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003857 }
3858 }
3859
Alex Light2d0691c2019-10-03 14:36:57 -07003860 static void handleAttachStartupAgents(String dataDir) {
3861 try {
3862 Path code_cache = ContextImpl.getCodeCacheDirBeforeBind(new File(dataDir)).toPath();
3863 if (!Files.exists(code_cache)) {
3864 return;
3865 }
3866 Path startup_path = code_cache.resolve("startup_agents");
3867 if (Files.exists(startup_path)) {
3868 for (Path p : Files.newDirectoryStream(startup_path)) {
3869 handleAttachAgent(
3870 p.toAbsolutePath().toString()
3871 + "="
3872 + dataDir,
3873 null);
3874 }
3875 }
3876 } catch (Exception e) {
3877 // Ignored.
3878 }
3879 }
3880
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003881 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
3882
3883 /**
3884 * Return the Intent that's currently being handled by a
3885 * BroadcastReceiver on this thread, or null if none.
3886 * @hide
3887 */
3888 public static Intent getIntentBeingBroadcast() {
3889 return sCurrentBroadcastIntent.get();
3890 }
3891
Mathew Inwood31755f92018-12-20 13:53:36 +00003892 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Romain Guy65b345f2011-07-27 18:51:50 -07003893 private void handleReceiver(ReceiverData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894 // If we are getting ready to gc after going to the background, well
3895 // we are back active so skip it.
3896 unscheduleGcIdler();
3897
3898 String component = data.intent.getComponent().getClassName();
3899
Todd Kennedy233a0b12018-01-29 20:30:24 +00003900 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003901 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003903 IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904
Adam Lesinski4e862812016-11-21 16:02:24 -08003905 Application app;
Romain Guy65b345f2011-07-27 18:51:50 -07003906 BroadcastReceiver receiver;
Adam Lesinski4e862812016-11-21 16:02:24 -08003907 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00003909 app = packageInfo.makeApplication(false, mInstrumentation);
Adam Lesinski4e862812016-11-21 16:02:24 -08003910 context = (ContextImpl) app.getBaseContext();
3911 if (data.info.splitName != null) {
3912 context = (ContextImpl) context.createContextForSplit(data.info.splitName);
3913 }
3914 java.lang.ClassLoader cl = context.getClassLoader();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003915 data.intent.setExtrasClassLoader(cl);
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003916 data.intent.prepareToEnterProcess();
Dianne Hackborne829fef2010-10-26 17:44:01 -07003917 data.setExtrasClassLoader(cl);
Todd Kennedy233a0b12018-01-29 20:30:24 +00003918 receiver = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05003919 .instantiateReceiver(cl, data.info.name, data.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07003921 if (DEBUG_BROADCAST) Slog.i(TAG,
3922 "Finishing failed broadcast to " + data.intent.getComponent());
3923 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 throw new RuntimeException(
3925 "Unable to instantiate receiver " + component
3926 + ": " + e.toString(), e);
3927 }
3928
3929 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003930 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931 TAG, "Performing receive of " + data.intent
3932 + ": app=" + app
3933 + ", appName=" + app.getPackageName()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003934 + ", pkg=" + packageInfo.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003935 + ", comp=" + data.intent.getComponent().toShortString()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003936 + ", dir=" + packageInfo.getAppDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003938 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07003939 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 receiver.onReceive(context.getReceiverRestrictedContext(),
3941 data.intent);
3942 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07003943 if (DEBUG_BROADCAST) Slog.i(TAG,
3944 "Finishing failed broadcast to " + data.intent.getComponent());
3945 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 if (!mInstrumentation.onException(receiver, e)) {
3947 throw new RuntimeException(
3948 "Unable to start receiver " + component
3949 + ": " + e.toString(), e);
3950 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003951 } finally {
3952 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003953 }
3954
Dianne Hackborne829fef2010-10-26 17:44:01 -07003955 if (receiver.getPendingResult() != null) {
3956 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 }
3958 }
3959
Christopher Tate181fafa2009-05-14 11:12:14 -07003960 // Instantiate a BackupAgent and tell it that it's alive
Romain Guy65b345f2011-07-27 18:51:50 -07003961 private void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003962 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07003963
Christopher Tate346acb12012-10-15 19:20:25 -07003964 // Sanity check the requested target package's uid against ours
3965 try {
3966 PackageInfo requestedPackage = getPackageManager().getPackageInfo(
3967 data.appInfo.packageName, 0, UserHandle.myUserId());
3968 if (requestedPackage.applicationInfo.uid != Process.myUid()) {
3969 Slog.w(TAG, "Asked to instantiate non-matching package "
3970 + data.appInfo.packageName);
3971 return;
3972 }
3973 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003974 throw e.rethrowFromSystemServer();
Christopher Tate346acb12012-10-15 19:20:25 -07003975 }
3976
Christopher Tate181fafa2009-05-14 11:12:14 -07003977 // no longer idle; we have backup work to do
3978 unscheduleGcIdler();
3979
3980 // instantiate the BackupAgent class named in the manifest
Todd Kennedy233a0b12018-01-29 20:30:24 +00003981 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
3982 String packageName = packageInfo.mPackageName;
Christopher Tate346acb12012-10-15 19:20:25 -07003983 if (packageName == null) {
3984 Slog.d(TAG, "Asked to create backup agent for nonexistent package");
3985 return;
3986 }
3987
Christopher Tate181fafa2009-05-14 11:12:14 -07003988 String classname = data.appInfo.backupAgentName;
Christopher Tate79ec80d2011-06-24 14:58:49 -07003989 // full backup operation but no app-supplied agent? use the default implementation
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003990 if (classname == null && (data.backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL
3991 || data.backupMode == ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL)) {
Christopher Tate4a627c72011-04-01 14:43:32 -07003992 classname = "android.app.backup.FullBackupAgent";
Christopher Tate181fafa2009-05-14 11:12:14 -07003993 }
Christopher Tate4a627c72011-04-01 14:43:32 -07003994
Christopher Tate181fafa2009-05-14 11:12:14 -07003995 try {
Christopher Tated1475e02009-07-09 15:36:17 -07003996 IBinder binder = null;
Annie Mengd5827872019-01-30 20:28:57 +00003997 ArrayMap<String, BackupAgent> backupAgents = getBackupAgentsForUser(data.userId);
3998 BackupAgent agent = backupAgents.get(packageName);
Christopher Tate2e40d112014-07-15 12:37:38 -07003999 if (agent != null) {
4000 // reusing the existing instance
4001 if (DEBUG_BACKUP) {
4002 Slog.v(TAG, "Reusing existing agent instance");
Christopher Tated1475e02009-07-09 15:36:17 -07004003 }
Christopher Tate2e40d112014-07-15 12:37:38 -07004004 binder = agent.onBind();
4005 } else {
4006 try {
4007 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing agent class " + classname);
4008
Todd Kennedy233a0b12018-01-29 20:30:24 +00004009 java.lang.ClassLoader cl = packageInfo.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04004010 agent = (BackupAgent) cl.loadClass(classname).newInstance();
Christopher Tate2e40d112014-07-15 12:37:38 -07004011
4012 // set up the agent's context
Todd Kennedy233a0b12018-01-29 20:30:24 +00004013 ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
Christopher Tate2e40d112014-07-15 12:37:38 -07004014 context.setOuterContext(agent);
4015 agent.attach(context);
4016
Ruslan Tkhakokhov063180f2019-01-28 20:29:46 +00004017 agent.onCreate(UserHandle.of(data.userId));
Christopher Tate2e40d112014-07-15 12:37:38 -07004018 binder = agent.onBind();
Annie Mengd5827872019-01-30 20:28:57 +00004019 backupAgents.put(packageName, agent);
Christopher Tate2e40d112014-07-15 12:37:38 -07004020 } catch (Exception e) {
4021 // If this is during restore, fail silently; otherwise go
4022 // ahead and let the user see the crash.
4023 Slog.e(TAG, "Agent threw during creation: " + e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07004024 if (data.backupMode != ApplicationThreadConstants.BACKUP_MODE_RESTORE
4025 && data.backupMode !=
4026 ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL) {
Christopher Tate2e40d112014-07-15 12:37:38 -07004027 throw e;
4028 }
4029 // falling through with 'binder' still null
4030 }
Christopher Tated1475e02009-07-09 15:36:17 -07004031 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004032
4033 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07004034 try {
Annie Mengd5827872019-01-30 20:28:57 +00004035 ActivityManager.getService().backupAgentCreated(packageName, binder, data.userId);
Christopher Tate181fafa2009-05-14 11:12:14 -07004036 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004037 throw e.rethrowFromSystemServer();
Christopher Tate181fafa2009-05-14 11:12:14 -07004038 }
Christopher Tate181fafa2009-05-14 11:12:14 -07004039 } catch (Exception e) {
4040 throw new RuntimeException("Unable to create BackupAgent "
Christopher Tate4a627c72011-04-01 14:43:32 -07004041 + classname + ": " + e.toString(), e);
Christopher Tate181fafa2009-05-14 11:12:14 -07004042 }
4043 }
4044
4045 // Tear down a BackupAgent
Romain Guy65b345f2011-07-27 18:51:50 -07004046 private void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004047 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07004048
Todd Kennedy233a0b12018-01-29 20:30:24 +00004049 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
4050 String packageName = packageInfo.mPackageName;
Annie Mengd5827872019-01-30 20:28:57 +00004051 ArrayMap<String, BackupAgent> backupAgents = getBackupAgentsForUser(data.userId);
4052 BackupAgent agent = backupAgents.get(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004053 if (agent != null) {
4054 try {
4055 agent.onDestroy();
4056 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004057 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07004058 e.printStackTrace();
4059 }
Annie Mengd5827872019-01-30 20:28:57 +00004060 backupAgents.remove(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004061 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004062 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07004063 }
4064 }
4065
Annie Mengd5827872019-01-30 20:28:57 +00004066 private ArrayMap<String, BackupAgent> getBackupAgentsForUser(int userId) {
4067 ArrayMap<String, BackupAgent> backupAgents = mBackupAgentsByUser.get(userId);
4068 if (backupAgents == null) {
4069 backupAgents = new ArrayMap<>();
4070 mBackupAgentsByUser.put(userId, backupAgents);
4071 }
4072 return backupAgents;
4073 }
4074
Mathew Inwood61e8ae62018-08-14 14:17:44 +01004075 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07004076 private void handleCreateService(CreateServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004077 // If we are getting ready to gc after going to the background, well
4078 // we are back active so skip it.
4079 unscheduleGcIdler();
4080
Todd Kennedy233a0b12018-01-29 20:30:24 +00004081 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004082 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004083 Service service = null;
4084 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004085 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086
Todd Kennedy233a0b12018-01-29 20:30:24 +00004087 ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
Todd Kennedy233a0b12018-01-29 20:30:24 +00004088 Application app = packageInfo.makeApplication(false, mInstrumentation);
Dave Mankoff66d22c82019-09-11 14:14:45 -04004089 java.lang.ClassLoader cl = packageInfo.getClassLoader();
4090 service = packageInfo.getAppFactory()
4091 .instantiateService(cl, data.info.name, data.intent);
4092 context.setOuterContext(service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004093 service.attach(context, this, data.info.name, data.token, app,
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004094 ActivityManager.getService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 service.onCreate();
4096 mServices.put(data.token, service);
4097 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004098 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08004099 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004100 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004101 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 }
4103 } catch (Exception e) {
4104 if (!mInstrumentation.onException(service, e)) {
4105 throw new RuntimeException(
4106 "Unable to create service " + data.info.name
4107 + ": " + e.toString(), e);
4108 }
4109 }
4110 }
4111
Romain Guy65b345f2011-07-27 18:51:50 -07004112 private void handleBindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004113 Service s = mServices.get(data.token);
Amith Yamasani742a6712011-05-04 14:49:28 -07004114 if (DEBUG_SERVICE)
4115 Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004116 if (s != null) {
4117 try {
4118 data.intent.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01004119 data.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004120 try {
4121 if (!data.rebind) {
4122 IBinder binder = s.onBind(data.intent);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004123 ActivityManager.getService().publishService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004124 data.token, data.intent, binder);
4125 } else {
4126 s.onRebind(data.intent);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004127 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08004128 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004129 }
4130 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004131 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132 }
4133 } catch (Exception e) {
4134 if (!mInstrumentation.onException(s, e)) {
4135 throw new RuntimeException(
4136 "Unable to bind to service " + s
4137 + " with " + data.intent + ": " + e.toString(), e);
4138 }
4139 }
4140 }
4141 }
4142
Romain Guy65b345f2011-07-27 18:51:50 -07004143 private void handleUnbindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004144 Service s = mServices.get(data.token);
4145 if (s != null) {
4146 try {
4147 data.intent.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01004148 data.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004149 boolean doRebind = s.onUnbind(data.intent);
4150 try {
4151 if (doRebind) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004152 ActivityManager.getService().unbindFinished(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004153 data.token, data.intent, doRebind);
4154 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004155 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08004156 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004157 }
4158 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004159 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004160 }
4161 } catch (Exception e) {
4162 if (!mInstrumentation.onException(s, e)) {
4163 throw new RuntimeException(
4164 "Unable to unbind to service " + s
4165 + " with " + data.intent + ": " + e.toString(), e);
4166 }
4167 }
4168 }
4169 }
4170
Dianne Hackborn625ac272010-09-17 18:29:22 -07004171 private void handleDumpService(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08004172 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
4173 try {
4174 Service s = mServices.get(info.token);
4175 if (s != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07004176 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
4177 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08004178 s.dump(info.fd.getFileDescriptor(), pw, info.args);
4179 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08004181 } finally {
4182 IoUtils.closeQuietly(info.fd);
4183 StrictMode.setThreadPolicy(oldPolicy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004184 }
4185 }
4186
Dianne Hackborn625ac272010-09-17 18:29:22 -07004187 private void handleDumpActivity(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08004188 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
4189 try {
4190 ActivityClientRecord r = mActivities.get(info.token);
4191 if (r != null && r.activity != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07004192 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
4193 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08004194 r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
4195 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07004196 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08004197 } finally {
4198 IoUtils.closeQuietly(info.fd);
4199 StrictMode.setThreadPolicy(oldPolicy);
Dianne Hackborn625ac272010-09-17 18:29:22 -07004200 }
4201 }
4202
Marco Nelissen18cb2872011-11-15 11:19:53 -08004203 private void handleDumpProvider(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08004204 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
4205 try {
4206 ProviderClientRecord r = mLocalProviders.get(info.token);
4207 if (r != null && r.mLocalProvider != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07004208 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
4209 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08004210 r.mLocalProvider.dump(info.fd.getFileDescriptor(), pw, info.args);
4211 pw.flush();
Marco Nelissen18cb2872011-11-15 11:19:53 -08004212 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08004213 } finally {
4214 IoUtils.closeQuietly(info.fd);
4215 StrictMode.setThreadPolicy(oldPolicy);
Marco Nelissen18cb2872011-11-15 11:19:53 -08004216 }
4217 }
4218
Romain Guy65b345f2011-07-27 18:51:50 -07004219 private void handleServiceArgs(ServiceArgsData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004220 Service s = mServices.get(data.token);
4221 if (s != null) {
4222 try {
4223 if (data.args != null) {
4224 data.args.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01004225 data.args.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004226 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004227 int res;
4228 if (!data.taskRemoved) {
4229 res = s.onStartCommand(data.args, data.flags, data.startId);
4230 } else {
4231 s.onTaskRemoved(data.args);
4232 res = Service.START_TASK_REMOVED_COMPLETE;
4233 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07004234
4235 QueuedWork.waitToFinish();
4236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004237 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004238 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08004239 data.token, SERVICE_DONE_EXECUTING_START, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004240 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004241 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004242 }
4243 } catch (Exception e) {
4244 if (!mInstrumentation.onException(s, e)) {
4245 throw new RuntimeException(
4246 "Unable to start service " + s
4247 + " with " + data.args + ": " + e.toString(), e);
4248 }
4249 }
4250 }
4251 }
4252
Romain Guy65b345f2011-07-27 18:51:50 -07004253 private void handleStopService(IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004254 Service s = mServices.remove(token);
4255 if (s != null) {
4256 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004257 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 s.onDestroy();
Amith Yamasani75928252017-05-22 15:10:47 -07004259 s.detachAndCleanUp();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004260 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08004261 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004262 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08004263 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004264 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07004265
4266 QueuedWork.waitToFinish();
4267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004268 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004269 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08004270 token, SERVICE_DONE_EXECUTING_STOP, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004272 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004273 }
4274 } catch (Exception e) {
4275 if (!mInstrumentation.onException(s, e)) {
4276 throw new RuntimeException(
4277 "Unable to stop service " + s
4278 + ": " + e.toString(), e);
4279 }
Craig Mautner66c4a822015-01-16 12:48:16 -08004280 Slog.i(TAG, "handleStopService: exception for " + token, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004281 }
Craig Mautner9776ad42015-01-15 14:38:39 -08004282 } else {
4283 Slog.i(TAG, "handleStopService: token=" + token + " not found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004284 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004285 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004286 }
4287
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004288 /**
4289 * Resume the activity.
4290 * @param token Target activity token.
4291 * @param finalStateRequest Flag indicating if this is part of final state resolution for a
4292 * transaction.
4293 * @param reason Reason for performing the action.
4294 *
4295 * @return The {@link ActivityClientRecord} that was resumed, {@code null} otherwise.
4296 */
4297 @VisibleForTesting
4298 public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
Andrii Kuliandfbf9712018-03-08 15:42:24 -08004299 String reason) {
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004300 final ActivityClientRecord r = mActivities.get(token);
4301 if (localLOGV) {
4302 Slog.v(TAG, "Performing resume of " + r + " finished=" + r.activity.mFinished);
4303 }
Andrii Kulian0f3356c2019-03-18 21:34:40 +00004304 if (r == null || r.activity.mFinished) {
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004305 return null;
4306 }
4307 if (r.getLifecycleState() == ON_RESUME) {
4308 if (!finalStateRequest) {
4309 final RuntimeException e = new IllegalStateException(
4310 "Trying to resume activity which is already resumed");
4311 Slog.e(TAG, e.getMessage(), e);
4312 Slog.e(TAG, r.getStateString());
4313 // TODO(lifecycler): A double resume request is possible when an activity
4314 // receives two consequent transactions with relaunch requests and "resumed"
4315 // final state requests and the second relaunch is omitted. We still try to
4316 // handle two resume requests for the final state. For cases other than this
4317 // one, we don't expect it to happen.
Andrii Kulian9956d892018-02-14 13:48:56 -08004318 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004319 return null;
4320 }
4321 if (finalStateRequest) {
4322 r.hideForNow = false;
4323 r.activity.mStartedActivity = false;
4324 }
4325 try {
4326 r.activity.onStateNotSaved();
4327 r.activity.mFragments.noteStateNotSaved();
4328 checkAndBlockForNetworkAccess();
4329 if (r.pendingIntents != null) {
4330 deliverNewIntents(r, r.pendingIntents);
4331 r.pendingIntents = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004332 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004333 if (r.pendingResults != null) {
Andrii Kuliane55b0092018-04-19 15:29:22 -07004334 deliverResults(r, r.pendingResults, reason);
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004335 r.pendingResults = null;
4336 }
4337 r.activity.performResume(r.startsNotResumed, reason);
Bob Leee5408332009-09-04 18:31:17 -07004338
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004339 r.state = null;
4340 r.persistentState = null;
4341 r.setState(ON_RESUME);
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004342
Andrii Kulian86024012019-04-18 19:41:23 -07004343 reportTopResumedActivityChanged(r, r.isTopResumedActivity, "topWhenResuming");
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004344 } catch (Exception e) {
4345 if (!mInstrumentation.onException(r.activity, e)) {
4346 throw new RuntimeException("Unable to resume activity "
4347 + r.intent.getComponent().toShortString() + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004348 }
4349 }
4350 return r;
4351 }
4352
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004353 static final void cleanUpPendingRemoveWindows(ActivityClientRecord r, boolean force) {
4354 if (r.mPreserveWindow && !force) {
4355 return;
4356 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004357 if (r.mPendingRemoveWindow != null) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004358 r.mPendingRemoveWindowManager.removeViewImmediate(
4359 r.mPendingRemoveWindow.getDecorView());
4360 IBinder wtoken = r.mPendingRemoveWindow.getDecorView().getWindowToken();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004361 if (wtoken != null) {
Jeff Brown98365d72012-08-19 20:30:52 -07004362 WindowManagerGlobal.getInstance().closeAll(wtoken,
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004363 r.activity.getClass().getName(), "Activity");
4364 }
4365 }
4366 r.mPendingRemoveWindow = null;
4367 r.mPendingRemoveWindowManager = null;
4368 }
4369
Andrii Kulian446e8242017-10-26 15:17:29 -07004370 @Override
Andrii Kuliandfbf9712018-03-08 15:42:24 -08004371 public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004372 String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004373 // If we are getting ready to gc after going to the background, well
4374 // we are back active so skip it.
4375 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004376 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004377
Adam Powellcfbe9be2013-11-06 14:58:58 -08004378 // TODO Push resumeArgs into the activity for consideration
Andrii Kuliandfbf9712018-03-08 15:42:24 -08004379 final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004380 if (r == null) {
4381 // We didn't actually resume the activity, so skipping any follow-up actions.
4382 return;
4383 }
Riddle Hsu66b74a82018-07-26 00:20:12 +08004384 if (mActivitiesToBeDestroyed.containsKey(token)) {
4385 // Although the activity is resumed, it is going to be destroyed. So the following
4386 // UI operations are unnecessary and also prevents exception because its token may
4387 // be gone that window manager cannot recognize it. All necessary cleanup actions
4388 // performed below will be done while handling destruction.
4389 return;
4390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004391
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004392 final Activity a = r.activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004393
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004394 if (localLOGV) {
4395 Slog.v(TAG, "Resume " + r + " started activity: " + a.mStartedActivity
4396 + ", hideForNow: " + r.hideForNow + ", finished: " + a.mFinished);
4397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004398
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004399 final int forwardBit = isForward
4400 ? WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07004401
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004402 // If the window hasn't yet been added to the window manager,
4403 // and this guy didn't finish itself or start another activity,
4404 // then go ahead and add the window.
4405 boolean willBeVisible = !a.mStartedActivity;
4406 if (!willBeVisible) {
4407 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004408 willBeVisible = ActivityTaskManager.getService().willActivityBeVisible(
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004409 a.getActivityToken());
4410 } catch (RemoteException e) {
4411 throw e.rethrowFromSystemServer();
4412 }
4413 }
4414 if (r.window == null && !a.mFinished && willBeVisible) {
4415 r.window = r.activity.getWindow();
4416 View decor = r.window.getDecorView();
4417 decor.setVisibility(View.INVISIBLE);
4418 ViewManager wm = a.getWindowManager();
4419 WindowManager.LayoutParams l = r.window.getAttributes();
4420 a.mDecor = decor;
4421 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
4422 l.softInputMode |= forwardBit;
4423 if (r.mPreserveWindow) {
4424 a.mWindowAdded = true;
4425 r.mPreserveWindow = false;
4426 // Normally the ViewRoot sets up callbacks with the Activity
4427 // in addView->ViewRootImpl#setView. If we are instead reusing
4428 // the decor view we have to notify the view root that the
4429 // callbacks may have changed.
4430 ViewRootImpl impl = decor.getViewRootImpl();
4431 if (impl != null) {
4432 impl.notifyChildRebuilt();
Dianne Hackborn061d58a2010-03-12 15:07:06 -08004433 }
4434 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004435 if (a.mVisibleFromClient) {
4436 if (!a.mWindowAdded) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004437 a.mWindowAdded = true;
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004438 wm.addView(decor, l);
4439 } else {
4440 // The activity will get a callback for this {@link LayoutParams} change
4441 // earlier. However, at that time the decor will not be set (this is set
4442 // in this method), so no action will be taken. This call ensures the
4443 // callback occurs with the decor set.
4444 a.onWindowAttributesChanged(l);
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004445 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004447
4448 // If the window has already been added, but during resume
4449 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08004450 // window visible.
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004451 } else if (!willBeVisible) {
4452 if (localLOGV) Slog.v(TAG, "Launch " + r + " mStartedActivity set");
4453 r.hideForNow = true;
4454 }
4455
4456 // Get rid of anything left hanging around.
4457 cleanUpPendingRemoveWindows(r, false /* force */);
4458
4459 // The window is now visible if it has been added, we are not
4460 // simply finishing, and we are not starting another activity.
4461 if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) {
4462 if (r.newConfig != null) {
4463 performConfigurationChangedForActivity(r, r.newConfig);
4464 if (DEBUG_CONFIGURATION) {
4465 Slog.v(TAG, "Resuming activity " + r.activityInfo.name + " with newConfig "
4466 + r.activity.mCurrentConfig);
4467 }
4468 r.newConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004469 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004470 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward=" + isForward);
Tiger Huang4a7835f2019-11-06 00:07:56 +08004471 ViewRootImpl impl = r.window.getDecorView().getViewRootImpl();
4472 WindowManager.LayoutParams l = impl != null
4473 ? impl.mWindowAttributes : r.window.getAttributes();
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004474 if ((l.softInputMode
4475 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
4476 != forwardBit) {
4477 l.softInputMode = (l.softInputMode
4478 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
4479 | forwardBit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004480 if (r.activity.mVisibleFromClient) {
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004481 ViewManager wm = a.getWindowManager();
4482 View decor = r.window.getDecorView();
4483 wm.updateViewLayout(decor, l);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004484 }
4485 }
4486
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004487 r.activity.mVisibleFromServer = true;
4488 mNumVisibleActivities++;
4489 if (r.activity.mVisibleFromClient) {
4490 r.activity.makeVisible();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004491 }
4492 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004493
4494 r.nextIdle = mNewActivities;
4495 mNewActivities = r;
4496 if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);
4497 Looper.myQueue().addIdleHandler(new Idler());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004498 }
4499
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004500
4501 @Override
4502 public void handleTopResumedActivityChanged(IBinder token, boolean onTop, String reason) {
4503 ActivityClientRecord r = mActivities.get(token);
4504 if (r == null || r.activity == null) {
4505 Slog.w(TAG, "Not found target activity to report position change for token: " + token);
4506 return;
4507 }
4508
4509 if (DEBUG_ORDER) {
4510 Slog.d(TAG, "Received position change to top: " + onTop + " for activity: " + r);
4511 }
4512
4513 if (r.isTopResumedActivity == onTop) {
4514 throw new IllegalStateException("Activity top position already set to onTop=" + onTop);
4515 }
4516
4517 r.isTopResumedActivity = onTop;
4518
4519 if (r.getLifecycleState() == ON_RESUME) {
Andrii Kulian86024012019-04-18 19:41:23 -07004520 reportTopResumedActivityChanged(r, onTop, "topStateChangedWhenResumed");
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004521 } else {
4522 if (DEBUG_ORDER) {
4523 Slog.d(TAG, "Won't deliver top position change in state=" + r.getLifecycleState());
4524 }
4525 }
4526 }
4527
4528 /**
4529 * Call {@link Activity#onTopResumedActivityChanged(boolean)} if its top resumed state changed
4530 * since the last report.
4531 */
Andrii Kulian86024012019-04-18 19:41:23 -07004532 private void reportTopResumedActivityChanged(ActivityClientRecord r, boolean onTop,
4533 String reason) {
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004534 if (r.lastReportedTopResumedState != onTop) {
4535 r.lastReportedTopResumedState = onTop;
Andrii Kulian86024012019-04-18 19:41:23 -07004536 r.activity.performTopResumedActivityChanged(onTop, reason);
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004537 }
4538 }
4539
Andrii Kulian446e8242017-10-26 15:17:29 -07004540 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004541 public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
Andrii Kuliana6176e32018-02-27 11:51:18 -08004542 int configChanges, PendingTransactionActions pendingActions, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004543 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004544 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004545 if (userLeaving) {
4546 performUserLeavingActivity(r);
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004547 r.mIsUserLeaving = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004548 }
Bob Leee5408332009-09-04 18:31:17 -07004549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004550 r.activity.mConfigChangeFlags |= configChanges;
Andrii Kuliand25680c2018-02-21 15:16:58 -08004551 performPauseActivity(r, finished, reason, pendingActions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004552
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07004553 // Make sure any pending writes are now committed.
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004554 if (r.isPreHoneycomb()) {
4555 QueuedWork.waitToFinish();
4556 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004557 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004558 }
4559 }
4560
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004561 final void performUserLeavingActivity(ActivityClientRecord r) {
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004562 r.mIsUserLeaving = true;
4563 mInstrumentation.callActivityOnPictureInPictureRequested(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004564 mInstrumentation.callActivityOnUserLeaving(r.activity);
4565 }
4566
Andrii Kulian8ae79572018-01-26 15:36:06 -08004567 final Bundle performPauseActivity(IBinder token, boolean finished, String reason,
4568 PendingTransactionActions pendingActions) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004569 ActivityClientRecord r = mActivities.get(token);
Andrii Kulian8ae79572018-01-26 15:36:06 -08004570 return r != null ? performPauseActivity(r, finished, reason, pendingActions) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004571 }
4572
Andrii Kulian8ae79572018-01-26 15:36:06 -08004573 /**
4574 * Pause the activity.
4575 * @return Saved instance state for pre-Honeycomb apps if it was saved, {@code null} otherwise.
4576 */
4577 private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
4578 PendingTransactionActions pendingActions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004579 if (r.paused) {
Andrii Kulian0f3356c2019-03-18 21:34:40 +00004580 if (r.activity.mFinished) {
4581 // If we are finishing, we won't call onResume() in certain cases.
4582 // So here we likewise don't want to call onPause() if the activity
4583 // isn't resumed.
4584 return null;
4585 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004586 RuntimeException e = new RuntimeException(
4587 "Performing pause of activity that is not resumed: "
4588 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004589 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004590 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004591 if (finished) {
4592 r.activity.mFinished = true;
4593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004594
Andrii Kulian8ae79572018-01-26 15:36:06 -08004595 // Pre-Honeycomb apps always save their state before pausing
4596 final boolean shouldSaveState = !r.activity.mFinished && r.isPreHoneycomb();
4597 if (shouldSaveState) {
4598 callActivityOnSaveInstanceState(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004599 }
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004600
4601 performPauseActivityIfNeeded(r, reason);
Jeff Hamilton52d32032011-01-08 15:31:26 -06004602
4603 // Notify any outstanding on paused listeners
4604 ArrayList<OnActivityPausedListener> listeners;
4605 synchronized (mOnPauseListeners) {
4606 listeners = mOnPauseListeners.remove(r.activity);
4607 }
4608 int size = (listeners != null ? listeners.size() : 0);
4609 for (int i = 0; i < size; i++) {
4610 listeners.get(i).onPaused(r.activity);
4611 }
4612
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004613 final Bundle oldState = pendingActions != null ? pendingActions.getOldState() : null;
4614 if (oldState != null) {
4615 // We need to keep around the original state, in case we need to be created again.
4616 // But we only do this for pre-Honeycomb apps, which always save their state when
4617 // pausing, so we can not have them save their state when restarting from a paused
4618 // state. For HC and later, we want to (and can) let the state be saved as the
4619 // normal part of stopping the activity.
4620 if (r.isPreHoneycomb()) {
4621 r.state = oldState;
4622 }
4623 }
4624
Andrii Kulian8ae79572018-01-26 15:36:06 -08004625 return shouldSaveState ? r.state : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004626 }
4627
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004628 private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
4629 if (r.paused) {
4630 // You are already paused silly...
4631 return;
4632 }
4633
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004634 // Always reporting top resumed position loss when pausing an activity. If necessary, it
4635 // will be restored in performResumeActivity().
Andrii Kulian86024012019-04-18 19:41:23 -07004636 reportTopResumedActivityChanged(r, false /* onTop */, "pausing");
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004637
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004638 try {
4639 r.activity.mCalled = false;
4640 mInstrumentation.callActivityOnPause(r.activity);
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004641 if (!r.activity.mCalled) {
4642 throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
4643 + " did not call through to super.onPause()");
4644 }
4645 } catch (SuperNotCalledException e) {
4646 throw e;
4647 } catch (Exception e) {
4648 if (!mInstrumentation.onException(r.activity, e)) {
4649 throw new RuntimeException("Unable to pause activity "
4650 + safeToComponentShortString(r.intent) + ": " + e.toString(), e);
4651 }
4652 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004653 r.setState(ON_PAUSE);
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004654 }
4655
Andrii Kulian829829c2018-03-19 18:19:05 -07004656 /** Called from {@link LocalActivityManager}. */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01004657 @UnsupportedAppUsage
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08004658 final void performStopActivity(IBinder token, boolean saveState, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004659 ActivityClientRecord r = mActivities.get(token);
Andrii Kulianb9faa032019-10-17 23:11:54 -07004660 performStopActivityInner(r, null /* stopInfo */, saveState, false /* finalStateRequest */,
4661 reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004662 }
4663
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004664 private static final class ProviderRefCount {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07004665 public final ContentProviderHolder holder;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004666 public final ProviderClientRecord client;
4667 public int stableCount;
4668 public int unstableCount;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004669
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004670 // When this is set, the stable and unstable ref counts are 0 and
4671 // we have a pending operation scheduled to remove the ref count
4672 // from the activity manager. On the activity manager we are still
4673 // holding an unstable ref, though it is not reflected in the counts
4674 // here.
4675 public boolean removePending;
4676
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07004677 ProviderRefCount(ContentProviderHolder inHolder,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004678 ProviderClientRecord inClient, int sCount, int uCount) {
4679 holder = inHolder;
4680 client = inClient;
4681 stableCount = sCount;
4682 unstableCount = uCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004683 }
4684 }
4685
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004686 /**
Andrii Kulianb9faa032019-10-17 23:11:54 -07004687 * Core implementation of stopping an activity.
Andrii Kulian829829c2018-03-19 18:19:05 -07004688 * @param r Target activity client record.
4689 * @param info Action that will report activity stop to server.
Andrii Kulian829829c2018-03-19 18:19:05 -07004690 * @param saveState Flag indicating whether the activity state should be saved.
4691 * @param finalStateRequest Flag indicating if this call is handling final lifecycle state
4692 * request for a transaction.
4693 * @param reason Reason for performing this operation.
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004694 */
Andrii Kulianb9faa032019-10-17 23:11:54 -07004695 private void performStopActivityInner(ActivityClientRecord r, StopInfo info,
Andrii Kulian829829c2018-03-19 18:19:05 -07004696 boolean saveState, boolean finalStateRequest, String reason) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004697 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004698 if (r != null) {
Andrii Kulianb9faa032019-10-17 23:11:54 -07004699 if (r.stopped) {
Andrii Kulian0f3356c2019-03-18 21:34:40 +00004700 if (r.activity.mFinished) {
4701 // If we are finishing, we won't call onResume() in certain
4702 // cases. So here we likewise don't want to call onStop()
4703 // if the activity isn't resumed.
4704 return;
4705 }
4706 if (!finalStateRequest) {
4707 final RuntimeException e = new RuntimeException(
4708 "Performing stop of activity that is already stopped: "
4709 + r.intent.getComponent().toShortString());
4710 Slog.e(TAG, e.getMessage(), e);
4711 Slog.e(TAG, r.getStateString());
4712 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004713 }
4714
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004715 // One must first be paused before stopped...
4716 performPauseActivityIfNeeded(r, reason);
4717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004718 if (info != null) {
4719 try {
4720 // First create a thumbnail for the activity...
Dianne Hackborn0500b3c2011-11-01 15:28:43 -07004721 // For now, don't create the thumbnail here; we are
4722 // doing that by doing a screen snapshot.
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004723 info.setDescription(r.activity.onCreateDescription());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004724 } catch (Exception e) {
4725 if (!mInstrumentation.onException(r.activity, e)) {
4726 throw new RuntimeException(
4727 "Unable to save state of activity "
4728 + r.intent.getComponent().toShortString()
4729 + ": " + e.toString(), e);
4730 }
4731 }
4732 }
4733
Andrii Kulianb9faa032019-10-17 23:11:54 -07004734 callActivityOnStop(r, saveState, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004735 }
4736 }
4737
Andrii Kulian8ae79572018-01-26 15:36:06 -08004738 /**
4739 * Calls {@link Activity#onStop()} and {@link Activity#onSaveInstanceState(Bundle)}, and updates
4740 * the client record's state.
4741 * All calls to stop an activity must be done through this method to make sure that
4742 * {@link Activity#onSaveInstanceState(Bundle)} is also executed in the same call.
4743 */
4744 private void callActivityOnStop(ActivityClientRecord r, boolean saveState, String reason) {
Andrii Kulian391161f2018-01-29 10:50:02 -08004745 // Before P onSaveInstanceState was called before onStop, starting with P it's
4746 // called after. Before Honeycomb state was always saved before onPause.
Andrii Kulian8ae79572018-01-26 15:36:06 -08004747 final boolean shouldSaveState = saveState && !r.activity.mFinished && r.state == null
4748 && !r.isPreHoneycomb();
Andrii Kulian391161f2018-01-29 10:50:02 -08004749 final boolean isPreP = r.isPreP();
4750 if (shouldSaveState && isPreP) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004751 callActivityOnSaveInstanceState(r);
4752 }
4753
4754 try {
Garfield Tanc1681e62018-05-29 11:05:05 -07004755 r.activity.performStop(r.mPreserveWindow, reason);
Andrii Kulian8ae79572018-01-26 15:36:06 -08004756 } catch (SuperNotCalledException e) {
4757 throw e;
4758 } catch (Exception e) {
4759 if (!mInstrumentation.onException(r.activity, e)) {
4760 throw new RuntimeException(
4761 "Unable to stop activity "
4762 + r.intent.getComponent().toShortString()
4763 + ": " + e.toString(), e);
4764 }
4765 }
4766 r.setState(ON_STOP);
Andrii Kulian391161f2018-01-29 10:50:02 -08004767
4768 if (shouldSaveState && !isPreP) {
4769 callActivityOnSaveInstanceState(r);
4770 }
Andrii Kulian8ae79572018-01-26 15:36:06 -08004771 }
4772
Romain Guy65b345f2011-07-27 18:51:50 -07004773 private void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004774 View v = r.activity.mDecor;
4775 if (v != null) {
4776 if (show) {
4777 if (!r.activity.mVisibleFromServer) {
4778 r.activity.mVisibleFromServer = true;
4779 mNumVisibleActivities++;
4780 if (r.activity.mVisibleFromClient) {
4781 r.activity.makeVisible();
4782 }
4783 }
4784 if (r.newConfig != null) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004785 performConfigurationChangedForActivity(r, r.newConfig);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004786 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Adam Lesinski082614c2016-03-04 14:33:47 -08004787 + r.activityInfo.name + " with new config "
4788 + r.activity.mCurrentConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004789 r.newConfig = null;
4790 }
4791 } else {
4792 if (r.activity.mVisibleFromServer) {
4793 r.activity.mVisibleFromServer = false;
4794 mNumVisibleActivities--;
4795 v.setVisibility(View.INVISIBLE);
4796 }
4797 }
4798 }
4799 }
4800
Andrii Kulian446e8242017-10-26 15:17:29 -07004801 @Override
Andrii Kulianb9faa032019-10-17 23:11:54 -07004802 public void handleStopActivity(IBinder token, int configChanges,
Andrii Kulian829829c2018-03-19 18:19:05 -07004803 PendingTransactionActions pendingActions, boolean finalStateRequest, String reason) {
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004804 final ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004805 r.activity.mConfigChangeFlags |= configChanges;
4806
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004807 final StopInfo stopInfo = new StopInfo();
Andrii Kulianb9faa032019-10-17 23:11:54 -07004808 performStopActivityInner(r, stopInfo, true /* saveState */, finalStateRequest,
Andrii Kulian829829c2018-03-19 18:19:05 -07004809 reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004810
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004811 if (localLOGV) Slog.v(
Andrii Kulianb9faa032019-10-17 23:11:54 -07004812 TAG, "Finishing stop of " + r + ": win=" + r.window);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004813
Andrii Kulianb9faa032019-10-17 23:11:54 -07004814 updateVisibility(r, false);
Bob Leee5408332009-09-04 18:31:17 -07004815
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004816 // Make sure any pending writes are now committed.
4817 if (!r.isPreHoneycomb()) {
4818 QueuedWork.waitToFinish();
4819 }
4820
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004821 stopInfo.setActivity(r);
4822 stopInfo.setState(r.state);
4823 stopInfo.setPersistentState(r.persistentState);
4824 pendingActions.setStopInfo(stopInfo);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004825 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004826 }
4827
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004828 /**
4829 * Schedule the call to tell the activity manager we have stopped. We don't do this
4830 * immediately, because we want to have a chance for any other pending work (in particular
4831 * memory trim requests) to complete before you tell the activity manager to proceed and allow
4832 * us to go fully into the background.
4833 */
4834 @Override
4835 public void reportStop(PendingTransactionActions pendingActions) {
4836 mH.post(pendingActions.getStopInfo());
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07004837 }
4838
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004839 @Override
4840 public void performRestartActivity(IBinder token, boolean start) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004841 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004842 if (r.stopped) {
Andrii Kuliand25680c2018-02-21 15:16:58 -08004843 r.activity.performRestart(start, "performRestartActivity");
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004844 if (start) {
4845 r.setState(ON_START);
4846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004847 }
4848 }
4849
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004850 private void handleSetCoreSettings(Bundle coreSettings) {
Craig Mautner88c05892013-06-28 09:47:45 -07004851 synchronized (mResourcesManager) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08004852 mCoreSettings = coreSettings;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004853 }
Jon Miranda836c0a82014-08-11 12:32:26 -07004854 onCoreSettingsChange();
4855 }
4856
4857 private void onCoreSettingsChange() {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08004858 if (updateDebugViewAttributeState()) {
Jon Miranda836c0a82014-08-11 12:32:26 -07004859 // request all activities to relaunch for the changes to take place
Adrian Roos03dd48c2019-03-19 17:17:37 -04004860 relaunchAllActivities(false /* preserveWindows */);
Fyodor Kupolovcb93d6f2017-05-04 17:27:16 -07004861 }
4862 }
4863
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08004864 private boolean updateDebugViewAttributeState() {
4865 boolean previousState = View.sDebugViewAttributes;
4866
4867 View.sDebugViewAttributesApplicationPackage = mCoreSettings.getString(
4868 Settings.Global.DEBUG_VIEW_ATTRIBUTES_APPLICATION_PACKAGE, "");
4869 String currentPackage = (mBoundApplication != null && mBoundApplication.appInfo != null)
MÃ¥rten Kongstad62eed6b2019-09-19 15:35:44 +02004870 ? mBoundApplication.appInfo.packageName : "<unknown-app>";
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08004871 View.sDebugViewAttributes =
4872 mCoreSettings.getInt(Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0
4873 || View.sDebugViewAttributesApplicationPackage.equals(currentPackage);
4874 return previousState != View.sDebugViewAttributes;
4875 }
4876
Adrian Roos03dd48c2019-03-19 17:17:37 -04004877 private void relaunchAllActivities(boolean preserveWindows) {
Fyodor Kupolovcb93d6f2017-05-04 17:27:16 -07004878 for (Map.Entry<IBinder, ActivityClientRecord> entry : mActivities.entrySet()) {
Adrian Roos03dd48c2019-03-19 17:17:37 -04004879 final ActivityClientRecord r = entry.getValue();
4880 if (!r.activity.mFinished) {
4881 if (preserveWindows && r.window != null) {
4882 r.mPreserveWindow = true;
4883 }
Andrii Kulian320e3b52018-05-03 16:26:25 -07004884 scheduleRelaunchActivity(entry.getKey());
Jon Miranda836c0a82014-08-11 12:32:26 -07004885 }
4886 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004887 }
4888
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004889 private void handleUpdatePackageCompatibilityInfo(UpdateCompatibilityData data) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00004890 LoadedApk apk = peekPackageInfo(data.pkg, false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004891 if (apk != null) {
Craig Mautner48d0d182013-06-11 07:53:06 -07004892 apk.setCompatibilityInfo(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004893 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00004894 apk = peekPackageInfo(data.pkg, true);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004895 if (apk != null) {
Craig Mautner48d0d182013-06-11 07:53:06 -07004896 apk.setCompatibilityInfo(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004897 }
4898 handleConfigurationChanged(mConfiguration, data.info);
Jeff Brown98365d72012-08-19 20:30:52 -07004899 WindowManagerGlobal.getInstance().reportNewConfiguration(mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004900 }
4901
Andrii Kuliane55b0092018-04-19 15:29:22 -07004902 private void deliverResults(ActivityClientRecord r, List<ResultInfo> results, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004903 final int N = results.size();
4904 for (int i=0; i<N; i++) {
4905 ResultInfo ri = results.get(i);
4906 try {
4907 if (ri.mData != null) {
4908 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01004909 ri.mData.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004910 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004911 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07004912 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004913 r.activity.dispatchActivityResult(ri.mResultWho,
Andrii Kuliane55b0092018-04-19 15:29:22 -07004914 ri.mRequestCode, ri.mResultCode, ri.mData, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004915 } catch (Exception e) {
4916 if (!mInstrumentation.onException(r.activity, e)) {
4917 throw new RuntimeException(
4918 "Failure delivering result " + ri + " to activity "
4919 + r.intent.getComponent().toShortString()
4920 + ": " + e.toString(), e);
4921 }
4922 }
4923 }
4924 }
4925
Andrii Kulian446e8242017-10-26 15:17:29 -07004926 @Override
Andrii Kuliane55b0092018-04-19 15:29:22 -07004927 public void handleSendResult(IBinder token, List<ResultInfo> results, String reason) {
Andrii Kulian446e8242017-10-26 15:17:29 -07004928 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004929 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004930 if (r != null) {
4931 final boolean resumed = !r.paused;
4932 if (!r.activity.mFinished && r.activity.mDecor != null
4933 && r.hideForNow && resumed) {
4934 // We had hidden the activity because it started another
4935 // one... we have gotten a result back and we are not
4936 // paused, so make sure our window is visible.
4937 updateVisibility(r, true);
4938 }
4939 if (resumed) {
4940 try {
4941 // Now we are idle.
4942 r.activity.mCalled = false;
4943 mInstrumentation.callActivityOnPause(r.activity);
4944 if (!r.activity.mCalled) {
4945 throw new SuperNotCalledException(
4946 "Activity " + r.intent.getComponent().toShortString()
4947 + " did not call through to super.onPause()");
4948 }
4949 } catch (SuperNotCalledException e) {
4950 throw e;
4951 } catch (Exception e) {
4952 if (!mInstrumentation.onException(r.activity, e)) {
4953 throw new RuntimeException(
4954 "Unable to pause activity "
4955 + r.intent.getComponent().toShortString()
4956 + ": " + e.toString(), e);
4957 }
4958 }
4959 }
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07004960 checkAndBlockForNetworkAccess();
Andrii Kuliane55b0092018-04-19 15:29:22 -07004961 deliverResults(r, results, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004962 if (resumed) {
Andrii Kuliane55b0092018-04-19 15:29:22 -07004963 r.activity.performResume(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004964 }
4965 }
4966 }
4967
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004968 /** Core implementation of activity destroy call. */
4969 ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
Bryce Leea33c13d2018-02-08 14:37:06 -08004970 int configChanges, boolean getNonConfigInstance, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004971 ActivityClientRecord r = mActivities.get(token);
Craig Mautner88c05892013-06-28 09:47:45 -07004972 Class<? extends Activity> activityClass = null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004973 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004974 if (r != null) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08004975 activityClass = r.activity.getClass();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004976 r.activity.mConfigChangeFlags |= configChanges;
4977 if (finishing) {
4978 r.activity.mFinished = true;
4979 }
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004980
4981 performPauseActivityIfNeeded(r, "destroy");
4982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004983 if (!r.stopped) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004984 callActivityOnStop(r, false /* saveState */, "destroy");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004985 }
4986 if (getNonConfigInstance) {
4987 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004988 r.lastNonConfigurationInstances
4989 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004990 } catch (Exception e) {
4991 if (!mInstrumentation.onException(r.activity, e)) {
4992 throw new RuntimeException(
4993 "Unable to retain activity "
4994 + r.intent.getComponent().toShortString()
4995 + ": " + e.toString(), e);
4996 }
4997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004998 }
4999 try {
5000 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07005001 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005002 if (!r.activity.mCalled) {
5003 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07005004 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005005 " did not call through to super.onDestroy()");
5006 }
5007 if (r.window != null) {
5008 r.window.closeAllPanels();
5009 }
5010 } catch (SuperNotCalledException e) {
5011 throw e;
5012 } catch (Exception e) {
5013 if (!mInstrumentation.onException(r.activity, e)) {
5014 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07005015 "Unable to destroy activity " + safeToComponentShortString(r.intent)
5016 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005017 }
5018 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08005019 r.setState(ON_DESTROY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005020 }
Tim Murray59f3dc12018-10-22 15:26:08 -07005021 schedulePurgeIdler();
Garfield Tan0443b372019-01-04 15:00:13 -08005022 // updatePendingActivityConfiguration() reads from mActivities to update
5023 // ActivityClientRecord which runs in a different thread. Protect modifications to
5024 // mActivities to avoid race.
5025 synchronized (mResourcesManager) {
5026 mActivities.remove(token);
5027 }
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08005028 StrictMode.decrementExpectedActivityCount(activityClass);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005029 return r;
5030 }
5031
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07005032 private static String safeToComponentShortString(Intent intent) {
5033 ComponentName component = intent.getComponent();
5034 return component == null ? "[Unknown]" : component.toShortString();
5035 }
5036
Andrii Kulian446e8242017-10-26 15:17:29 -07005037 @Override
Riddle Hsud3062cb2018-06-30 02:06:42 +08005038 public Map<IBinder, ClientTransactionItem> getActivitiesToBeDestroyed() {
5039 return mActivitiesToBeDestroyed;
5040 }
5041
5042 @Override
Andrii Kulian446e8242017-10-26 15:17:29 -07005043 public void handleDestroyActivity(IBinder token, boolean finishing, int configChanges,
Bryce Leea33c13d2018-02-08 14:37:06 -08005044 boolean getNonConfigInstance, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005045 ActivityClientRecord r = performDestroyActivity(token, finishing,
Bryce Leea33c13d2018-02-08 14:37:06 -08005046 configChanges, getNonConfigInstance, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005047 if (r != null) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07005048 cleanUpPendingRemoveWindows(r, finishing);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005049 WindowManager wm = r.activity.getWindowManager();
5050 View v = r.activity.mDecor;
5051 if (v != null) {
5052 if (r.activity.mVisibleFromServer) {
5053 mNumVisibleActivities--;
5054 }
5055 IBinder wtoken = v.getWindowToken();
5056 if (r.activity.mWindowAdded) {
Robert Carr77bdfb52016-05-02 18:18:31 -07005057 if (r.mPreserveWindow) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005058 // Hold off on removing this until the new activity's
5059 // window is being added.
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07005060 r.mPendingRemoveWindow = r.window;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005061 r.mPendingRemoveWindowManager = wm;
Andrii Kulianeac0ea52016-05-11 15:50:24 -07005062 // We can only keep the part of the view hierarchy that we control,
5063 // everything else must be removed, because it might not be able to
5064 // behave properly when activity is relaunching.
5065 r.window.clearContentView();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005066 } else {
5067 wm.removeViewImmediate(v);
5068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005069 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005070 if (wtoken != null && r.mPendingRemoveWindow == null) {
Jeff Brown98365d72012-08-19 20:30:52 -07005071 WindowManagerGlobal.getInstance().closeAll(wtoken,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005072 r.activity.getClass().getName(), "Activity");
Andrii Kulianeac0ea52016-05-11 15:50:24 -07005073 } else if (r.mPendingRemoveWindow != null) {
5074 // We're preserving only one window, others should be closed so app views
5075 // will be detached before the final tear down. It should be done now because
5076 // some components (e.g. WebView) rely on detach callbacks to perform receiver
5077 // unregister and other cleanup.
5078 WindowManagerGlobal.getInstance().closeAllExceptView(token, v,
5079 r.activity.getClass().getName(), "Activity");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005080 }
5081 r.activity.mDecor = null;
5082 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005083 if (r.mPendingRemoveWindow == null) {
5084 // If we are delaying the removal of the activity window, then
5085 // we can't clean up all windows here. Note that we can't do
5086 // so later either, which means any windows that aren't closed
5087 // by the app will leak. Well we try to warning them a lot
5088 // about leaking windows, because that is a bug, so if they are
5089 // using this recreate facility then they get to live with leaks.
Jeff Brown98365d72012-08-19 20:30:52 -07005090 WindowManagerGlobal.getInstance().closeAll(token,
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005091 r.activity.getClass().getName(), "Activity");
5092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005093
5094 // Mocked out contexts won't be participating in the normal
5095 // process lifecycle, but if we're running with a proper
5096 // ApplicationContext we need to have it tear down things
5097 // cleanly.
5098 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08005099 if (c instanceof ContextImpl) {
5100 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005101 r.activity.getClass().getName(), "Activity");
5102 }
5103 }
5104 if (finishing) {
5105 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07005106 ActivityTaskManager.getService().activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005107 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005108 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005109 }
5110 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07005111 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005112 }
5113
Andrii Kulianb372da62018-01-18 10:46:24 -08005114 @Override
5115 public ActivityClientRecord prepareRelaunchActivity(IBinder token,
Dianne Hackborn85d558c2014-11-04 10:31:54 -08005116 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
Andrii Kulianb372da62018-01-18 10:46:24 -08005117 int configChanges, MergedConfiguration config, boolean preserveWindow) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005118 ActivityClientRecord target = null;
Andrii Kulianb372da62018-01-18 10:46:24 -08005119 boolean scheduleRelaunch = false;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005120
Craig Mautner88c05892013-06-28 09:47:45 -07005121 synchronized (mResourcesManager) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005122 for (int i=0; i<mRelaunchingActivities.size(); i++) {
5123 ActivityClientRecord r = mRelaunchingActivities.get(i);
Filip Gruszczynskic3b61792016-01-22 16:43:48 -08005124 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: " + this + ", trying: " + r);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005125 if (r.token == token) {
5126 target = r;
5127 if (pendingResults != null) {
5128 if (r.pendingResults != null) {
5129 r.pendingResults.addAll(pendingResults);
5130 } else {
5131 r.pendingResults = pendingResults;
5132 }
5133 }
5134 if (pendingNewIntents != null) {
5135 if (r.pendingIntents != null) {
5136 r.pendingIntents.addAll(pendingNewIntents);
5137 } else {
5138 r.pendingIntents = pendingNewIntents;
5139 }
5140 }
5141 break;
5142 }
5143 }
5144
5145 if (target == null) {
Andrii Kulianb372da62018-01-18 10:46:24 -08005146 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: target is null");
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005147 target = new ActivityClientRecord();
5148 target.token = token;
5149 target.pendingResults = pendingResults;
5150 target.pendingIntents = pendingNewIntents;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07005151 target.mPreserveWindow = preserveWindow;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005152 mRelaunchingActivities.add(target);
Andrii Kulianb372da62018-01-18 10:46:24 -08005153 scheduleRelaunch = true;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005154 }
Andrii Kulianb372da62018-01-18 10:46:24 -08005155 target.createdConfig = config.getGlobalConfiguration();
5156 target.overrideConfig = config.getOverrideConfiguration();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005157 target.pendingConfigChanges |= configChanges;
5158 }
Andrii Kulianb372da62018-01-18 10:46:24 -08005159
5160 return scheduleRelaunch ? target : null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005161 }
5162
Andrii Kulianb372da62018-01-18 10:46:24 -08005163 @Override
5164 public void handleRelaunchActivity(ActivityClientRecord tmp,
5165 PendingTransactionActions pendingActions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005166 // If we are getting ready to gc after going to the background, well
5167 // we are back active so skip it.
5168 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07005169 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005170
5171 Configuration changedConfig = null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005172 int configChanges = 0;
Bob Leee5408332009-09-04 18:31:17 -07005173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005174 // First: make sure we have the most recent configuration and most
5175 // recent version of the activity, or skip it if some previous call
5176 // had taken a more recent version.
Craig Mautner88c05892013-06-28 09:47:45 -07005177 synchronized (mResourcesManager) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005178 int N = mRelaunchingActivities.size();
5179 IBinder token = tmp.token;
5180 tmp = null;
5181 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005182 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005183 if (r.token == token) {
5184 tmp = r;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005185 configChanges |= tmp.pendingConfigChanges;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005186 mRelaunchingActivities.remove(i);
5187 i--;
5188 N--;
5189 }
5190 }
Bob Leee5408332009-09-04 18:31:17 -07005191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005192 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005193 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005194 return;
5195 }
Bob Leee5408332009-09-04 18:31:17 -07005196
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08005197 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
5198 + tmp.token + " with configChanges=0x"
5199 + Integer.toHexString(configChanges));
5200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005201 if (mPendingConfiguration != null) {
5202 changedConfig = mPendingConfiguration;
5203 mPendingConfiguration = null;
5204 }
5205 }
Bob Leee5408332009-09-04 18:31:17 -07005206
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08005207 if (tmp.createdConfig != null) {
5208 // If the activity manager is passing us its current config,
5209 // assume that is really what we want regardless of what we
5210 // may have pending.
5211 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005212 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
5213 && mConfiguration.diff(tmp.createdConfig) != 0)) {
5214 if (changedConfig == null
5215 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
5216 changedConfig = tmp.createdConfig;
5217 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08005218 }
5219 }
Tim Murraye1e6c662015-04-07 13:24:14 -07005220
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005221 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07005222 + tmp.token + ": changedConfig=" + changedConfig);
Tim Murraye1e6c662015-04-07 13:24:14 -07005223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005224 // If there was a pending configuration change, execute it first.
5225 if (changedConfig != null) {
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005226 mCurDefaultDisplayDpi = changedConfig.densityDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -07005227 updateDefaultDensity();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04005228 handleConfigurationChanged(changedConfig, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005229 }
Bob Leee5408332009-09-04 18:31:17 -07005230
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005231 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005232 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005233 if (r == null) {
5234 return;
5235 }
Bob Leee5408332009-09-04 18:31:17 -07005236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005237 r.activity.mConfigChangeFlags |= configChanges;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07005238 r.mPreserveWindow = tmp.mPreserveWindow;
Bob Leee5408332009-09-04 18:31:17 -07005239
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08005240 r.activity.mChangingConfigurations = true;
5241
Robert Carr23fa16b2016-01-13 13:19:58 -08005242 // If we are preserving the main window across relaunches we would also like to preserve
5243 // the children. However the client side view system does not support preserving
5244 // the child views so we notify the window manager to expect these windows to
5245 // be replaced and defer requests to destroy or hide them. This way we can achieve
5246 // visual continuity. It's important that we do this here prior to pause and destroy
5247 // as that is when we may hide or remove the child views.
Robert Carr77bdfb52016-05-02 18:18:31 -07005248 //
5249 // There is another scenario, if we have decided locally to relaunch the app from a
5250 // call to recreate, then none of the windows will be prepared for replacement or
5251 // preserved by the server, so we want to notify it that we are preparing to replace
5252 // everything
Robert Carr23fa16b2016-01-13 13:19:58 -08005253 try {
Andrii Kulianb372da62018-01-18 10:46:24 -08005254 if (r.mPreserveWindow) {
Robert Carr77bdfb52016-05-02 18:18:31 -07005255 WindowManagerGlobal.getWindowSession().prepareToReplaceWindows(
Andrii Kulianb372da62018-01-18 10:46:24 -08005256 r.token, true /* childrenOnly */);
Robert Carr23fa16b2016-01-13 13:19:58 -08005257 }
5258 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005259 throw e.rethrowFromSystemServer();
Robert Carr23fa16b2016-01-13 13:19:58 -08005260 }
5261
Wale Ogunwale5527a502018-02-20 18:18:21 -08005262 handleRelaunchActivityInner(r, configChanges, tmp.pendingResults, tmp.pendingIntents,
5263 pendingActions, tmp.startsNotResumed, tmp.overrideConfig, "handleRelaunchActivity");
5264
5265 if (pendingActions != null) {
5266 // Only report a successful relaunch to WindowManager.
5267 pendingActions.setReportRelaunchToWindowManager(true);
Dianne Hackborne2b04802010-12-09 09:24:55 -08005268 }
Wale Ogunwale5527a502018-02-20 18:18:21 -08005269 }
5270
Andrii Kulian320e3b52018-05-03 16:26:25 -07005271 /**
5272 * Post a message to relaunch the activity. We do this instead of launching it immediately,
5273 * because this will destroy the activity from which it was called and interfere with the
5274 * lifecycle changes it was going through before. We need to make sure that we have finished
5275 * handling current transaction item before relaunching the activity.
5276 */
5277 void scheduleRelaunchActivity(IBinder token) {
Amin Shaikh96e60d72019-04-24 13:47:57 -04005278 mH.removeMessages(H.RELAUNCH_ACTIVITY, token);
Andrii Kulian320e3b52018-05-03 16:26:25 -07005279 sendMessage(H.RELAUNCH_ACTIVITY, token);
5280 }
Bob Leee5408332009-09-04 18:31:17 -07005281
Andrii Kulian320e3b52018-05-03 16:26:25 -07005282 /** Performs the activity relaunch locally vs. requesting from system-server. */
5283 private void handleRelaunchActivityLocally(IBinder token) {
Wale Ogunwale5527a502018-02-20 18:18:21 -08005284 final ActivityClientRecord r = mActivities.get(token);
5285 if (r == null) {
Andrii Kulian320e3b52018-05-03 16:26:25 -07005286 Log.w(TAG, "Activity to relaunch no longer exists");
Wale Ogunwale5527a502018-02-20 18:18:21 -08005287 return;
5288 }
5289
5290 final int prevState = r.getLifecycleState();
5291
Andrii Kulian320e3b52018-05-03 16:26:25 -07005292 if (prevState < ON_RESUME || prevState > ON_STOP) {
5293 Log.w(TAG, "Activity state must be in [ON_RESUME..ON_STOP] in order to be relaunched,"
5294 + "current state is " + prevState);
Wale Ogunwale5527a502018-02-20 18:18:21 -08005295 return;
5296 }
5297
Wale Ogunwale5527a502018-02-20 18:18:21 -08005298
Andrii Kulian914aa7d2018-03-19 21:51:53 -07005299 // Initialize a relaunch request.
5300 final MergedConfiguration mergedConfiguration = new MergedConfiguration(
5301 r.createdConfig != null ? r.createdConfig : mConfiguration,
5302 r.overrideConfig);
5303 final ActivityRelaunchItem activityRelaunchItem = ActivityRelaunchItem.obtain(
5304 null /* pendingResults */, null /* pendingIntents */, 0 /* configChanges */,
5305 mergedConfiguration, r.mPreserveWindow);
5306 // Make sure to match the existing lifecycle state in the end of the transaction.
5307 final ActivityLifecycleItem lifecycleRequest =
5308 TransactionExecutorHelper.getLifecycleRequestForCurrentState(r);
5309 // Schedule the transaction.
5310 final ClientTransaction transaction = ClientTransaction.obtain(this.mAppThread, r.token);
5311 transaction.addCallback(activityRelaunchItem);
5312 transaction.setLifecycleStateRequest(lifecycleRequest);
5313 executeTransaction(transaction);
Wale Ogunwale5527a502018-02-20 18:18:21 -08005314 }
5315
5316 private void handleRelaunchActivityInner(ActivityClientRecord r, int configChanges,
5317 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingIntents,
5318 PendingTransactionActions pendingActions, boolean startsNotResumed,
5319 Configuration overrideConfig, String reason) {
Andrii Kulian770c4032018-05-02 18:40:59 -07005320 // Preserve last used intent, it may be set from Activity#setIntent().
5321 final Intent customIntent = r.activity.mIntent;
Wale Ogunwale5527a502018-02-20 18:18:21 -08005322 // Need to ensure state is saved.
5323 if (!r.paused) {
5324 performPauseActivity(r, false, reason, null /* pendingActions */);
5325 }
5326 if (!r.stopped) {
5327 callActivityOnStop(r, true /* saveState */, reason);
5328 }
5329
5330 handleDestroyActivity(r.token, false, configChanges, true, reason);
Bob Leee5408332009-09-04 18:31:17 -07005331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005332 r.activity = null;
5333 r.window = null;
5334 r.hideForNow = false;
5335 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07005336 // Merge any pending results and pending intents; don't just replace them
Wale Ogunwale5527a502018-02-20 18:18:21 -08005337 if (pendingResults != null) {
The Android Open Source Project10592532009-03-18 17:39:46 -07005338 if (r.pendingResults == null) {
Wale Ogunwale5527a502018-02-20 18:18:21 -08005339 r.pendingResults = pendingResults;
The Android Open Source Project10592532009-03-18 17:39:46 -07005340 } else {
Wale Ogunwale5527a502018-02-20 18:18:21 -08005341 r.pendingResults.addAll(pendingResults);
The Android Open Source Project10592532009-03-18 17:39:46 -07005342 }
5343 }
Wale Ogunwale5527a502018-02-20 18:18:21 -08005344 if (pendingIntents != null) {
The Android Open Source Project10592532009-03-18 17:39:46 -07005345 if (r.pendingIntents == null) {
Wale Ogunwale5527a502018-02-20 18:18:21 -08005346 r.pendingIntents = pendingIntents;
The Android Open Source Project10592532009-03-18 17:39:46 -07005347 } else {
Wale Ogunwale5527a502018-02-20 18:18:21 -08005348 r.pendingIntents.addAll(pendingIntents);
The Android Open Source Project10592532009-03-18 17:39:46 -07005349 }
5350 }
Wale Ogunwale5527a502018-02-20 18:18:21 -08005351 r.startsNotResumed = startsNotResumed;
5352 r.overrideConfig = overrideConfig;
Bob Leee5408332009-09-04 18:31:17 -07005353
Andrii Kulian770c4032018-05-02 18:40:59 -07005354 handleLaunchActivity(r, pendingActions, customIntent);
Andrii Kulianb372da62018-01-18 10:46:24 -08005355 }
Jorim Jaggife89d122015-12-22 16:28:44 +01005356
Andrii Kulianb372da62018-01-18 10:46:24 -08005357 @Override
5358 public void reportRelaunch(IBinder token, PendingTransactionActions pendingActions) {
5359 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07005360 ActivityTaskManager.getService().activityRelaunched(token);
Andrii Kulianb372da62018-01-18 10:46:24 -08005361 final ActivityClientRecord r = mActivities.get(token);
5362 if (pendingActions.shouldReportRelaunchToWindowManager() && r != null
5363 && r.window != null) {
5364 r.window.reportActivityRelaunched();
Jorim Jaggife89d122015-12-22 16:28:44 +01005365 }
Andrii Kulianb372da62018-01-18 10:46:24 -08005366 } catch (RemoteException e) {
5367 throw e.rethrowFromSystemServer();
Jorim Jaggife89d122015-12-22 16:28:44 +01005368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005369 }
5370
Andrii Kulian8ae79572018-01-26 15:36:06 -08005371 private void callActivityOnSaveInstanceState(ActivityClientRecord r) {
Craig Mautnera0026042014-04-23 11:45:37 -07005372 r.state = new Bundle();
5373 r.state.setAllowFds(false);
5374 if (r.isPersistable()) {
5375 r.persistentState = new PersistableBundle();
5376 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state,
5377 r.persistentState);
5378 } else {
5379 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
5380 }
5381 }
5382
Dianne Hackborn73c14162012-09-19 15:45:06 -07005383 ArrayList<ComponentCallbacks2> collectComponentCallbacks(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005384 boolean allActivities, Configuration newConfig) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005385 ArrayList<ComponentCallbacks2> callbacks
5386 = new ArrayList<ComponentCallbacks2>();
Bob Leee5408332009-09-04 18:31:17 -07005387
Craig Mautner88c05892013-06-28 09:47:45 -07005388 synchronized (mResourcesManager) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005389 final int NAPP = mAllApplications.size();
5390 for (int i=0; i<NAPP; i++) {
Dianne Hackborn73c14162012-09-19 15:45:06 -07005391 callbacks.add(mAllApplications.get(i));
5392 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005393 final int NACT = mActivities.size();
5394 for (int i=0; i<NACT; i++) {
5395 ActivityClientRecord ar = mActivities.valueAt(i);
5396 Activity a = ar.activity;
5397 if (a != null) {
5398 Configuration thisConfig = applyConfigCompatMainThread(
5399 mCurDefaultDisplayDpi, newConfig,
Todd Kennedy233a0b12018-01-29 20:30:24 +00005400 ar.packageInfo.getCompatibilityInfo());
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005401 if (!ar.activity.mFinished && (allActivities || !ar.paused)) {
5402 // If the activity is currently resumed, its configuration
5403 // needs to change right now.
5404 callbacks.add(a);
5405 } else if (thisConfig != null) {
5406 // Otherwise, we will tell it about the change
5407 // the next time it is resumed or shown. Note that
5408 // the activity manager may, before then, decide the
5409 // activity needs to be destroyed to handle its new
5410 // configuration.
5411 if (DEBUG_CONFIGURATION) {
5412 Slog.v(TAG, "Setting activity "
5413 + ar.activityInfo.name + " newConfig=" + thisConfig);
Romain Guya998dff2012-03-23 18:58:36 -07005414 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005415 ar.newConfig = thisConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005416 }
5417 }
5418 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005419 final int NSVC = mServices.size();
5420 for (int i=0; i<NSVC; i++) {
lumarkddc77fb2019-06-27 22:22:23 +08005421 final ComponentCallbacks2 serviceComp = mServices.valueAt(i);
5422 if (serviceComp instanceof InputMethodService) {
5423 mHasImeComponent = true;
5424 }
5425 callbacks.add(serviceComp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005426 }
5427 }
5428 synchronized (mProviderMap) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005429 final int NPRV = mLocalProviders.size();
5430 for (int i=0; i<NPRV; i++) {
5431 callbacks.add(mLocalProviders.valueAt(i).mLocalProvider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005432 }
5433 }
Bob Leee5408332009-09-04 18:31:17 -07005434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005435 return callbacks;
5436 }
Bob Leee5408332009-09-04 18:31:17 -07005437
Adam Lesinski082614c2016-03-04 14:33:47 -08005438 /**
5439 * Updates the configuration for an Activity. The ActivityClientRecord's
5440 * {@link ActivityClientRecord#overrideConfig} is used to compute the final Configuration for
5441 * that Activity. {@link ActivityClientRecord#tmpConfig} is used as a temporary for delivering
5442 * the updated Configuration.
5443 * @param r ActivityClientRecord representing the Activity.
5444 * @param newBaseConfig The new configuration to use. This may be augmented with
5445 * {@link ActivityClientRecord#overrideConfig}.
Adam Lesinski082614c2016-03-04 14:33:47 -08005446 */
5447 private void performConfigurationChangedForActivity(ActivityClientRecord r,
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005448 Configuration newBaseConfig) {
5449 performConfigurationChangedForActivity(r, newBaseConfig,
Yohei Yukawa5281b6b2018-10-15 07:38:25 +08005450 r.activity.getDisplayId(), false /* movedToDifferentDisplay */);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005451 }
5452
5453 /**
5454 * Updates the configuration for an Activity. The ActivityClientRecord's
5455 * {@link ActivityClientRecord#overrideConfig} is used to compute the final Configuration for
5456 * that Activity. {@link ActivityClientRecord#tmpConfig} is used as a temporary for delivering
5457 * the updated Configuration.
5458 * @param r ActivityClientRecord representing the Activity.
5459 * @param newBaseConfig The new configuration to use. This may be augmented with
5460 * {@link ActivityClientRecord#overrideConfig}.
5461 * @param displayId The id of the display where the Activity currently resides.
5462 * @param movedToDifferentDisplay Indicates if the activity was moved to different display.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005463 * @return {@link Configuration} instance sent to client, null if not sent.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005464 */
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005465 private Configuration performConfigurationChangedForActivity(ActivityClientRecord r,
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005466 Configuration newBaseConfig, int displayId, boolean movedToDifferentDisplay) {
Adam Lesinski082614c2016-03-04 14:33:47 -08005467 r.tmpConfig.setTo(newBaseConfig);
5468 if (r.overrideConfig != null) {
5469 r.tmpConfig.updateFrom(r.overrideConfig);
5470 }
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005471 final Configuration reportedConfig = performActivityConfigurationChanged(r.activity,
5472 r.tmpConfig, r.overrideConfig, displayId, movedToDifferentDisplay);
Adam Lesinski082614c2016-03-04 14:33:47 -08005473 freeTextLayoutCachesIfNeeded(r.activity.mCurrentConfig.diff(r.tmpConfig));
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005474 return reportedConfig;
Adam Lesinski082614c2016-03-04 14:33:47 -08005475 }
5476
5477 /**
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -07005478 * Creates a new Configuration only if override would modify base. Otherwise returns base.
5479 * @param base The base configuration.
5480 * @param override The update to apply to the base configuration. Can be null.
5481 * @return A Configuration representing base with override applied.
5482 */
5483 private static Configuration createNewConfigAndUpdateIfNotNull(@NonNull Configuration base,
5484 @Nullable Configuration override) {
5485 if (override == null) {
5486 return base;
5487 }
5488 Configuration newConfig = new Configuration(base);
5489 newConfig.updateFrom(override);
5490 return newConfig;
5491 }
5492
5493 /**
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005494 * Decides whether to update a component's configuration and whether to inform it.
Adam Lesinski082614c2016-03-04 14:33:47 -08005495 * @param cb The component callback to notify of configuration change.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005496 * @param newConfig The new configuration.
5497 */
5498 private void performConfigurationChanged(ComponentCallbacks2 cb, Configuration newConfig) {
5499 if (!REPORT_TO_ACTIVITY) {
5500 return;
5501 }
5502
5503 // ContextThemeWrappers may override the configuration for that context. We must check and
5504 // apply any overrides defined.
5505 Configuration contextThemeWrapperOverrideConfig = null;
5506 if (cb instanceof ContextThemeWrapper) {
5507 final ContextThemeWrapper contextThemeWrapper = (ContextThemeWrapper) cb;
5508 contextThemeWrapperOverrideConfig = contextThemeWrapper.getOverrideConfiguration();
5509 }
5510
5511 // Apply the ContextThemeWrapper override if necessary.
5512 // NOTE: Make sure the configurations are not modified, as they are treated as immutable
5513 // in many places.
5514 final Configuration configToReport = createNewConfigAndUpdateIfNotNull(
5515 newConfig, contextThemeWrapperOverrideConfig);
5516 cb.onConfigurationChanged(configToReport);
5517 }
5518
5519 /**
5520 * Decides whether to update an Activity's configuration and whether to inform it.
5521 * @param activity The activity to notify of configuration change.
Adam Lesinski082614c2016-03-04 14:33:47 -08005522 * @param newConfig The new configuration.
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -07005523 * @param amOverrideConfig The override config that differentiates the Activity's configuration
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005524 * from the base global configuration. This is supplied by
5525 * ActivityManager.
5526 * @param displayId Id of the display where activity currently resides.
5527 * @param movedToDifferentDisplay Indicates if the activity was moved to different display.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005528 * @return Configuration sent to client, null if no changes and not moved to different display.
Adam Lesinski082614c2016-03-04 14:33:47 -08005529 */
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005530 private Configuration performActivityConfigurationChanged(Activity activity,
5531 Configuration newConfig, Configuration amOverrideConfig, int displayId,
5532 boolean movedToDifferentDisplay) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005533 if (activity == null) {
5534 throw new IllegalArgumentException("No activity provided.");
5535 }
5536 final IBinder activityToken = activity.getActivityToken();
5537 if (activityToken == null) {
5538 throw new IllegalArgumentException("Activity token not set. Is the activity attached?");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539 }
Bob Leee5408332009-09-04 18:31:17 -07005540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005541 boolean shouldChangeConfig = false;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005542 if (activity.mCurrentConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005543 shouldChangeConfig = true;
5544 } else {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005545 // If the new config is the same as the config this Activity is already running with and
5546 // the override config also didn't change, then don't bother calling
5547 // onConfigurationChanged.
Bryce Lee658d9842017-07-28 08:33:36 -07005548 final int diff = activity.mCurrentConfig.diffPublicOnly(newConfig);
5549
Andrii Kulian3b3c9142016-07-18 19:15:56 -07005550 if (diff != 0 || !mResourcesManager.isSameResourcesOverrideConfig(activityToken,
5551 amOverrideConfig)) {
Chong Zhang4951f9d2016-06-23 13:15:08 -07005552 // Always send the task-level config changes. For system-level configuration, if
5553 // this activity doesn't handle any of the config changes, then don't bother
5554 // calling onConfigurationChanged as we're going to destroy it.
5555 if (!mUpdatingSystemConfig
5556 || (~activity.mActivityInfo.getRealConfigChanged() & diff) == 0
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005557 || !REPORT_TO_ACTIVITY) {
Chong Zhang4951f9d2016-06-23 13:15:08 -07005558 shouldChangeConfig = true;
5559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005560 }
5561 }
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005562 if (!shouldChangeConfig && !movedToDifferentDisplay) {
5563 // Nothing significant, don't proceed with updating and reporting.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005564 return null;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005565 }
5566
5567 // Propagate the configuration change to ResourcesManager and Activity.
5568
5569 // ContextThemeWrappers may override the configuration for that context. We must check and
5570 // apply any overrides defined.
5571 Configuration contextThemeWrapperOverrideConfig = activity.getOverrideConfiguration();
5572
5573 // We only update an Activity's configuration if this is not a global configuration change.
5574 // This must also be done before the callback, or else we violate the contract that the new
5575 // resources are available in ComponentCallbacks2#onConfigurationChanged(Configuration).
5576 // Also apply the ContextThemeWrapper override if necessary.
5577 // NOTE: Make sure the configurations are not modified, as they are treated as immutable in
5578 // many places.
5579 final Configuration finalOverrideConfig = createNewConfigAndUpdateIfNotNull(
5580 amOverrideConfig, contextThemeWrapperOverrideConfig);
5581 mResourcesManager.updateResourcesForActivity(activityToken, finalOverrideConfig,
5582 displayId, movedToDifferentDisplay);
5583
5584 activity.mConfigChangeFlags = 0;
5585 activity.mCurrentConfig = new Configuration(newConfig);
5586
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005587 // Apply the ContextThemeWrapper override if necessary.
5588 // NOTE: Make sure the configurations are not modified, as they are treated as immutable
5589 // in many places.
5590 final Configuration configToReport = createNewConfigAndUpdateIfNotNull(newConfig,
5591 contextThemeWrapperOverrideConfig);
5592
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005593 if (!REPORT_TO_ACTIVITY) {
5594 // Not configured to report to activity.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005595 return configToReport;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005596 }
5597
5598 if (movedToDifferentDisplay) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005599 activity.dispatchMovedToDisplay(displayId, configToReport);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005600 }
Bob Leee5408332009-09-04 18:31:17 -07005601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 if (shouldChangeConfig) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005603 activity.mCalled = false;
5604 activity.onConfigurationChanged(configToReport);
5605 if (!activity.mCalled) {
5606 throw new SuperNotCalledException("Activity " + activity.getLocalClassName() +
5607 " did not call through to super.onConfigurationChanged()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005608 }
5609 }
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005610
5611 return configToReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005612 }
5613
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07005614 public final void applyConfigurationToResources(Configuration config) {
Craig Mautner88c05892013-06-28 09:47:45 -07005615 synchronized (mResourcesManager) {
5616 mResourcesManager.applyConfigurationToResourcesLocked(config, null);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07005617 }
5618 }
5619
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005620 final Configuration applyCompatConfiguration(int displayDensity) {
Dianne Hackborn836e2622011-10-04 18:32:39 -07005621 Configuration config = mConfiguration;
5622 if (mCompatConfiguration == null) {
5623 mCompatConfiguration = new Configuration();
5624 }
5625 mCompatConfiguration.setTo(mConfiguration);
Adam Lesinski082614c2016-03-04 14:33:47 -08005626 if (mResourcesManager.applyCompatConfigurationLocked(displayDensity,
5627 mCompatConfiguration)) {
Dianne Hackborn836e2622011-10-04 18:32:39 -07005628 config = mCompatConfiguration;
5629 }
5630 return config;
5631 }
5632
Andrii Kulian446e8242017-10-26 15:17:29 -07005633 @Override
5634 public void handleConfigurationChanged(Configuration config) {
5635 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "configChanged");
5636 mCurDefaultDisplayDpi = config.densityDpi;
5637 mUpdatingSystemConfig = true;
5638 try {
5639 handleConfigurationChanged(config, null /* compat */);
5640 } finally {
5641 mUpdatingSystemConfig = false;
5642 }
5643 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
5644 }
5645
5646 private void handleConfigurationChanged(Configuration config, CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005647
Tiger Huang968064b2019-05-28 14:36:18 +08005648 int configDiff;
5649 boolean equivalent;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005650
Todd Kennedy35a9a382018-01-25 13:25:37 -08005651 final Theme systemTheme = getSystemContext().getTheme();
5652 final Theme systemUiTheme = getSystemUiContext().getTheme();
Bryce Lee658d9842017-07-28 08:33:36 -07005653
Craig Mautner88c05892013-06-28 09:47:45 -07005654 synchronized (mResourcesManager) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005655 if (mPendingConfiguration != null) {
5656 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
5657 config = mPendingConfiguration;
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005658 mCurDefaultDisplayDpi = config.densityDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -07005659 updateDefaultDensity();
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005660 }
5661 mPendingConfiguration = null;
5662 }
5663
5664 if (config == null) {
lumarkddc77fb2019-06-27 22:22:23 +08005665 // TODO (b/135719017): Temporary log for debugging IME service.
5666 if (Build.IS_DEBUGGABLE && mHasImeComponent) {
5667 Log.w(TAG, "handleConfigurationChanged for IME app but config is null");
5668 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005669 return;
5670 }
Tim Murraye1e6c662015-04-07 13:24:14 -07005671
Tiger Huang968064b2019-05-28 14:36:18 +08005672 // This flag tracks whether the new configuration is fundamentally equivalent to the
5673 // existing configuration. This is necessary to determine whether non-activity callbacks
5674 // should receive notice when the only changes are related to non-public fields.
5675 // We do not gate calling {@link #performActivityConfigurationChanged} based on this
5676 // flag as that method uses the same check on the activity config override as well.
5677 equivalent = mConfiguration != null && (0 == mConfiguration.diffPublicOnly(config));
5678
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005679 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005680 + config);
Craig Mautner88c05892013-06-28 09:47:45 -07005681
5682 mResourcesManager.applyConfigurationToResourcesLocked(config, compat);
Adam Lesinskib61e4052016-05-19 18:23:05 -07005683 updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
5684 mResourcesManager.getConfiguration().getLocales());
Craig Mautner88c05892013-06-28 09:47:45 -07005685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005686 if (mConfiguration == null) {
5687 mConfiguration = new Configuration();
5688 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04005689 if (!mConfiguration.isOtherSeqNewer(config) && compat == null) {
lumarkddc77fb2019-06-27 22:22:23 +08005690 // TODO (b/135719017): Temporary log for debugging IME service.
5691 if (Build.IS_DEBUGGABLE && mHasImeComponent) {
5692 Log.w(TAG, "handleConfigurationChanged for IME app but config seq is obsolete "
5693 + ", config=" + config
5694 + ", mConfiguration=" + mConfiguration);
5695 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005696 return;
5697 }
Alan Viverettee54d2452015-05-06 10:41:43 -07005698
5699 configDiff = mConfiguration.updateFrom(config);
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005700 config = applyCompatConfiguration(mCurDefaultDisplayDpi);
Alan Viverette395cd012015-08-11 17:27:04 -04005701
Alan Viverette395cd012015-08-11 17:27:04 -04005702 if ((systemTheme.getChangingConfigurations() & configDiff) != 0) {
5703 systemTheme.rebase();
5704 }
Adam Lesinskia82b6262017-03-21 16:56:17 -07005705
Adam Lesinskia82b6262017-03-21 16:56:17 -07005706 if ((systemUiTheme.getChangingConfigurations() & configDiff) != 0) {
5707 systemUiTheme.rebase();
5708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005709 }
Dianne Hackborn73c14162012-09-19 15:45:06 -07005710
5711 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(false, config);
5712
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005713 freeTextLayoutCachesIfNeeded(configDiff);
5714
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005715 if (callbacks != null) {
5716 final int N = callbacks.size();
5717 for (int i=0; i<N; i++) {
Andrii Kulian701214b2016-04-07 09:36:33 -07005718 ComponentCallbacks2 cb = callbacks.get(i);
5719 if (cb instanceof Activity) {
5720 // If callback is an Activity - call corresponding method to consider override
5721 // config and avoid onConfigurationChanged if it hasn't changed.
5722 Activity a = (Activity) cb;
5723 performConfigurationChangedForActivity(mActivities.get(a.getActivityToken()),
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005724 config);
Bryce Lee658d9842017-07-28 08:33:36 -07005725 } else if (!equivalent) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005726 performConfigurationChanged(cb, config);
lumarkddc77fb2019-06-27 22:22:23 +08005727 } else {
5728 // TODO (b/135719017): Temporary log for debugging IME service.
5729 if (Build.IS_DEBUGGABLE && cb instanceof InputMethodService) {
5730 Log.w(TAG, "performConfigurationChanged didn't callback to IME "
5731 + ", configDiff=" + configDiff
5732 + ", mConfiguration=" + mConfiguration);
5733 }
Andrii Kulian701214b2016-04-07 09:36:33 -07005734 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 }
5737 }
5738
Winson72dbe7e2019-04-29 14:55:30 -07005739 /**
5740 * Updates the application info.
5741 *
5742 * This only works in the system process. Must be called on the main thread.
5743 */
5744 public void handleSystemApplicationInfoChanged(@NonNull ApplicationInfo ai) {
5745 Preconditions.checkState(mSystemThread, "Must only be called in the system process");
5746 handleApplicationInfoChanged(ai);
5747 }
5748
Adrian Roos03dd48c2019-03-19 17:17:37 -04005749 @VisibleForTesting(visibility = PACKAGE)
5750 public void handleApplicationInfoChanged(@NonNull final ApplicationInfo ai) {
Adam Lesinskid33ef562017-01-19 14:49:59 -08005751 // Updates triggered by package installation go through a package update
5752 // receiver. Here we try to capture ApplicationInfo changes that are
5753 // caused by other sources, such as overlays. That means we want to be as conservative
5754 // about code changes as possible. Take the diff of the old ApplicationInfo and the new
5755 // to see if anything needs to change.
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005756 LoadedApk apk;
5757 LoadedApk resApk;
5758 // Update all affected loaded packages with new package information
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005759 synchronized (mResourcesManager) {
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005760 WeakReference<LoadedApk> ref = mPackages.get(ai.packageName);
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005761 apk = ref != null ? ref.get() : null;
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005762 ref = mResourcePackages.get(ai.packageName);
5763 resApk = ref != null ? ref.get() : null;
5764 }
Winsond605e2d2019-02-11 16:05:51 -08005765
5766 final String[] oldResDirs = new String[2];
5767
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005768 if (apk != null) {
Winsond605e2d2019-02-11 16:05:51 -08005769 oldResDirs[0] = apk.getResDir();
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005770 final ArrayList<String> oldPaths = new ArrayList<>();
5771 LoadedApk.makePaths(this, apk.getApplicationInfo(), oldPaths);
5772 apk.updateApplicationInfo(ai, oldPaths);
5773 }
5774 if (resApk != null) {
Winsond605e2d2019-02-11 16:05:51 -08005775 oldResDirs[1] = resApk.getResDir();
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005776 final ArrayList<String> oldPaths = new ArrayList<>();
5777 LoadedApk.makePaths(this, resApk.getApplicationInfo(), oldPaths);
5778 resApk.updateApplicationInfo(ai, oldPaths);
5779 }
Winsond605e2d2019-02-11 16:05:51 -08005780
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005781 synchronized (mResourcesManager) {
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005782 // Update all affected Resources objects to use new ResourcesImpl
Winsond605e2d2019-02-11 16:05:51 -08005783 mResourcesManager.applyNewResourceDirsLocked(ai, oldResDirs);
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005784 }
5785
5786 ApplicationPackageManager.configurationChanged();
5787
5788 // Trigger a regular Configuration change event, only with a different assetsSeq number
5789 // so that we actually call through to all components.
Adam Lesinskia82b6262017-03-21 16:56:17 -07005790 // TODO(adamlesinski): Change this to make use of ActivityManager's upcoming ability to
5791 // store configurations per-process.
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005792 Configuration newConfig = new Configuration();
Adam Lesinskia82b6262017-03-21 16:56:17 -07005793 newConfig.assetsSeq = (mConfiguration != null ? mConfiguration.assetsSeq : 0) + 1;
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005794 handleConfigurationChanged(newConfig, null);
5795
Adrian Roos03dd48c2019-03-19 17:17:37 -04005796 // Preserve windows to avoid black flickers when overlays change.
5797 relaunchAllActivities(true /* preserveWindows */);
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005798 }
5799
Romain Guy46bfc482013-08-16 18:38:29 -07005800 static void freeTextLayoutCachesIfNeeded(int configDiff) {
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005801 if (configDiff != 0) {
5802 // Ask text layout engine to free its caches if there is a locale change
5803 boolean hasLocaleConfigChange = ((configDiff & ActivityInfo.CONFIG_LOCALE) != 0);
5804 if (hasLocaleConfigChange) {
5805 Canvas.freeTextLayoutCaches();
5806 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Cleared TextLayout Caches");
5807 }
5808 }
5809 }
5810
Garfield Tan0443b372019-01-04 15:00:13 -08005811 @Override
5812 public void updatePendingActivityConfiguration(IBinder activityToken,
5813 Configuration overrideConfig) {
5814 final ActivityClientRecord r;
5815 synchronized (mResourcesManager) {
5816 r = mActivities.get(activityToken);
5817 }
5818
5819 if (r == null) {
5820 if (DEBUG_CONFIGURATION) {
5821 Slog.w(TAG, "Not found target activity to update its pending config.");
5822 }
5823 return;
5824 }
5825
5826 synchronized (r) {
5827 r.mPendingOverrideConfig = overrideConfig;
5828 }
5829 }
5830
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005831 /**
5832 * Handle new activity configuration and/or move to a different display.
Andrii Kulian446e8242017-10-26 15:17:29 -07005833 * @param activityToken Target activity token.
5834 * @param overrideConfig Activity override config.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005835 * @param displayId Id of the display where activity was moved to, -1 if there was no move and
5836 * value didn't change.
5837 */
Andrii Kulian446e8242017-10-26 15:17:29 -07005838 @Override
5839 public void handleActivityConfigurationChanged(IBinder activityToken,
5840 Configuration overrideConfig, int displayId) {
5841 ActivityClientRecord r = mActivities.get(activityToken);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005842 // Check input params.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005843 if (r == null || r.activity == null) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005844 if (DEBUG_CONFIGURATION) Slog.w(TAG, "Not found target activity to report to: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 return;
5846 }
Andrii Kulian51c1b672017-04-07 18:39:32 -07005847 final boolean movedToDifferentDisplay = displayId != INVALID_DISPLAY
Yohei Yukawa5281b6b2018-10-15 07:38:25 +08005848 && displayId != r.activity.getDisplayId();
Bob Leee5408332009-09-04 18:31:17 -07005849
Garfield Tan0443b372019-01-04 15:00:13 -08005850 synchronized (r) {
5851 if (r.mPendingOverrideConfig != null
5852 && !r.mPendingOverrideConfig.isOtherSeqNewer(overrideConfig)) {
5853 overrideConfig = r.mPendingOverrideConfig;
5854 }
5855 r.mPendingOverrideConfig = null;
5856 }
5857
5858 if (r.overrideConfig != null && !r.overrideConfig.isOtherSeqNewer(overrideConfig)
5859 && !movedToDifferentDisplay) {
5860 if (DEBUG_CONFIGURATION) {
5861 Slog.v(TAG, "Activity already handled newer configuration so drop this"
5862 + " transaction. overrideConfig=" + overrideConfig + " r.overrideConfig="
5863 + r.overrideConfig);
5864 }
5865 return;
5866 }
5867
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005868 // Perform updates.
Andrii Kulian446e8242017-10-26 15:17:29 -07005869 r.overrideConfig = overrideConfig;
Stephen Kiazykf903b732017-03-20 16:23:45 -07005870 final ViewRootImpl viewRoot = r.activity.mDecor != null
5871 ? r.activity.mDecor.getViewRootImpl() : null;
5872
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005873 if (movedToDifferentDisplay) {
5874 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity moved to display, activity:"
5875 + r.activityInfo.name + ", displayId=" + displayId
Andrii Kulian446e8242017-10-26 15:17:29 -07005876 + ", config=" + overrideConfig);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005877
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005878 final Configuration reportedConfig = performConfigurationChangedForActivity(r,
5879 mCompatConfiguration, displayId, true /* movedToDifferentDisplay */);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005880 if (viewRoot != null) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005881 viewRoot.onMovedToDisplay(displayId, reportedConfig);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005882 }
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005883 } else {
5884 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Andrii Kulian446e8242017-10-26 15:17:29 -07005885 + r.activityInfo.name + ", config=" + overrideConfig);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005886 performConfigurationChangedForActivity(r, mCompatConfiguration);
5887 }
Andrii Kulian44607962017-03-16 11:06:24 -07005888 // Notify the ViewRootImpl instance about configuration changes. It may have initiated this
5889 // update to make sure that resources are updated before updating itself.
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005890 if (viewRoot != null) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005891 viewRoot.updateConfiguration(displayId);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005892 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07005893 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005894 }
5895
Jeff Hao1b012d32014-08-20 10:35:34 -07005896 final void handleProfilerControl(boolean start, ProfilerInfo profilerInfo, int profileType) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005897 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005898 try {
Romain Guy7eabe552011-07-21 14:56:34 -07005899 switch (profileType) {
Jeff Hao1b012d32014-08-20 10:35:34 -07005900 default:
5901 mProfiler.setProfiler(profilerInfo);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005902 mProfiler.startProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07005903 break;
5904 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005905 } catch (RuntimeException e) {
Jeff Hao1b012d32014-08-20 10:35:34 -07005906 Slog.w(TAG, "Profiling failed on path " + profilerInfo.profileFile
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005907 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07005908 } finally {
Andreas Gampe2b073a02017-06-22 17:28:57 -07005909 profilerInfo.closeFd();
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005910 }
5911 } else {
Romain Guy7eabe552011-07-21 14:56:34 -07005912 switch (profileType) {
Romain Guy7eabe552011-07-21 14:56:34 -07005913 default:
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005914 mProfiler.stopProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07005915 break;
Romain Guy7eabe552011-07-21 14:56:34 -07005916 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005917 }
5918 }
Bob Leee5408332009-09-04 18:31:17 -07005919
Andreas Gampe4c79fea2016-01-28 20:11:41 -08005920 /**
5921 * Public entrypoint to stop profiling. This is required to end profiling when the app crashes,
5922 * so that profiler data won't be lost.
5923 *
5924 * @hide
5925 */
5926 public void stopProfiling() {
Amith Yamasanib1684432017-01-26 14:57:20 -08005927 if (mProfiler != null) {
5928 mProfiler.stopProfiling();
5929 }
Andreas Gampe4c79fea2016-01-28 20:11:41 -08005930 }
5931
Christopher Ferris8d652f82017-04-11 16:29:18 -07005932 static void handleDumpHeap(DumpHeapData dhd) {
Makoto Onuki4556b7b2017-07-07 14:58:58 -07005933 if (dhd.runGc) {
5934 System.gc();
5935 System.runFinalization();
5936 System.gc();
5937 }
Kweku Adams4af1b502019-05-23 16:23:48 -07005938 try (ParcelFileDescriptor fd = dhd.fd) {
5939 if (dhd.managed) {
5940 Debug.dumpHprofData(dhd.path, fd.getFileDescriptor());
5941 } else if (dhd.mallocInfo) {
5942 Debug.dumpNativeMallocInfo(fd.getFileDescriptor());
5943 } else {
5944 Debug.dumpNativeHeap(fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07005945 }
Kweku Adams4af1b502019-05-23 16:23:48 -07005946 } catch (IOException e) {
5947 if (dhd.managed) {
5948 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
5949 + " -- can the process access this path?", e);
5950 } else {
5951 Slog.w(TAG, "Failed to dump heap", e);
5952 }
5953 } catch (RuntimeException e) {
5954 // This should no longer happening now that we're copying the file descriptor.
5955 Slog.wtf(TAG, "Heap dumper threw a runtime exception", e);
Andy McFadden824c5102010-07-09 16:26:57 -07005956 }
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005957 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005958 ActivityManager.getService().dumpHeapFinished(dhd.path);
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005959 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005960 throw e.rethrowFromSystemServer();
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005961 }
Makoto Onuki2c6657f2018-06-06 15:24:02 -07005962 if (dhd.finishCallback != null) {
5963 dhd.finishCallback.sendResult(null);
5964 }
Andy McFadden824c5102010-07-09 16:26:57 -07005965 }
5966
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005967 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005968 boolean hasPkgInfo = false;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005969 switch (cmd) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005970 case ApplicationThreadConstants.PACKAGE_REMOVED:
5971 case ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL:
Todd Kennedy39bfee52016-02-24 10:28:21 -08005972 {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005973 final boolean killApp = cmd == ApplicationThreadConstants.PACKAGE_REMOVED;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005974 if (packages == null) {
5975 break;
5976 }
5977 synchronized (mResourcesManager) {
5978 for (int i = packages.length - 1; i >= 0; i--) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005979 if (!hasPkgInfo) {
Todd Kennedy39bfee52016-02-24 10:28:21 -08005980 WeakReference<LoadedApk> ref = mPackages.get(packages[i]);
5981 if (ref != null && ref.get() != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005982 hasPkgInfo = true;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005983 } else {
5984 ref = mResourcePackages.get(packages[i]);
5985 if (ref != null && ref.get() != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005986 hasPkgInfo = true;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005987 }
5988 }
5989 }
5990 if (killApp) {
5991 mPackages.remove(packages[i]);
5992 mResourcePackages.remove(packages[i]);
5993 }
5994 }
5995 }
5996 break;
5997 }
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005998 case ApplicationThreadConstants.PACKAGE_REPLACED:
Todd Kennedy39bfee52016-02-24 10:28:21 -08005999 {
6000 if (packages == null) {
6001 break;
6002 }
Winson23863be2019-04-04 17:41:28 -07006003
6004 List<String> packagesHandled = new ArrayList<>();
6005
Todd Kennedy39bfee52016-02-24 10:28:21 -08006006 synchronized (mResourcesManager) {
6007 for (int i = packages.length - 1; i >= 0; i--) {
Winson23863be2019-04-04 17:41:28 -07006008 String packageName = packages[i];
6009 WeakReference<LoadedApk> ref = mPackages.get(packageName);
Todd Kennedy233a0b12018-01-29 20:30:24 +00006010 LoadedApk pkgInfo = ref != null ? ref.get() : null;
6011 if (pkgInfo != null) {
6012 hasPkgInfo = true;
mark_chen89764e32014-12-12 15:38:48 +08006013 } else {
Winson23863be2019-04-04 17:41:28 -07006014 ref = mResourcePackages.get(packageName);
Todd Kennedy233a0b12018-01-29 20:30:24 +00006015 pkgInfo = ref != null ? ref.get() : null;
6016 if (pkgInfo != null) {
6017 hasPkgInfo = true;
mark_chen89764e32014-12-12 15:38:48 +08006018 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07006019 }
Todd Kennedy39bfee52016-02-24 10:28:21 -08006020 // If the package is being replaced, yet it still has a valid
6021 // LoadedApk object, the package was updated with _DONT_KILL.
6022 // Adjust it's internal references to the application info and
6023 // resources.
Todd Kennedy233a0b12018-01-29 20:30:24 +00006024 if (pkgInfo != null) {
Winson23863be2019-04-04 17:41:28 -07006025 packagesHandled.add(packageName);
Todd Kennedy39bfee52016-02-24 10:28:21 -08006026 try {
Todd Kennedy39bfee52016-02-24 10:28:21 -08006027 final ApplicationInfo aInfo =
6028 sPackageManager.getApplicationInfo(
6029 packageName,
Svet Ganov6ce92392017-09-27 16:04:10 -07006030 PackageManager.GET_SHARED_LIBRARY_FILES,
Todd Kennedy39bfee52016-02-24 10:28:21 -08006031 UserHandle.myUserId());
6032
6033 if (mActivities.size() > 0) {
6034 for (ActivityClientRecord ar : mActivities.values()) {
6035 if (ar.activityInfo.applicationInfo.packageName
6036 .equals(packageName)) {
6037 ar.activityInfo.applicationInfo = aInfo;
Todd Kennedy233a0b12018-01-29 20:30:24 +00006038 ar.packageInfo = pkgInfo;
Todd Kennedy39bfee52016-02-24 10:28:21 -08006039 }
6040 }
6041 }
Winsond605e2d2019-02-11 16:05:51 -08006042
6043 final String[] oldResDirs = { pkgInfo.getResDir() };
6044
Todd Kennedyb9656a92018-05-02 10:59:45 +01006045 final ArrayList<String> oldPaths = new ArrayList<>();
6046 LoadedApk.makePaths(this, pkgInfo.getApplicationInfo(), oldPaths);
Todd Kennedy233a0b12018-01-29 20:30:24 +00006047 pkgInfo.updateApplicationInfo(aInfo, oldPaths);
Winsond605e2d2019-02-11 16:05:51 -08006048
6049 synchronized (mResourcesManager) {
6050 // Update affected Resources objects to use new ResourcesImpl
6051 mResourcesManager.applyNewResourceDirsLocked(aInfo, oldResDirs);
6052 }
Todd Kennedy39bfee52016-02-24 10:28:21 -08006053 } catch (RemoteException e) {
6054 }
6055 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07006056 }
6057 }
Winson23863be2019-04-04 17:41:28 -07006058
6059 try {
6060 getPackageManager().notifyPackagesReplacedReceived(
6061 packagesHandled.toArray(new String[0]));
6062 } catch (RemoteException ignored) {
6063 }
6064
Todd Kennedy39bfee52016-02-24 10:28:21 -08006065 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07006066 }
6067 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00006068 ApplicationPackageManager.handlePackageBroadcast(cmd, packages, hasPkgInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07006069 }
Tim Murraye1e6c662015-04-07 13:24:14 -07006070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006071 final void handleLowMemory() {
Dianne Hackborn73c14162012-09-19 15:45:06 -07006072 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(true, null);
Bob Leee5408332009-09-04 18:31:17 -07006073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006074 final int N = callbacks.size();
6075 for (int i=0; i<N; i++) {
6076 callbacks.get(i).onLowMemory();
6077 }
6078
Chris Tatece229052009-03-25 16:44:52 -07006079 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
6080 if (Process.myUid() != Process.SYSTEM_UID) {
6081 int sqliteReleased = SQLiteDatabase.releaseMemory();
6082 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
6083 }
Bob Leee5408332009-09-04 18:31:17 -07006084
Mike Reedcaf0df12009-04-27 14:32:05 -04006085 // Ask graphics to free up as much as possible (font/image caches)
6086 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006087
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07006088 // Ask text layout engine to free also as much as possible
6089 Canvas.freeTextLayoutCaches();
6090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006091 BinderInternal.forceGc("mem");
6092 }
6093
Jorim Jaggib29e3182018-04-30 18:51:56 +02006094 private void handleTrimMemory(int level) {
6095 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "trimMemory");
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07006096 if (DEBUG_MEMORY_TRIM) Slog.v(TAG, "Trimming memory to level: " + level);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07006097
Dianne Hackborn73c14162012-09-19 15:45:06 -07006098 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(true, null);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07006099
6100 final int N = callbacks.size();
Romain Guya998dff2012-03-23 18:58:36 -07006101 for (int i = 0; i < N; i++) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07006102 callbacks.get(i).onTrimMemory(level);
6103 }
Romain Guy19f86e82012-04-23 15:19:07 -07006104
John Reckf47a5942014-06-30 16:20:04 -07006105 WindowManagerGlobal.getInstance().trimMemory(level);
Jorim Jaggib29e3182018-04-30 18:51:56 +02006106 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Makoto Onuki0a9ee1a2019-06-19 08:58:02 -07006107
6108 if (SystemProperties.getInt("debug.am.run_gc_trim_level", Integer.MAX_VALUE) <= level) {
6109 unscheduleGcIdler();
6110 doGcIfNeeded("tm");
6111 }
6112 if (SystemProperties.getInt("debug.am.run_mallopt_trim_level", Integer.MAX_VALUE)
6113 <= level) {
6114 unschedulePurgeIdler();
6115 purgePendingResources();
6116 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006117 }
6118
Jesse Hall317fa5a2017-05-23 15:46:55 -07006119 private void setupGraphicsSupport(Context context) {
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006120 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setupGraphicsSupport");
Romain Guya9582652011-11-10 14:20:10 -08006121
Jesse Hall317fa5a2017-05-23 15:46:55 -07006122 // The system package doesn't have real data directories, so don't set up cache paths.
6123 if (!"android".equals(context.getPackageName())) {
6124 // This cache location probably points at credential-encrypted
6125 // storage which may not be accessible yet; assign it anyway instead
6126 // of pointing at device-encrypted storage.
6127 final File cacheDir = context.getCacheDir();
6128 if (cacheDir != null) {
6129 // Provide a usable directory for temporary files
6130 System.setProperty("java.io.tmpdir", cacheDir.getAbsolutePath());
6131 } else {
6132 Log.v(TAG, "Unable to initialize \"java.io.tmpdir\" property "
6133 + "due to missing cache directory");
Romain Guya9582652011-11-10 14:20:10 -08006134 }
Jesse Hall317fa5a2017-05-23 15:46:55 -07006135
6136 // Setup a location to store generated/compiled graphics code.
6137 final Context deviceContext = context.createDeviceProtectedStorageContext();
6138 final File codeCacheDir = deviceContext.getCodeCacheDir();
6139 if (codeCacheDir != null) {
6140 try {
6141 int uid = Process.myUid();
6142 String[] packages = getPackageManager().getPackagesForUid(uid);
6143 if (packages != null) {
John Reck8785ceb2018-10-29 16:45:58 -07006144 HardwareRenderer.setupDiskCache(codeCacheDir);
Romain Guycecbe072017-07-18 15:42:06 -07006145 RenderScriptCacheDir.setupDiskCache(codeCacheDir);
Jesse Hall317fa5a2017-05-23 15:46:55 -07006146 }
6147 } catch (RemoteException e) {
6148 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6149 throw e.rethrowFromSystemServer();
6150 }
6151 } else {
6152 Log.w(TAG, "Unable to use shader/script cache: missing code-cache directory");
6153 }
Romain Guya9582652011-11-10 14:20:10 -08006154 }
Jesse Hall317fa5a2017-05-23 15:46:55 -07006155
Cody Northropdeb43282018-10-04 16:04:05 -06006156 GraphicsEnvironment.getInstance().setup(context, mCoreSettings);
Jesse Hall317fa5a2017-05-23 15:46:55 -07006157 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborndde331c2012-08-03 14:01:57 -07006158 }
6159
6160 private void updateDefaultDensity() {
Alan Viverette2ac46f12016-02-04 16:58:14 -05006161 final int densityDpi = mCurDefaultDisplayDpi;
6162 if (!mDensityCompatMode
6163 && densityDpi != Configuration.DENSITY_DPI_UNDEFINED
6164 && densityDpi != DisplayMetrics.DENSITY_DEVICE) {
6165 DisplayMetrics.DENSITY_DEVICE = densityDpi;
6166 Bitmap.setDefaultDensity(densityDpi);
Dianne Hackborndde331c2012-08-03 14:01:57 -07006167 }
6168 }
6169
Todd Kennedye713efc2016-05-10 13:45:40 -07006170 /**
6171 * Returns the correct library directory for the current ABI.
6172 * <p>
6173 * If we're dealing with a multi-arch application that has both 32 and 64 bit shared
6174 * libraries, we might need to choose the secondary depending on what the current
6175 * runtime's instruction set is.
6176 */
6177 private String getInstrumentationLibrary(ApplicationInfo appInfo, InstrumentationInfo insInfo) {
Patrick Baumanneb595802018-04-17 09:49:55 -07006178 if (appInfo.primaryCpuAbi != null && appInfo.secondaryCpuAbi != null
6179 && appInfo.secondaryCpuAbi.equals(insInfo.secondaryCpuAbi)) {
Todd Kennedye713efc2016-05-10 13:45:40 -07006180 // Get the instruction set supported by the secondary ABI. In the presence
6181 // of a native bridge this might be different than the one secondary ABI used.
6182 String secondaryIsa =
6183 VMRuntime.getInstructionSet(appInfo.secondaryCpuAbi);
6184 final String secondaryDexCodeIsa =
6185 SystemProperties.get("ro.dalvik.vm.isa." + secondaryIsa);
6186 secondaryIsa = secondaryDexCodeIsa.isEmpty() ? secondaryIsa : secondaryDexCodeIsa;
6187
6188 final String runtimeIsa = VMRuntime.getRuntime().vmInstructionSet();
6189 if (runtimeIsa.equals(secondaryIsa)) {
6190 return insInfo.secondaryNativeLibraryDir;
6191 }
6192 }
6193 return insInfo.nativeLibraryDir;
6194 }
6195
Adam Lesinskib61e4052016-05-19 18:23:05 -07006196 /**
6197 * The LocaleList set for the app's resources may have been shuffled so that the preferred
6198 * Locale is at position 0. We must find the index of this preferred Locale in the
6199 * original LocaleList.
6200 */
6201 private void updateLocaleListFromAppContext(Context context, LocaleList newLocaleList) {
6202 final Locale bestLocale = context.getResources().getConfiguration().getLocales().get(0);
6203 final int newLocaleListSize = newLocaleList.size();
6204 for (int i = 0; i < newLocaleListSize; i++) {
6205 if (bestLocale.equals(newLocaleList.get(i))) {
6206 LocaleList.setDefault(newLocaleList, i);
6207 return;
6208 }
6209 }
Adam Lesinski27d30162016-05-25 16:45:14 -07006210
6211 // The app may have overridden the LocaleList with its own Locale
6212 // (not present in the available list). Push the chosen Locale
6213 // to the front of the list.
6214 LocaleList.setDefault(new LocaleList(bestLocale, newLocaleList));
Adam Lesinskib61e4052016-05-19 18:23:05 -07006215 }
6216
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006217 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07006218 private void handleBindApplication(AppBindData data) {
Calin Juravle8f5770d2016-04-12 14:12:04 +01006219 // Register the UI Thread as a sensitive thread to the runtime.
6220 VMRuntime.registerSensitiveThread();
Mathieu Chartier90aa9452019-03-29 13:49:35 -07006221 // In the case the stack depth property exists, pass it down to the runtime.
6222 String property = SystemProperties.get("debug.allocTracker.stackDepth");
6223 if (property.length() != 0) {
6224 VMDebug.setAllocTrackerStackDepth(Integer.parseInt(property));
6225 }
Man Caocfa78b22015-06-11 20:14:34 -07006226 if (data.trackAllocation) {
6227 DdmVmInternal.enableRecentAllocations(true);
6228 }
Dianne Hackbornd98885c2016-03-01 17:13:03 -08006229 // Note when this process has started.
6230 Process.setStartTimes(SystemClock.elapsedRealtime(), SystemClock.uptimeMillis());
6231
Mathew Inwood80652db2019-06-24 12:07:22 +01006232 AppCompatCallbacks.install(data.disabledCompatChanges);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006233 mBoundApplication = data;
6234 mConfiguration = new Configuration(data.config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07006235 mCompatConfiguration = new Configuration(data.config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006236
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07006237 mProfiler = new Profiler();
Andreas Gampeab8a63b2018-01-05 13:55:15 -08006238 String agent = null;
Jeff Hao1b012d32014-08-20 10:35:34 -07006239 if (data.initProfilerInfo != null) {
6240 mProfiler.profileFile = data.initProfilerInfo.profileFile;
6241 mProfiler.profileFd = data.initProfilerInfo.profileFd;
6242 mProfiler.samplingInterval = data.initProfilerInfo.samplingInterval;
6243 mProfiler.autoStopProfiler = data.initProfilerInfo.autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -08006244 mProfiler.streamingOutput = data.initProfilerInfo.streamingOutput;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08006245 if (data.initProfilerInfo.attachAgentDuringBind) {
6246 agent = data.initProfilerInfo.agent;
6247 }
Jeff Hao1b012d32014-08-20 10:35:34 -07006248 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07006249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08006251 Process.setArgV0(data.processName);
Siva Velusamyd693dfa2012-09-10 14:36:58 -07006252 android.ddm.DdmHandleAppName.setAppName(data.processName,
Chester Hsiehab720ee2019-11-12 12:01:54 -08006253 data.appInfo.packageName,
Siva Velusamyd693dfa2012-09-10 14:36:58 -07006254 UserHandle.myUserId());
Mathew Inwood37b6ca82018-05-02 10:42:23 +01006255 VMRuntime.setProcessPackageName(data.appInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006256
David Brazdil06f2e1292019-04-03 13:00:55 +01006257 // Pass data directory path to ART. This is used for caching information and
6258 // should be set before any application code is loaded.
6259 VMRuntime.setProcessDataDirectory(data.appInfo.dataDir);
6260
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07006261 if (mProfiler.profileFd != null) {
6262 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006263 }
6264
Joe Onoratod630f102011-03-17 18:42:26 -07006265 // If the app is Honeycomb MR1 or earlier, switch its AsyncTask
6266 // implementation to use the pool executor. Normally, we use the
6267 // serialized executor as the default. This has to happen in the
6268 // main thread so the main looper is set right.
Dianne Hackborn81e92762011-10-09 16:00:21 -07006269 if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
Joe Onoratod630f102011-03-17 18:42:26 -07006270 AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
6271 }
6272
Kweku Adams4be0b1a2019-04-25 16:16:34 -07006273 // Let the util.*Array classes maintain "undefined" for apps targeting Pie or earlier.
6274 UtilConfig.setThrowExceptionForUpperArrayOutOfBounds(
6275 data.appInfo.targetSdkVersion >= Build.VERSION_CODES.Q);
6276
Dianne Hackborn7895bc22014-09-05 15:09:03 -07006277 Message.updateCheckRecycle(data.appInfo.targetSdkVersion);
6278
Leon Scroggins III8290eab2018-03-19 10:51:44 -04006279 // Prior to P, internal calls to decode Bitmaps used BitmapFactory,
6280 // which may scale up to account for density. In P, we switched to
6281 // ImageDecoder, which skips the upscale to save memory. ImageDecoder
6282 // needs to still scale up in older apps, in case they rely on the
6283 // size of the Bitmap without considering its density.
6284 ImageDecoder.sApiLevel = data.appInfo.targetSdkVersion;
6285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 /*
6287 * Before spawning a new process, reset the time zone to be the system time zone.
6288 * This needs to be done because the system time zone could have changed after the
6289 * the spawning of this process. Without doing this this process would have the incorrect
6290 * system time zone.
6291 */
6292 TimeZone.setDefault(null);
6293
Adam Lesinskib61e4052016-05-19 18:23:05 -07006294 /*
6295 * Set the LocaleList. This may change once we create the App Context.
6296 */
6297 LocaleList.setDefault(data.config.getLocales());
6298
6299 synchronized (mResourcesManager) {
6300 /*
6301 * Update the system configuration since its preloaded and might not
6302 * reflect configuration changes. The configuration object passed
6303 * in AppBindData can be safely assumed to be up to date
6304 */
6305 mResourcesManager.applyConfigurationToResourcesLocked(data.config, data.compatInfo);
6306 mCurDefaultDisplayDpi = data.config.densityDpi;
6307
6308 // This calls mResourcesManager so keep it within the synchronized block.
6309 applyCompatConfiguration(mCurDefaultDisplayDpi);
6310 }
6311
Todd Kennedy233a0b12018-01-29 20:30:24 +00006312 data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313
Andreas Gampeab8a63b2018-01-05 13:55:15 -08006314 if (agent != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00006315 handleAttachAgent(agent, data.info);
Andreas Gampeab8a63b2018-01-05 13:55:15 -08006316 }
6317
Dianne Hackborndde331c2012-08-03 14:01:57 -07006318 /**
6319 * Switch this process to density compatibility mode if needed.
6320 */
6321 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
6322 == 0) {
6323 mDensityCompatMode = true;
6324 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
6325 }
6326 updateDefaultDensity();
6327
Neil Fullerc66ec402016-11-14 16:06:42 +00006328 final String use24HourSetting = mCoreSettings.getString(Settings.System.TIME_12_24);
6329 Boolean is24Hr = null;
6330 if (use24HourSetting != null) {
6331 is24Hr = "24".equals(use24HourSetting) ? Boolean.TRUE : Boolean.FALSE;
6332 }
6333 // null : use locale default for 12/24 hour formatting,
6334 // false : use 12 hour format,
6335 // true : use 24 hour format.
Narayan Kamathccb2a0862013-12-19 14:49:36 +00006336 DateFormat.set24HourTimePref(is24Hr);
6337
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08006338 updateDebugViewAttributeState();
Jon Miranda836c0a82014-08-11 12:32:26 -07006339
Jeff Sharkey89182982017-11-01 19:02:56 -06006340 StrictMode.initThreadDefaults(data.appInfo);
6341 StrictMode.initVmDefaults(data.appInfo);
Jeff Sharkey344744b2016-01-28 19:03:30 -07006342
Sudheer Shankacc6418f2016-10-13 12:03:44 -07006343 if (data.debugMode != ApplicationThreadConstants.DEBUG_OFF) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 // XXX should have option to change the port.
6345 Debug.changeDebugPort(8100);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07006346 if (data.debugMode == ApplicationThreadConstants.DEBUG_WAIT) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00006347 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006348 + " is waiting for the debugger on port 8100...");
6349
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006350 IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351 try {
6352 mgr.showWaitingForDebugger(mAppThread, true);
6353 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006354 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006355 }
6356
6357 Debug.waitForDebugger();
6358
6359 try {
6360 mgr.showWaitingForDebugger(mAppThread, false);
6361 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006362 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 }
6364
6365 } else {
Todd Kennedy233a0b12018-01-29 20:30:24 +00006366 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 + " can be debugged on port 8100...");
6368 }
6369 }
6370
Chris Craikce030282018-10-16 14:33:11 -07006371 // Allow binder tracing, and application-generated systrace messages if we're profileable.
6372 boolean isAppProfileable = data.appInfo.isProfileableByShell();
6373 Trace.setAppTracingAllowed(isAppProfileable);
6374 if (isAppProfileable && data.enableBinderTracking) {
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04006375 Binder.enableTracing();
6376 }
Jamie Gennisf9c7d6b2013-03-25 14:18:25 -07006377
Ryan Savitskicfdc1512018-12-14 16:20:52 +00006378 // Initialize heap profiling.
6379 if (isAppProfileable || Build.IS_DEBUGGABLE) {
6380 nInitZygoteChildHeapProfiling();
6381 }
6382
Chris Craikce030282018-10-16 14:33:11 -07006383 // Allow renderer debugging features if we're debuggable.
6384 boolean isAppDebuggable = (data.appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
John Reck8785ceb2018-10-29 16:45:58 -07006385 HardwareRenderer.setDebuggingEnabled(isAppDebuggable || Build.IS_DEBUGGABLE);
6386 HardwareRenderer.setPackageName(data.appInfo.packageName);
Chris Craikce030282018-10-16 14:33:11 -07006387
Robert Greenwalt434203a2010-10-11 16:00:27 -07006388 /**
6389 * Initialize the default http proxy in this process for the reasons we set the time zone.
6390 */
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006391 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Setup proxies");
Alan Viverettebe64eae2015-09-03 14:56:04 -04006392 final IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08006393 if (b != null) {
6394 // In pre-boot mode (doing initial launch to collect password), not
6395 // all system is up. This includes the connectivity service, so don't
6396 // crash if we can't get it.
Alan Viverettebe64eae2015-09-03 14:56:04 -04006397 final IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08006398 try {
Irina Dumitrescu18622d32018-12-05 16:19:47 +00006399 Proxy.setHttpProxySystemProperty(service.getProxyForNetwork(null));
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006400 } catch (RemoteException e) {
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006401 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006402 throw e.rethrowFromSystemServer();
6403 }
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08006404 }
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006405 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Robert Greenwalt434203a2010-10-11 16:00:27 -07006406
Alan Viverette2107d692015-09-03 14:55:27 -04006407 // Instrumentation info affects the class loader, so load it before
6408 // setting up the app context.
6409 final InstrumentationInfo ii;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006410 if (data.instrumentationName != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 try {
Todd Kennedy8f135982019-07-02 07:35:15 -07006412 ii = new ApplicationPackageManager(
6413 null, getPackageManager(), getPermissionManager())
Alan Viverette2107d692015-09-03 14:55:27 -04006414 .getInstrumentationInfo(data.instrumentationName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006415 } catch (PackageManager.NameNotFoundException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 throw new RuntimeException(
Alan Viverette2107d692015-09-03 14:55:27 -04006417 "Unable to find instrumentation info for: " + data.instrumentationName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006418 }
6419
Patrick Baumanneb595802018-04-17 09:49:55 -07006420 // Warn of potential ABI mismatches.
6421 if (!Objects.equals(data.appInfo.primaryCpuAbi, ii.primaryCpuAbi)
6422 || !Objects.equals(data.appInfo.secondaryCpuAbi, ii.secondaryCpuAbi)) {
6423 Slog.w(TAG, "Package uses different ABI(s) than its instrumentation: "
6424 + "package[" + data.appInfo.packageName + "]: "
6425 + data.appInfo.primaryCpuAbi + ", " + data.appInfo.secondaryCpuAbi
6426 + " instrumentation[" + ii.packageName + "]: "
6427 + ii.primaryCpuAbi + ", " + ii.secondaryCpuAbi);
6428 }
6429
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07006430 mInstrumentationPackageName = ii.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006431 mInstrumentationAppDir = ii.sourceDir;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07006432 mInstrumentationSplitAppDirs = ii.splitSourceDirs;
Todd Kennedye713efc2016-05-10 13:45:40 -07006433 mInstrumentationLibDir = getInstrumentationLibrary(data.appInfo, ii);
Todd Kennedy233a0b12018-01-29 20:30:24 +00006434 mInstrumentedAppDir = data.info.getAppDir();
6435 mInstrumentedSplitAppDirs = data.info.getSplitAppDirs();
6436 mInstrumentedLibDir = data.info.getLibDir();
Alan Viverette2107d692015-09-03 14:55:27 -04006437 } else {
6438 ii = null;
6439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006440
Todd Kennedy233a0b12018-01-29 20:30:24 +00006441 final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
Adam Lesinskib61e4052016-05-19 18:23:05 -07006442 updateLocaleListFromAppContext(appContext,
6443 mResourcesManager.getConfiguration().getLocales());
Seigo Nonakac14dd782016-03-30 23:09:16 +09006444
Jesse Hall317fa5a2017-05-23 15:46:55 -07006445 if (!Process.isIsolated()) {
Jeff Sharkey89182982017-11-01 19:02:56 -06006446 final int oldMask = StrictMode.allowThreadDiskWritesMask();
6447 try {
6448 setupGraphicsSupport(appContext);
6449 } finally {
6450 StrictMode.setThreadPolicyMask(oldMask);
6451 }
John Reck56428472018-03-16 17:27:17 -07006452 } else {
John Reck8785ceb2018-10-29 16:45:58 -07006453 HardwareRenderer.setIsolatedProcess(true);
Michael Lentine2ba303f2016-02-01 20:44:34 -06006454 }
Michael Lentine03d8f7682016-01-31 15:37:11 -06006455
Chad Brubaker78d47122015-11-17 22:26:58 -08006456 // Install the Network Security Config Provider. This must happen before the application
6457 // code is loaded to prevent issues with instances of TLS objects being created before
6458 // the provider is installed.
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006459 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "NetworkSecurityConfigProvider.install");
Chad Brubaker276ee962016-06-08 12:57:46 -07006460 NetworkSecurityConfigProvider.install(appContext);
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006461 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Chad Brubaker78d47122015-11-17 22:26:58 -08006462
Alan Viverette2107d692015-09-03 14:55:27 -04006463 // Continue loading instrumentation.
6464 if (ii != null) {
Dianne Hackbornf4ef6eb2017-12-07 13:57:21 -08006465 ApplicationInfo instrApp;
6466 try {
6467 instrApp = getPackageManager().getApplicationInfo(ii.packageName, 0,
6468 UserHandle.myUserId());
6469 } catch (RemoteException e) {
6470 instrApp = null;
6471 }
6472 if (instrApp == null) {
6473 instrApp = new ApplicationInfo();
6474 }
Jeff Sharkey15447792015-11-05 16:18:51 -08006475 ii.copyTo(instrApp);
Fyodor Kupolovaf38b8e2015-12-02 16:16:07 -08006476 instrApp.initForUser(UserHandle.myUserId());
Todd Kennedy233a0b12018-01-29 20:30:24 +00006477 final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07006478 appContext.getClassLoader(), false, true, false);
Makoto Onuki4becc352019-01-30 13:30:41 -08006479
6480 // The test context's op package name == the target app's op package name, because
6481 // the app ops manager checks the op package name against the real calling UID,
6482 // which is what the target package name is associated with.
6483 final ContextImpl instrContext = ContextImpl.createAppContext(this, pi,
6484 appContext.getOpPackageName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006485
6486 try {
Alan Viverettebe64eae2015-09-03 14:56:04 -04006487 final ClassLoader cl = instrContext.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04006488 mInstrumentation = (Instrumentation)
6489 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006490 } catch (Exception e) {
6491 throw new RuntimeException(
6492 "Unable to instantiate instrumentation "
6493 + data.instrumentationName + ": " + e.toString(), e);
6494 }
6495
Alan Viverettebe64eae2015-09-03 14:56:04 -04006496 final ComponentName component = new ComponentName(ii.packageName, ii.name);
6497 mInstrumentation.init(this, instrContext, appContext, component,
6498 data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006499
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07006500 if (mProfiler.profileFile != null && !ii.handleProfiling
6501 && mProfiler.profileFd == null) {
6502 mProfiler.handlingProfiling = true;
Alan Viverettebe64eae2015-09-03 14:56:04 -04006503 final File file = new File(mProfiler.profileFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006504 file.getParentFile().mkdirs();
6505 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
6506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006507 } else {
6508 mInstrumentation = new Instrumentation();
Jason Monka80bfb52017-11-16 17:15:37 -05006509 mInstrumentation.basicInit(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006510 }
6511
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08006512 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
Dianne Hackbornde398512011-01-18 18:45:21 -08006513 dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
Mathieu Chartier24cee072015-01-08 14:42:20 -08006514 } else {
6515 // Small heap, clamp to the current growth limit and let the heap release
6516 // pages after the growth limit to the non growth limit capacity. b/18387825
6517 dalvik.system.VMRuntime.getRuntime().clampGrowthLimit();
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08006518 }
6519
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006520 // Allow disk access during application and provider setup. This could
Jeff Sharkey7c501672012-02-28 12:08:37 -08006521 // block processing ordered broadcasts, but later processing would
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006522 // probably end up doing the same disk access.
Kurt Nelson5e154362017-06-29 17:20:56 -07006523 Application app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08006524 final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
Kurt Nelson571c3f62017-07-10 11:09:04 -07006525 final StrictMode.ThreadPolicy writesAllowedPolicy = StrictMode.getThreadPolicy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006526 try {
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006527 // If the app is being launched for full backup or restore, bring it up in
6528 // a restricted environment with the base application class.
Todd Kennedy233a0b12018-01-29 20:30:24 +00006529 app = data.info.makeApplication(data.restrictedBackupMode, null);
Svetoslav Ganov24c90452017-12-27 15:17:14 -08006530
6531 // Propagate autofill compat state
Felipe Lemea4f39cd2019-02-19 15:08:59 -08006532 app.setAutofillOptions(data.autofillOptions);
Svetoslav Ganov24c90452017-12-27 15:17:14 -08006533
Felipe Leme326f15a2019-02-19 09:42:24 -08006534 // Propagate Content Capture options
6535 app.setContentCaptureOptions(data.contentCaptureOptions);
6536
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006537 mInitialApplication = app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08006538
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006539 // don't bring up providers in restricted mode; they may depend on the
6540 // app's custom Application class
6541 if (!data.restrictedBackupMode) {
Jeff Sharkey3e195892016-03-05 19:48:59 -07006542 if (!ArrayUtils.isEmpty(data.providers)) {
6543 installContentProviders(app, data.providers);
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006544 }
6545 }
6546
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006547 // Do this after providers, since instrumentation tests generally start their
6548 // test thread at this point, and we don't want that racing.
6549 try {
6550 mInstrumentation.onCreate(data.instrumentationArgs);
6551 }
6552 catch (Exception e) {
6553 throw new RuntimeException(
6554 "Exception thrown in onCreate() of "
6555 + data.instrumentationName + ": " + e.toString(), e);
6556 }
Kurt Nelson571c3f62017-07-10 11:09:04 -07006557 try {
6558 mInstrumentation.callApplicationOnCreate(app);
6559 } catch (Exception e) {
6560 if (!mInstrumentation.onException(app, e)) {
6561 throw new RuntimeException(
6562 "Unable to create application " + app.getClass().getName()
6563 + ": " + e.toString(), e);
6564 }
6565 }
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006566 } finally {
Kurt Nelson571c3f62017-07-10 11:09:04 -07006567 // If the app targets < O-MR1, or doesn't change the thread policy
6568 // during startup, clobber the policy to maintain behavior of b/36951662
Jeff Sharkeyaa1a9112018-04-10 15:18:12 -06006569 if (data.appInfo.targetSdkVersion < Build.VERSION_CODES.O_MR1
Kurt Nelson571c3f62017-07-10 11:09:04 -07006570 || StrictMode.getThreadPolicy().equals(writesAllowedPolicy)) {
6571 StrictMode.setThreadPolicy(savedPolicy);
Kurt Nelson5e154362017-06-29 17:20:56 -07006572 }
6573 }
6574
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00006575 // Preload fonts resources
Seigo Nonaka54084b62017-04-24 14:46:23 -07006576 FontsContract.setApplicationContextForResources(appContext);
Torne (Richard Coles)85ecae52018-01-30 18:13:00 -05006577 if (!Process.isIsolated()) {
6578 try {
6579 final ApplicationInfo info =
6580 getPackageManager().getApplicationInfo(
6581 data.appInfo.packageName,
6582 PackageManager.GET_META_DATA /*flags*/,
6583 UserHandle.myUserId());
6584 if (info.metaData != null) {
6585 final int preloadedFontsResource = info.metaData.getInt(
6586 ApplicationInfo.METADATA_PRELOADED_FONTS, 0);
6587 if (preloadedFontsResource != 0) {
6588 data.info.getResources().preloadFonts(preloadedFontsResource);
6589 }
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00006590 }
Torne (Richard Coles)85ecae52018-01-30 18:13:00 -05006591 } catch (RemoteException e) {
6592 throw e.rethrowFromSystemServer();
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00006593 }
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00006594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006595 }
6596
6597 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006598 IActivityManager am = ActivityManager.getService();
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07006599 if (mProfiler.profileFile != null && mProfiler.handlingProfiling
6600 && mProfiler.profileFd == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006601 Debug.stopMethodTracing();
6602 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006603 //Slog.i(TAG, "am: " + ActivityManager.getService()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006604 // + ", app thr: " + mAppThread);
6605 try {
6606 am.finishInstrumentation(mAppThread, resultCode, results);
6607 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006608 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006609 }
6610 }
6611
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006612 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07006613 private void installContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614 Context context, List<ProviderInfo> providers) {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006615 final ArrayList<ContentProviderHolder> results = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006616
Romain Guya998dff2012-03-23 18:58:36 -07006617 for (ProviderInfo cpi : providers) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08006618 if (DEBUG_PROVIDER) {
6619 StringBuilder buf = new StringBuilder(128);
6620 buf.append("Pub ");
6621 buf.append(cpi.authority);
6622 buf.append(": ");
6623 buf.append(cpi.name);
6624 Log.i(TAG, buf.toString());
6625 }
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006626 ContentProviderHolder cph = installProvider(context, null, cpi,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006627 false /*noisy*/, true /*noReleaseNeeded*/, true /*stable*/);
6628 if (cph != null) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006629 cph.noReleaseNeeded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006630 results.add(cph);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006631 }
6632 }
6633
6634 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006635 ActivityManager.getService().publishContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006636 getApplicationThread(), results);
6637 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006638 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006639 }
6640 }
6641
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006642 @UnsupportedAppUsage
Jeff Sharkey6d515712012-09-20 16:06:08 -07006643 public final IContentProvider acquireProvider(
6644 Context c, String auth, int userId, boolean stable) {
Wale Ogunwale1d646122015-04-24 14:45:14 -07006645 final IContentProvider provider = acquireExistingProvider(c, auth, userId, stable);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006646 if (provider != null) {
6647 return provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006648 }
6649
Wale Ogunwale1d646122015-04-24 14:45:14 -07006650 // There is a possible race here. Another thread may try to acquire
6651 // the same provider at the same time. When this happens, we want to ensure
6652 // that the first one wins.
6653 // Note that we cannot hold the lock while acquiring and installing the
6654 // provider since it might take a long time to run and it could also potentially
6655 // be re-entrant in the case where the provider is in the same process.
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006656 ContentProviderHolder holder = null;
Wale Ogunwale1d646122015-04-24 14:45:14 -07006657 try {
Makoto Onukib6c79ea2018-05-31 11:03:56 -07006658 synchronized (getGetProviderLock(auth, userId)) {
6659 holder = ActivityManager.getService().getContentProvider(
Dianne Hackborn24bbe582018-12-17 11:58:31 -08006660 getApplicationThread(), c.getOpPackageName(), auth, userId, stable);
Makoto Onukib6c79ea2018-05-31 11:03:56 -07006661 }
Wale Ogunwale1d646122015-04-24 14:45:14 -07006662 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006663 throw ex.rethrowFromSystemServer();
Wale Ogunwale67fe0a42015-04-24 14:44:54 -07006664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006665 if (holder == null) {
Jeff Sharkey6d515712012-09-20 16:06:08 -07006666 Slog.e(TAG, "Failed to find provider info for " + auth);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 return null;
6668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006669
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006670 // Install provider will increment the reference count for us, and break
6671 // any ties in the race.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006672 holder = installProvider(c, holder, holder.info,
6673 true /*noisy*/, holder.noReleaseNeeded, stable);
6674 return holder.provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006675 }
6676
Makoto Onukib6c79ea2018-05-31 11:03:56 -07006677 private Object getGetProviderLock(String auth, int userId) {
6678 final ProviderKey key = new ProviderKey(auth, userId);
6679 synchronized (mGetProviderLocks) {
6680 Object lock = mGetProviderLocks.get(key);
6681 if (lock == null) {
6682 lock = key;
6683 mGetProviderLocks.put(key, lock);
6684 }
6685 return lock;
6686 }
6687 }
6688
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006689 private final void incProviderRefLocked(ProviderRefCount prc, boolean stable) {
6690 if (stable) {
6691 prc.stableCount += 1;
6692 if (prc.stableCount == 1) {
6693 // We are acquiring a new stable reference on the provider.
6694 int unstableDelta;
6695 if (prc.removePending) {
6696 // We have a pending remove operation, which is holding the
6697 // last unstable reference. At this point we are converting
6698 // that unstable reference to our new stable reference.
6699 unstableDelta = -1;
6700 // Cancel the removal of the provider.
6701 if (DEBUG_PROVIDER) {
6702 Slog.v(TAG, "incProviderRef: stable "
6703 + "snatched provider from the jaws of death");
6704 }
6705 prc.removePending = false;
Guobin Zhang9e3e52662013-03-21 13:57:11 +08006706 // There is a race! It fails to remove the message, which
6707 // will be handled in completeRemoveProvider().
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006708 mH.removeMessages(H.REMOVE_PROVIDER, prc);
6709 } else {
6710 unstableDelta = 0;
6711 }
6712 try {
6713 if (DEBUG_PROVIDER) {
6714 Slog.v(TAG, "incProviderRef Now stable - "
6715 + prc.holder.info.name + ": unstableDelta="
6716 + unstableDelta);
6717 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006718 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006719 prc.holder.connection, 1, unstableDelta);
6720 } catch (RemoteException e) {
6721 //do nothing content provider object is dead any way
6722 }
6723 }
6724 } else {
6725 prc.unstableCount += 1;
6726 if (prc.unstableCount == 1) {
6727 // We are acquiring a new unstable reference on the provider.
6728 if (prc.removePending) {
6729 // Oh look, we actually have a remove pending for the
6730 // provider, which is still holding the last unstable
6731 // reference. We just need to cancel that to take new
6732 // ownership of the reference.
6733 if (DEBUG_PROVIDER) {
6734 Slog.v(TAG, "incProviderRef: unstable "
6735 + "snatched provider from the jaws of death");
6736 }
6737 prc.removePending = false;
6738 mH.removeMessages(H.REMOVE_PROVIDER, prc);
6739 } else {
6740 // First unstable ref, increment our count in the
6741 // activity manager.
6742 try {
6743 if (DEBUG_PROVIDER) {
6744 Slog.v(TAG, "incProviderRef: Now unstable - "
6745 + prc.holder.info.name);
6746 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006747 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006748 prc.holder.connection, 0, 1);
6749 } catch (RemoteException e) {
6750 //do nothing content provider object is dead any way
6751 }
6752 }
6753 }
6754 }
6755 }
6756
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006757 @UnsupportedAppUsage
Jeff Sharkey6d515712012-09-20 16:06:08 -07006758 public final IContentProvider acquireExistingProvider(
6759 Context c, String auth, int userId, boolean stable) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006760 synchronized (mProviderMap) {
Wale Ogunwale1d646122015-04-24 14:45:14 -07006761 final ProviderKey key = new ProviderKey(auth, userId);
Jeff Sharkey6d515712012-09-20 16:06:08 -07006762 final ProviderClientRecord pr = mProviderMap.get(key);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006763 if (pr == null) {
6764 return null;
6765 }
6766
6767 IContentProvider provider = pr.mProvider;
6768 IBinder jBinder = provider.asBinder();
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006769 if (!jBinder.isBinderAlive()) {
6770 // The hosting process of the provider has died; we can't
6771 // use this one.
Wale Ogunwale1d646122015-04-24 14:45:14 -07006772 Log.i(TAG, "Acquiring provider " + auth + " for user " + userId
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006773 + ": existing object's process dead");
6774 handleUnstableProviderDiedLocked(jBinder, true);
6775 return null;
6776 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006777
6778 // Only increment the ref count if we have one. If we don't then the
6779 // provider is not reference counted and never needs to be released.
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006780 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006781 if (prc != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006782 incProviderRefLocked(prc, stable);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006783 }
6784 return provider;
6785 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006786 }
6787
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006788 @UnsupportedAppUsage
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006789 public final boolean releaseProvider(IContentProvider provider, boolean stable) {
6790 if (provider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006791 return false;
6792 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006794 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006795 synchronized (mProviderMap) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006796 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006797 if (prc == null) {
6798 // The provider has no ref count, no release is needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006799 return false;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006800 }
6801
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006802 boolean lastRef = false;
6803 if (stable) {
6804 if (prc.stableCount == 0) {
6805 if (DEBUG_PROVIDER) Slog.v(TAG,
6806 "releaseProvider: stable ref count already 0, how?");
6807 return false;
6808 }
6809 prc.stableCount -= 1;
6810 if (prc.stableCount == 0) {
6811 // What we do at this point depends on whether there are
6812 // any unstable refs left: if there are, we just tell the
6813 // activity manager to decrement its stable count; if there
6814 // aren't, we need to enqueue this provider to be removed,
6815 // and convert to holding a single unstable ref while
6816 // doing so.
6817 lastRef = prc.unstableCount == 0;
6818 try {
6819 if (DEBUG_PROVIDER) {
6820 Slog.v(TAG, "releaseProvider: No longer stable w/lastRef="
6821 + lastRef + " - " + prc.holder.info.name);
6822 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006823 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006824 prc.holder.connection, -1, lastRef ? 1 : 0);
6825 } catch (RemoteException e) {
6826 //do nothing content provider object is dead any way
6827 }
6828 }
6829 } else {
6830 if (prc.unstableCount == 0) {
6831 if (DEBUG_PROVIDER) Slog.v(TAG,
6832 "releaseProvider: unstable ref count already 0, how?");
6833 return false;
6834 }
6835 prc.unstableCount -= 1;
6836 if (prc.unstableCount == 0) {
6837 // If this is the last reference, we need to enqueue
6838 // this provider to be removed instead of telling the
6839 // activity manager to remove it at this point.
6840 lastRef = prc.stableCount == 0;
6841 if (!lastRef) {
6842 try {
6843 if (DEBUG_PROVIDER) {
6844 Slog.v(TAG, "releaseProvider: No longer unstable - "
6845 + prc.holder.info.name);
6846 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006847 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006848 prc.holder.connection, 0, -1);
6849 } catch (RemoteException e) {
6850 //do nothing content provider object is dead any way
6851 }
6852 }
6853 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006854 }
6855
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006856 if (lastRef) {
6857 if (!prc.removePending) {
6858 // Schedule the actual remove asynchronously, since we don't know the context
6859 // this will be called in.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006860 if (DEBUG_PROVIDER) {
6861 Slog.v(TAG, "releaseProvider: Enqueueing pending removal - "
6862 + prc.holder.info.name);
6863 }
6864 prc.removePending = true;
6865 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, prc);
Riddle Hsu4e8e3b02019-04-12 17:37:10 +08006866 mH.sendMessageDelayed(msg, CONTENT_PROVIDER_RETAIN_TIME);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006867 } else {
6868 Slog.w(TAG, "Duplicate remove pending of provider " + prc.holder.info.name);
6869 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006870 }
6871 return true;
6872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006873 }
6874
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006875 final void completeRemoveProvider(ProviderRefCount prc) {
6876 synchronized (mProviderMap) {
6877 if (!prc.removePending) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006878 // There was a race! Some other client managed to acquire
6879 // the provider before the removal was completed.
6880 // Abort the removal. We will do it later.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006881 if (DEBUG_PROVIDER) Slog.v(TAG, "completeRemoveProvider: lost the race, "
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006882 + "provider still in use");
6883 return;
6884 }
6885
Guobin Zhang9e3e52662013-03-21 13:57:11 +08006886 // More complicated race!! Some client managed to acquire the
6887 // provider and release it before the removal was completed.
6888 // Continue the removal, and abort the next remove message.
6889 prc.removePending = false;
6890
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006891 final IBinder jBinder = prc.holder.provider.asBinder();
6892 ProviderRefCount existingPrc = mProviderRefCountMap.get(jBinder);
6893 if (existingPrc == prc) {
6894 mProviderRefCountMap.remove(jBinder);
6895 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006896
Dianne Hackbornadd005c2013-07-17 18:43:12 -07006897 for (int i=mProviderMap.size()-1; i>=0; i--) {
6898 ProviderClientRecord pr = mProviderMap.valueAt(i);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006899 IBinder myBinder = pr.mProvider.asBinder();
6900 if (myBinder == jBinder) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07006901 mProviderMap.removeAt(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006902 }
6903 }
6904 }
6905
6906 try {
6907 if (DEBUG_PROVIDER) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006908 Slog.v(TAG, "removeProvider: Invoking ActivityManagerService."
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006909 + "removeContentProvider(" + prc.holder.info.name + ")");
6910 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006911 ActivityManager.getService().removeContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006912 prc.holder.connection, false);
6913 } catch (RemoteException e) {
6914 //do nothing content provider object is dead any way
6915 }
6916 }
6917
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006918 @UnsupportedAppUsage
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006919 final void handleUnstableProviderDied(IBinder provider, boolean fromClient) {
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006920 synchronized (mProviderMap) {
6921 handleUnstableProviderDiedLocked(provider, fromClient);
6922 }
6923 }
6924
6925 final void handleUnstableProviderDiedLocked(IBinder provider, boolean fromClient) {
6926 ProviderRefCount prc = mProviderRefCountMap.get(provider);
6927 if (prc != null) {
6928 if (DEBUG_PROVIDER) Slog.v(TAG, "Cleaning up dead provider "
6929 + provider + " " + prc.holder.info.name);
6930 mProviderRefCountMap.remove(provider);
You Kimbc74de62013-10-01 00:13:26 +09006931 for (int i=mProviderMap.size()-1; i>=0; i--) {
6932 ProviderClientRecord pr = mProviderMap.valueAt(i);
6933 if (pr != null && pr.mProvider.asBinder() == provider) {
6934 Slog.i(TAG, "Removing dead content provider:" + pr.mProvider.toString());
6935 mProviderMap.removeAt(i);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006936 }
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006937 }
You Kimbc74de62013-10-01 00:13:26 +09006938
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006939 if (fromClient) {
6940 // We found out about this due to execution in our client
6941 // code. Tell the activity manager about it now, to ensure
6942 // that the next time we go to do anything with the provider
6943 // it knows it is dead (so we don't race with its death
6944 // notification).
6945 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006946 ActivityManager.getService().unstableProviderDied(
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006947 prc.holder.connection);
6948 } catch (RemoteException e) {
6949 //do nothing content provider object is dead any way
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006950 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07006951 }
6952 }
6953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006954
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006955 final void appNotRespondingViaProvider(IBinder provider) {
6956 synchronized (mProviderMap) {
6957 ProviderRefCount prc = mProviderRefCountMap.get(provider);
6958 if (prc != null) {
6959 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006960 ActivityManager.getService()
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006961 .appNotRespondingViaProvider(prc.holder.connection);
6962 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006963 throw e.rethrowFromSystemServer();
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006964 }
6965 }
6966 }
6967 }
6968
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006969 private ProviderClientRecord installProviderAuthoritiesLocked(IContentProvider provider,
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006970 ContentProvider localProvider, ContentProviderHolder holder) {
Andreas Gampe18e99c12015-03-06 15:29:06 -08006971 final String auths[] = holder.info.authority.split(";");
Jeff Sharkey6d515712012-09-20 16:06:08 -07006972 final int userId = UserHandle.getUserId(holder.info.applicationInfo.uid);
6973
Jeff Sharkey0a17db12016-11-04 11:23:46 -06006974 if (provider != null) {
6975 // If this provider is hosted by the core OS and cannot be upgraded,
6976 // then I guess we're okay doing blocking calls to it.
6977 for (String auth : auths) {
6978 switch (auth) {
6979 case ContactsContract.AUTHORITY:
6980 case CallLog.AUTHORITY:
6981 case CallLog.SHADOW_AUTHORITY:
6982 case BlockedNumberContract.AUTHORITY:
6983 case CalendarContract.AUTHORITY:
6984 case Downloads.Impl.AUTHORITY:
Jeff Sharkeycb621622016-11-11 14:04:32 -07006985 case "telephony":
Jeff Sharkey0a17db12016-11-04 11:23:46 -06006986 Binder.allowBlocking(provider.asBinder());
6987 }
6988 }
6989 }
6990
Jeff Sharkey6d515712012-09-20 16:06:08 -07006991 final ProviderClientRecord pcr = new ProviderClientRecord(
6992 auths, provider, localProvider, holder);
6993 for (String auth : auths) {
6994 final ProviderKey key = new ProviderKey(auth, userId);
6995 final ProviderClientRecord existing = mProviderMap.get(key);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006996 if (existing != null) {
6997 Slog.w(TAG, "Content provider " + pcr.mHolder.info.name
Jeff Sharkey6d515712012-09-20 16:06:08 -07006998 + " already published as " + auth);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006999 } else {
Jeff Sharkey6d515712012-09-20 16:06:08 -07007000 mProviderMap.put(key, pcr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007001 }
7002 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007003 return pcr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007004 }
7005
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007006 /**
7007 * Installs the provider.
7008 *
7009 * Providers that are local to the process or that come from the system server
7010 * may be installed permanently which is indicated by setting noReleaseNeeded to true.
7011 * Other remote providers are reference counted. The initial reference count
7012 * for all reference counted providers is one. Providers that are not reference
7013 * counted do not have a reference count (at all).
7014 *
7015 * This method detects when a provider has already been installed. When this happens,
7016 * it increments the reference count of the existing provider (if appropriate)
7017 * and returns the existing provider. This can happen due to concurrent
7018 * attempts to acquire the same provider.
7019 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01007020 @UnsupportedAppUsage
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07007021 private ContentProviderHolder installProvider(Context context,
7022 ContentProviderHolder holder, ProviderInfo info,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007023 boolean noisy, boolean noReleaseNeeded, boolean stable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007024 ContentProvider localProvider = null;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007025 IContentProvider provider;
Dianne Hackborn5f48fca2012-05-30 11:06:31 -07007026 if (holder == null || holder.provider == null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007027 if (DEBUG_PROVIDER || noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07007028 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007029 + info.name);
7030 }
7031 Context c = null;
7032 ApplicationInfo ai = info.applicationInfo;
7033 if (context.getPackageName().equals(ai.packageName)) {
7034 c = context;
7035 } else if (mInitialApplication != null &&
7036 mInitialApplication.getPackageName().equals(ai.packageName)) {
7037 c = mInitialApplication;
7038 } else {
7039 try {
7040 c = context.createPackageContext(ai.packageName,
7041 Context.CONTEXT_INCLUDE_CODE);
7042 } catch (PackageManager.NameNotFoundException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07007043 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007044 }
7045 }
7046 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08007047 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007048 ai.packageName +
7049 " while loading content provider " +
7050 info.name);
7051 return null;
7052 }
Adam Lesinski4e862812016-11-21 16:02:24 -08007053
7054 if (info.splitName != null) {
7055 try {
7056 c = c.createContextForSplit(info.splitName);
7057 } catch (NameNotFoundException e) {
7058 throw new RuntimeException(e);
7059 }
7060 }
7061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007062 try {
7063 final java.lang.ClassLoader cl = c.getClassLoader();
Todd Kennedy233a0b12018-01-29 20:30:24 +00007064 LoadedApk packageInfo = peekPackageInfo(ai.packageName, true);
7065 if (packageInfo == null) {
Jason Monka80bfb52017-11-16 17:15:37 -05007066 // System startup case.
Todd Kennedy233a0b12018-01-29 20:30:24 +00007067 packageInfo = getSystemContext().mPackageInfo;
Jason Monka80bfb52017-11-16 17:15:37 -05007068 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00007069 localProvider = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05007070 .instantiateProvider(cl, info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007071 provider = localProvider.getIContentProvider();
7072 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08007073 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007074 info.name + " from sourceDir " +
7075 info.applicationInfo.sourceDir);
7076 return null;
7077 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007078 if (DEBUG_PROVIDER) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007079 TAG, "Instantiating local provider " + info.name);
7080 // XXX Need to create the correct context for this provider.
7081 localProvider.attachInfo(c, info);
7082 } catch (java.lang.Exception e) {
7083 if (!mInstrumentation.onException(null, e)) {
7084 throw new RuntimeException(
7085 "Unable to get provider " + info.name
7086 + ": " + e.toString(), e);
7087 }
7088 return null;
7089 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007090 } else {
7091 provider = holder.provider;
7092 if (DEBUG_PROVIDER) Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007093 + info.name);
7094 }
7095
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07007096 ContentProviderHolder retHolder;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007097
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007098 synchronized (mProviderMap) {
7099 if (DEBUG_PROVIDER) Slog.v(TAG, "Checking to add " + provider
7100 + " / " + info.name);
7101 IBinder jBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007102 if (localProvider != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007103 ComponentName cname = new ComponentName(info.packageName, info.name);
7104 ProviderClientRecord pr = mLocalProvidersByName.get(cname);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007105 if (pr != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007106 if (DEBUG_PROVIDER) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007107 Slog.v(TAG, "installProvider: lost the race, "
7108 + "using existing local provider");
7109 }
7110 provider = pr.mProvider;
7111 } else {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07007112 holder = new ContentProviderHolder(info);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007113 holder.provider = provider;
7114 holder.noReleaseNeeded = true;
7115 pr = installProviderAuthoritiesLocked(provider, localProvider, holder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007116 mLocalProviders.put(jBinder, pr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007117 mLocalProvidersByName.put(cname, pr);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007118 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007119 retHolder = pr.mHolder;
7120 } else {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007121 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
7122 if (prc != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007123 if (DEBUG_PROVIDER) {
7124 Slog.v(TAG, "installProvider: lost the race, updating ref count");
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007125 }
Wale Ogunwale1d646122015-04-24 14:45:14 -07007126 // We need to transfer our new reference to the existing
7127 // ref count, releasing the old one... but only if
7128 // release is needed (that is, it is not running in the
7129 // system process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007130 if (!noReleaseNeeded) {
7131 incProviderRefLocked(prc, stable);
Wale Ogunwale1d646122015-04-24 14:45:14 -07007132 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08007133 ActivityManager.getService().removeContentProvider(
Wale Ogunwale1d646122015-04-24 14:45:14 -07007134 holder.connection, stable);
7135 } catch (RemoteException e) {
7136 //do nothing content provider object is dead any way
7137 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007138 }
7139 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007140 ProviderClientRecord client = installProviderAuthoritiesLocked(
7141 provider, localProvider, holder);
7142 if (noReleaseNeeded) {
7143 prc = new ProviderRefCount(holder, client, 1000, 1000);
7144 } else {
7145 prc = stable
7146 ? new ProviderRefCount(holder, client, 1, 0)
7147 : new ProviderRefCount(holder, client, 0, 1);
7148 }
7149 mProviderRefCountMap.put(jBinder, prc);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08007150 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007151 retHolder = prc.holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007152 }
7153 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07007154 return retHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007155 }
7156
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04007157 private void handleRunIsolatedEntryPoint(String entryPoint, String[] entryPointArgs) {
7158 try {
7159 Method main = Class.forName(entryPoint).getMethod("main", String[].class);
7160 main.invoke(null, new Object[]{entryPointArgs});
7161 } catch (ReflectiveOperationException e) {
7162 throw new AndroidRuntimeException("runIsolatedEntryPoint failed", e);
7163 }
7164 // The process will be empty after this method returns; exit the VM now.
7165 System.exit(0);
7166 }
7167
Mathew Inwood61e8ae62018-08-14 14:17:44 +01007168 @UnsupportedAppUsage
Sudheer Shankaf6690102017-10-16 10:20:32 -07007169 private void attach(boolean system, long startSeq) {
Jeff Sharkey66a017b2013-01-17 18:18:22 -08007170 sCurrentActivityThread = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007171 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007172 if (!system) {
Siva Velusamyd693dfa2012-09-10 14:36:58 -07007173 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
7174 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007175 RuntimeInit.setApplicationObject(mAppThread.asBinder());
Sudheer Shankadc589ac2016-11-10 15:30:17 -08007176 final IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007177 try {
Sudheer Shankaf6690102017-10-16 10:20:32 -07007178 mgr.attachApplication(mAppThread, startSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007179 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07007180 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007181 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07007182 // Watch for getting close to heap limit.
7183 BinderInternal.addGcWatcher(new Runnable() {
7184 @Override public void run() {
7185 if (!mSomeActivitiesChanged) {
7186 return;
7187 }
7188 Runtime runtime = Runtime.getRuntime();
7189 long dalvikMax = runtime.maxMemory();
7190 long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
7191 if (dalvikUsed > ((3*dalvikMax)/4)) {
7192 if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
7193 + " total=" + (runtime.totalMemory()/1024)
7194 + " used=" + (dalvikUsed/1024));
7195 mSomeActivitiesChanged = false;
7196 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07007197 ActivityTaskManager.getService().releaseSomeActivities(mAppThread);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07007198 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07007199 throw e.rethrowFromSystemServer();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07007200 }
7201 }
7202 }
7203 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007204 } else {
7205 // Don't set application object here -- if the system crashes,
7206 // we can't display an alert, we just want to die die die.
Siva Velusamyd693dfa2012-09-10 14:36:58 -07007207 android.ddm.DdmHandleAppName.setAppName("system_process",
Dianne Hackborn89ad4562014-08-24 16:45:38 -07007208 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007209 try {
7210 mInstrumentation = new Instrumentation();
Jason Monka80bfb52017-11-16 17:15:37 -05007211 mInstrumentation.basicInit(this);
Jeff Browndefd4a62014-03-10 21:24:37 -07007212 ContextImpl context = ContextImpl.createAppContext(
Todd Kennedy233a0b12018-01-29 20:30:24 +00007213 this, getSystemContext().mPackageInfo);
7214 mInitialApplication = context.mPackageInfo.makeApplication(true, null);
Jeff Brown7fc8e352014-09-16 18:06:47 -07007215 mInitialApplication.onCreate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007216 } catch (Exception e) {
7217 throw new RuntimeException(
7218 "Unable to instantiate Application():" + e.toString(), e);
7219 }
7220 }
Geremy Condrab7faaf42012-09-19 18:07:42 -07007221
Andrii Kulian44607962017-03-16 11:06:24 -07007222 ViewRootImpl.ConfigChangedCallback configChangedCallback
7223 = (Configuration globalConfig) -> {
7224 synchronized (mResourcesManager) {
lumarkddc77fb2019-06-27 22:22:23 +08007225 // TODO (b/135719017): Temporary log for debugging IME service.
7226 if (Build.IS_DEBUGGABLE && mHasImeComponent) {
7227 Log.d(TAG, "ViewRootImpl.ConfigChangedCallback for IME, "
7228 + "config=" + globalConfig);
7229 }
7230
Andrii Kulian44607962017-03-16 11:06:24 -07007231 // We need to apply this change to the resources immediately, because upon returning
7232 // the view hierarchy will be informed about it.
7233 if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,
7234 null /* compat */)) {
7235 updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
7236 mResourcesManager.getConfiguration().getLocales());
Adam Lesinskib61e4052016-05-19 18:23:05 -07007237
Andrii Kulian44607962017-03-16 11:06:24 -07007238 // This actually changed the resources! Tell everyone about it.
7239 if (mPendingConfiguration == null
7240 || mPendingConfiguration.isOtherSeqNewer(globalConfig)) {
7241 mPendingConfiguration = globalConfig;
7242 sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08007243 }
7244 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08007245 }
Andrii Kulian44607962017-03-16 11:06:24 -07007246 };
7247 ViewRootImpl.addConfigCallback(configChangedCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007248 }
7249
Mathew Inwood61e8ae62018-08-14 14:17:44 +01007250 @UnsupportedAppUsage
Romain Guy5e9120d2012-01-30 12:17:22 -08007251 public static ActivityThread systemMain() {
Alan Viverette5e1565e2014-07-29 16:14:25 -07007252 // The system process on low-memory devices do not get to use hardware
7253 // accelerated drawing, since this can add too much overhead to the
7254 // process.
7255 if (!ActivityManager.isHighEndGfx()) {
John Reck51aaf902015-12-02 15:08:07 -08007256 ThreadedRenderer.disable(true);
John Reck73840ea2014-09-22 07:39:18 -07007257 } else {
John Reck51aaf902015-12-02 15:08:07 -08007258 ThreadedRenderer.enableForegroundTrimming();
Alan Viverette5e1565e2014-07-29 16:14:25 -07007259 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007260 ActivityThread thread = new ActivityThread();
Sudheer Shankaf6690102017-10-16 10:20:32 -07007261 thread.attach(true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007262 return thread;
7263 }
7264
Irina Dumitrescu34a27c42019-04-15 19:20:38 +01007265 public static void updateHttpProxy(@NonNull Context context) {
7266 final ConnectivityManager cm = ConnectivityManager.from(context);
7267 Proxy.setHttpProxySystemProperty(cm.getDefaultProxy());
7268 }
7269
Mathew Inwood61e8ae62018-08-14 14:17:44 +01007270 @UnsupportedAppUsage
Jeff Brown10e89712011-07-08 18:52:57 -07007271 public final void installSystemProviders(List<ProviderInfo> providers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007272 if (providers != null) {
Jeff Brown10e89712011-07-08 18:52:57 -07007273 installContentProviders(mInitialApplication, providers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007274 }
7275 }
7276
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08007277 public int getIntCoreSetting(String key, int defaultValue) {
Craig Mautner88c05892013-06-28 09:47:45 -07007278 synchronized (mResourcesManager) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08007279 if (mCoreSettings != null) {
7280 return mCoreSettings.getInt(key, defaultValue);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08007281 }
Craig Mautner88c05892013-06-28 09:47:45 -07007282 return defaultValue;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08007283 }
7284 }
7285
Shu Chen9d744e52020-01-22 14:28:08 +08007286 float getFloatCoreSetting(String key, float defaultValue) {
7287 synchronized (mResourcesManager) {
7288 if (mCoreSettings != null) {
7289 return mCoreSettings.getFloat(key, defaultValue);
7290 }
7291 return defaultValue;
7292 }
7293 }
7294
Jeff Sharkeybc2ae002018-07-31 10:45:37 -06007295 private static class AndroidOs extends ForwardingOs {
7296 /**
7297 * Install selective syscall interception. For example, this is used to
7298 * implement special filesystem paths that will be redirected to
7299 * {@link ContentResolver#openFileDescriptor(Uri, String)}.
7300 */
7301 public static void install() {
7302 // If feature is disabled, we don't need to install
7303 if (!DEPRECATE_DATA_COLUMNS) return;
7304
Jeff Sharkeybc2ae002018-07-31 10:45:37 -06007305 // Install interception and make sure it sticks!
7306 Os def = null;
7307 do {
7308 def = Os.getDefault();
7309 } while (!Os.compareAndSetDefault(def, new AndroidOs(def)));
7310 }
7311
7312 private AndroidOs(Os os) {
7313 super(os);
7314 }
7315
7316 private FileDescriptor openDeprecatedDataPath(String path, int mode) throws ErrnoException {
7317 final Uri uri = ContentResolver.translateDeprecatedDataPath(path);
7318 Log.v(TAG, "Redirecting " + path + " to " + uri);
7319
7320 final ContentResolver cr = currentActivityThread().getApplication()
7321 .getContentResolver();
7322 try {
7323 final FileDescriptor fd = new FileDescriptor();
7324 fd.setInt$(cr.openFileDescriptor(uri,
7325 FileUtils.translateModePosixToString(mode)).detachFd());
7326 return fd;
Jeff Sharkeyb50f51e2019-02-27 13:55:38 -07007327 } catch (SecurityException e) {
7328 throw new ErrnoException(e.getMessage(), OsConstants.EACCES);
Jeff Sharkeybc2ae002018-07-31 10:45:37 -06007329 } catch (FileNotFoundException e) {
7330 throw new ErrnoException(e.getMessage(), OsConstants.ENOENT);
7331 }
7332 }
7333
Jeff Sharkey416d4622019-02-27 22:14:16 -07007334 private void deleteDeprecatedDataPath(String path) throws ErrnoException {
7335 final Uri uri = ContentResolver.translateDeprecatedDataPath(path);
7336 Log.v(TAG, "Redirecting " + path + " to " + uri);
7337
7338 final ContentResolver cr = currentActivityThread().getApplication()
7339 .getContentResolver();
7340 try {
7341 if (cr.delete(uri, null, null) == 0) {
7342 throw new FileNotFoundException();
7343 }
7344 } catch (SecurityException e) {
7345 throw new ErrnoException(e.getMessage(), OsConstants.EACCES);
7346 } catch (FileNotFoundException e) {
7347 throw new ErrnoException(e.getMessage(), OsConstants.ENOENT);
7348 }
7349 }
7350
Jeff Sharkeybc2ae002018-07-31 10:45:37 -06007351 @Override
7352 public boolean access(String path, int mode) throws ErrnoException {
7353 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7354 // If we opened it okay, then access check succeeded
7355 IoUtils.closeQuietly(
7356 openDeprecatedDataPath(path, FileUtils.translateModeAccessToPosix(mode)));
7357 return true;
7358 } else {
7359 return super.access(path, mode);
7360 }
7361 }
7362
7363 @Override
7364 public FileDescriptor open(String path, int flags, int mode) throws ErrnoException {
7365 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7366 return openDeprecatedDataPath(path, mode);
7367 } else {
7368 return super.open(path, flags, mode);
7369 }
7370 }
7371
7372 @Override
7373 public StructStat stat(String path) throws ErrnoException {
7374 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7375 final FileDescriptor fd = openDeprecatedDataPath(path, OsConstants.O_RDONLY);
7376 try {
7377 return android.system.Os.fstat(fd);
7378 } finally {
7379 IoUtils.closeQuietly(fd);
7380 }
7381 } else {
7382 return super.stat(path);
Narayan Kamath7f062242015-04-08 13:24:13 +01007383 }
7384 }
Jeff Sharkey416d4622019-02-27 22:14:16 -07007385
7386 @Override
7387 public void unlink(String path) throws ErrnoException {
7388 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7389 deleteDeprecatedDataPath(path);
7390 } else {
7391 super.unlink(path);
7392 }
7393 }
7394
7395 @Override
7396 public void remove(String path) throws ErrnoException {
7397 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7398 deleteDeprecatedDataPath(path);
7399 } else {
7400 super.remove(path);
7401 }
7402 }
Zime59cb732019-12-12 10:54:45 +00007403
7404 @Override
7405 public void rename(String oldPath, String newPath) throws ErrnoException {
7406 try {
7407 super.rename(oldPath, newPath);
7408 } catch (ErrnoException e) {
7409 if (e.errno == OsConstants.EXDEV && oldPath.startsWith("/storage/")) {
7410 Log.v(TAG, "Recovering failed rename " + oldPath + " to " + newPath);
7411 try {
7412 Files.move(new File(oldPath).toPath(), new File(newPath).toPath());
7413 } catch (IOException e2) {
7414 throw e;
7415 }
7416 } else {
7417 throw e;
7418 }
7419 }
7420 }
Geremy Condrab7faaf42012-09-19 18:07:42 -07007421 }
7422
Romain Guy65b345f2011-07-27 18:51:50 -07007423 public static void main(String[] args) {
Narayan Kamathfbb32f62015-06-12 15:34:35 +01007424 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
Bob Leee5408332009-09-04 18:31:17 -07007425
Jeff Sharkeybc2ae002018-07-31 10:45:37 -06007426 // Install selective syscall interception
7427 AndroidOs.install();
7428
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08007429 // CloseGuard defaults to true and can be quite spammy. We
7430 // disable it here, but selectively enable it later (via
7431 // StrictMode) on debug builds, but using DropBox, not logs.
7432 CloseGuard.setEnabled(false);
7433
Andreas Gamped281b422016-07-08 03:50:27 +00007434 Environment.initForCurrentUser();
Jeff Sharkeyb049e212012-09-07 23:16:01 -07007435
Robin Lee3d076af2014-04-25 14:57:49 +01007436 // Make sure TrustedCertificateStore looks in the right place for CA certificates
7437 final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
7438 TrustedCertificateStore.setDefaultUserDirectory(configDir);
7439
Makoto Onuki6b0a7b82019-10-18 15:44:53 -07007440 // Call per-process mainline module initialization.
7441 initializeMainlineModules();
7442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007443 Process.setArgV0("<pre-initialized>");
7444
7445 Looper.prepareMainLooper();
7446
Sudheer Shankaf6690102017-10-16 10:20:32 -07007447 // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
7448 // It will be in the format "seq=114"
7449 long startSeq = 0;
7450 if (args != null) {
7451 for (int i = args.length - 1; i >= 0; --i) {
7452 if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
7453 startSeq = Long.parseLong(
7454 args[i].substring(PROC_START_SEQ_IDENT.length()));
7455 }
7456 }
7457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007458 ActivityThread thread = new ActivityThread();
Sudheer Shankaf6690102017-10-16 10:20:32 -07007459 thread.attach(false, startSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007460
Vairavan Srinivasan7335cfd2012-08-18 18:36:03 -07007461 if (sMainThreadHandler == null) {
7462 sMainThreadHandler = thread.getHandler();
7463 }
7464
Dianne Hackborn287952c2010-09-22 22:34:31 -07007465 if (false) {
7466 Looper.myLooper().setMessageLogging(new
7467 LogPrinter(Log.DEBUG, "ActivityThread"));
7468 }
7469
Narayan Kamathfbb32f62015-06-12 15:34:35 +01007470 // End of event ActivityThreadMain.
7471 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007472 Looper.loop();
7473
Jeff Brown10e89712011-07-08 18:52:57 -07007474 throw new RuntimeException("Main thread loop unexpectedly exited");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007475 }
Chris Craikfc294242016-12-13 18:10:46 -08007476
Makoto Onuki6b0a7b82019-10-18 15:44:53 -07007477 /**
7478 * Call various initializer APIs in mainline modules that need to be called when each process
7479 * starts.
7480 */
7481 public static void initializeMainlineModules() {
7482 TelephonyFrameworkInitializer.setTelephonyServiceManager(new TelephonyServiceManager());
Jeffrey Huangf58800b2020-01-23 13:22:10 -08007483 StatsFrameworkInitializer.setStatsServiceManager(new StatsServiceManager());
Makoto Onuki6b0a7b82019-10-18 15:44:53 -07007484 }
7485
Makoto Onuki0a9ee1a2019-06-19 08:58:02 -07007486 private void purgePendingResources() {
7487 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "purgePendingResources");
7488 nPurgePendingResources();
7489 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
7490 }
7491
Chris Craikfc294242016-12-13 18:10:46 -08007492 // ------------------ Regular JNI ------------------------
Tim Murray59f3dc12018-10-22 15:26:08 -07007493 private native void nPurgePendingResources();
Chris Craikfc294242016-12-13 18:10:46 -08007494 private native void nDumpGraphicsInfo(FileDescriptor fd);
Ryan Savitskicfdc1512018-12-14 16:20:52 +00007495 private native void nInitZygoteChildHeapProfiling();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007496}