blob: 08239a1e7ed9c55bd3bd972d851d661312f35a3a [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
Andrii Kulian88e05cb2017-12-05 17:21:10 -080019import static android.app.servertransaction.ActivityLifecycleItem.ON_CREATE;
20import static android.app.servertransaction.ActivityLifecycleItem.ON_DESTROY;
21import static android.app.servertransaction.ActivityLifecycleItem.ON_PAUSE;
22import static android.app.servertransaction.ActivityLifecycleItem.ON_RESUME;
23import static android.app.servertransaction.ActivityLifecycleItem.ON_START;
24import static android.app.servertransaction.ActivityLifecycleItem.ON_STOP;
25import static android.app.servertransaction.ActivityLifecycleItem.PRE_ON_CREATE;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -060026import static android.content.ContentResolver.DEPRECATE_DATA_COLUMNS;
27import static android.content.ContentResolver.DEPRECATE_DATA_PREFIX;
Andrii Kulianb047b8b2017-02-08 18:38:26 -080028import static android.view.Display.INVALID_DISPLAY;
29
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -070030import android.annotation.NonNull;
31import android.annotation.Nullable;
Mathew Inwood61e8ae62018-08-14 14:17:44 +010032import android.annotation.UnsupportedAppUsage;
Dianne Hackborn69c6adc2015-06-02 10:52:59 -070033import android.app.assist.AssistContent;
34import android.app.assist.AssistStructure;
Christopher Tate45281862010-03-05 15:46:30 -080035import android.app.backup.BackupAgent;
Andrii Kulian914aa7d2018-03-19 21:51:53 -070036import android.app.servertransaction.ActivityLifecycleItem;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080037import android.app.servertransaction.ActivityLifecycleItem.LifecycleState;
Andrii Kulian914aa7d2018-03-19 21:51:53 -070038import android.app.servertransaction.ActivityRelaunchItem;
Andrii Kulian446e8242017-10-26 15:17:29 -070039import android.app.servertransaction.ActivityResultItem;
40import android.app.servertransaction.ClientTransaction;
Riddle Hsud3062cb2018-06-30 02:06:42 +080041import android.app.servertransaction.ClientTransactionItem;
Andrii Kulian88e05cb2017-12-05 17:21:10 -080042import android.app.servertransaction.PendingTransactionActions;
43import android.app.servertransaction.PendingTransactionActions.StopInfo;
44import android.app.servertransaction.TransactionExecutor;
Andrii Kulian914aa7d2018-03-19 21:51:53 -070045import android.app.servertransaction.TransactionExecutorHelper;
Felipe Lemea4f39cd2019-02-19 15:08:59 -080046import android.content.AutofillOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.content.BroadcastReceiver;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070048import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.ComponentName;
Felipe Leme326f15a2019-02-19 09:42:24 -080050import android.content.ContentCaptureOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.content.ContentProvider;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -060052import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.content.Context;
54import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070055import android.content.IIntentReceiver;
Jesse Hall317fa5a2017-05-23 15:46:55 -070056import android.content.Intent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.content.pm.ActivityInfo;
58import android.content.pm.ApplicationInfo;
59import android.content.pm.IPackageManager;
60import android.content.pm.InstrumentationInfo;
Christopher Tate346acb12012-10-15 19:20:25 -070061import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.content.pm.PackageManager;
Sen Hubde75702010-05-28 01:54:03 -070063import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -070064import android.content.pm.ParceledListSlice;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.content.pm.ProviderInfo;
66import android.content.pm.ServiceInfo;
67import android.content.res.AssetManager;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -070068import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.content.res.Configuration;
70import android.content.res.Resources;
Alan Viverettee54d2452015-05-06 10:41:43 -070071import android.content.res.Resources.Theme;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.database.sqlite.SQLiteDatabase;
73import android.database.sqlite.SQLiteDebug;
Vasu Noric3849202010-03-09 10:47:25 -080074import android.database.sqlite.SQLiteDebug.DbStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.graphics.Bitmap;
76import android.graphics.Canvas;
John Reck8785ceb2018-10-29 16:45:58 -070077import android.graphics.HardwareRenderer;
Leon Scroggins III8290eab2018-03-19 10:51:44 -040078import android.graphics.ImageDecoder;
Jeff Brownbd6e1502012-08-28 03:27:37 -070079import android.hardware.display.DisplayManagerGlobal;
Paul Jensene0bef712014-12-10 15:12:18 -050080import android.net.ConnectivityManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070081import android.net.IConnectivityManager;
82import android.net.Proxy;
Jason Monk83520b92014-05-09 15:16:06 -040083import android.net.Uri;
Joe Onoratod630f102011-03-17 18:42:26 -070084import android.os.AsyncTask;
Amith Yamasani742a6712011-05-04 14:49:28 -070085import android.os.Binder;
Jeff Sharkey344744b2016-01-28 19:03:30 -070086import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.os.Bundle;
88import android.os.Debug;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070089import android.os.Environment;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -060090import android.os.FileUtils;
Jesse Hallb12249b2016-12-12 12:53:02 -080091import android.os.GraphicsEnvironment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.os.Handler;
Jeff Sharkey8439ac02017-12-12 17:26:23 -070093import android.os.HandlerExecutor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import android.os.IBinder;
Adam Lesinskib61e4052016-05-19 18:23:05 -070095import android.os.LocaleList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import android.os.Looper;
97import android.os.Message;
98import android.os.MessageQueue;
Dianne Hackbornfabb70b2014-11-11 12:22:36 -080099import android.os.Parcel;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700100import android.os.ParcelFileDescriptor;
Craig Mautnera0026042014-04-23 11:45:37 -0700101import android.os.PersistableBundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import android.os.Process;
Makoto Onuki2c6657f2018-06-06 15:24:02 -0700103import android.os.RemoteCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import android.os.RemoteException;
105import android.os.ServiceManager;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700106import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import android.os.SystemClock;
Jeff Brownefd43bd2012-09-21 17:02:35 -0700108import android.os.SystemProperties;
Dianne Hackborn1ded0b12012-04-26 14:14:50 -0700109import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700110import android.os.UserHandle;
Jeff Sharkey0a17db12016-11-04 11:23:46 -0600111import android.provider.BlockedNumberContract;
112import android.provider.CalendarContract;
113import android.provider.CallLog;
114import android.provider.ContactsContract;
115import android.provider.Downloads;
Seigo Nonaka54084b62017-04-24 14:46:23 -0700116import android.provider.FontsContract;
Narayan Kamathccb2a0862013-12-19 14:49:36 +0000117import android.provider.Settings;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700118import android.renderscript.RenderScriptCacheDir;
Chad Brubakerc72875b2016-04-27 16:35:11 -0700119import android.security.NetworkSecurityPolicy;
Chad Brubaker78d47122015-11-17 22:26:58 -0800120import android.security.net.config.NetworkSecurityConfigProvider;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -0600121import android.system.ErrnoException;
122import android.system.OsConstants;
123import android.system.StructStat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import android.util.AndroidRuntimeException;
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700125import android.util.ArrayMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126import android.util.DisplayMetrics;
127import android.util.EventLog;
128import android.util.Log;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700129import android.util.LogPrinter;
Andrii Kulianb372da62018-01-18 10:46:24 -0800130import android.util.MergedConfiguration;
Craig Mautnereb8abf72014-07-02 15:04:09 -0700131import android.util.Pair;
Jeff Brown6754ba22011-12-14 20:20:01 -0800132import android.util.PrintWriterPrinter;
Dianne Hackbornc9421ba2010-03-11 22:23:46 -0800133import android.util.Slog;
Annie Mengd5827872019-01-30 20:28:57 +0000134import android.util.SparseArray;
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -0700135import android.util.SparseIntArray;
Adam Powell14874662013-07-18 19:42:41 -0700136import android.util.SuperNotCalledException;
Kweku Adams598e9a22017-11-02 17:12:20 -0700137import android.util.proto.ProtoOutputStream;
Jorim Jaggib29e3182018-04-30 18:51:56 +0200138import android.view.Choreographer;
Adam Lesinski3ad1b482016-04-01 16:41:41 -0700139import android.view.ContextThemeWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140import android.view.Display;
John Reck51aaf902015-12-02 15:08:07 -0800141import android.view.ThreadedRenderer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142import android.view.View;
143import android.view.ViewDebug;
144import android.view.ViewManager;
Dianne Hackborn6dd005b2011-07-18 13:22:50 -0700145import android.view.ViewRootImpl;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146import android.view.Window;
147import android.view.WindowManager;
Jeff Brown98365d72012-08-19 20:30:52 -0700148import android.view.WindowManagerGlobal;
Richard Uhler2c036192016-09-14 09:48:31 +0100149import android.webkit.WebView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700151import com.android.internal.annotations.GuardedBy;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800152import com.android.internal.annotations.VisibleForTesting;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700153import com.android.internal.app.IVoiceInteractor;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800154import com.android.internal.content.ReferrerIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155import com.android.internal.os.BinderInternal;
156import com.android.internal.os.RuntimeInit;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700157import com.android.internal.os.SomeArgs;
Jeff Sharkey3e195892016-03-05 19:48:59 -0700158import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -0700159import com.android.internal.util.FastPrintWriter;
Jorim Jaggib29e3182018-04-30 18:51:56 +0200160import com.android.internal.util.function.pooled.PooledLambda;
Kenny Root12e75222013-04-23 22:34:24 -0700161import com.android.org.conscrypt.OpenSSLSocketImpl;
Robin Lee3d076af2014-04-25 14:57:49 +0100162import com.android.org.conscrypt.TrustedCertificateStore;
Yi Jin6c6e9ca2018-03-20 16:53:35 -0700163import com.android.server.am.MemInfoDumpProto;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700164
Jesse Hall317fa5a2017-05-23 15:46:55 -0700165import dalvik.system.CloseGuard;
166import dalvik.system.VMDebug;
167import dalvik.system.VMRuntime;
168
Jeff Sharkeybc2ae002018-07-31 10:45:37 -0600169import libcore.io.ForwardingOs;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700170import libcore.io.IoUtils;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -0600171import libcore.io.Os;
Jesse Hall317fa5a2017-05-23 15:46:55 -0700172import libcore.net.event.NetworkEventDispatcher;
173
174import org.apache.harmony.dalvik.ddmc.DdmVmInternal;
175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176import java.io.File;
177import java.io.FileDescriptor;
Jeff Sharkeybc2ae002018-07-31 10:45:37 -0600178import java.io.FileNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179import java.io.FileOutputStream;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -0700180import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181import java.io.PrintWriter;
182import java.lang.ref.WeakReference;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -0400183import java.lang.reflect.Method;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700184import java.net.InetAddress;
Jeff Sharkey416d4622019-02-27 22:14:16 -0700185import java.nio.file.Files;
Narayan Kamathccb2a0862013-12-19 14:49:36 +0000186import java.text.DateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187import java.util.ArrayList;
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -0600188import java.util.Arrays;
Riddle Hsud3062cb2018-06-30 02:06:42 +0800189import java.util.Collections;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190import java.util.List;
Adam Lesinskib61e4052016-05-19 18:23:05 -0700191import java.util.Locale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192import java.util.Map;
Kenny Roote6585b32013-12-13 12:00:26 -0800193import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194import java.util.TimeZone;
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700195import java.util.concurrent.Executor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700197final class RemoteServiceException extends AndroidRuntimeException {
198 public RemoteServiceException(String msg) {
199 super(msg);
200 }
201}
202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203/**
204 * This manages the execution of the main thread in an
205 * application process, scheduling and executing activities,
206 * broadcasts, and other operations on it as the activity
207 * manager requests.
208 *
209 * {@hide}
210 */
Andrii Kulian446e8242017-10-26 15:17:29 -0700211public final class ActivityThread extends ClientTransactionHandler {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700212 /** @hide */
213 public static final String TAG = "ActivityThread";
Jim Miller0b2a6d02010-07-13 18:01:29 -0700214 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
Joe Onorato43a17652011-04-06 19:22:23 -0700215 static final boolean localLOGV = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700216 static final boolean DEBUG_MESSAGES = false;
Dianne Hackborne829fef2010-10-26 17:44:01 -0700217 /** @hide */
218 public static final boolean DEBUG_BROADCAST = false;
Chris Tate8a7dc172009-03-24 20:11:42 -0700219 private static final boolean DEBUG_RESULTS = false;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700220 private static final boolean DEBUG_BACKUP = false;
Craig Mautner88c05892013-06-28 09:47:45 -0700221 public static final boolean DEBUG_CONFIGURATION = false;
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800222 private static final boolean DEBUG_SERVICE = false;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800223 public static final boolean DEBUG_MEMORY_TRIM = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700224 private static final boolean DEBUG_PROVIDER = false;
Andrii Kulianb372da62018-01-18 10:46:24 -0800225 public static final boolean DEBUG_ORDER = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228
Dianne Hackborn455625e2015-01-21 09:55:13 -0800229 /** Type for IActivityManager.serviceDoneExecuting: anonymous operation */
230 public static final int SERVICE_DONE_EXECUTING_ANON = 0;
231 /** Type for IActivityManager.serviceDoneExecuting: done with an onStart call */
232 public static final int SERVICE_DONE_EXECUTING_START = 1;
233 /** Type for IActivityManager.serviceDoneExecuting: done stopping (destroying) service */
234 public static final int SERVICE_DONE_EXECUTING_STOP = 2;
235
Filip Gruszczynskica664812015-12-04 12:43:36 -0800236 // Whether to invoke an activity callback after delivering new configuration.
237 private static final boolean REPORT_TO_ACTIVITY = true;
238
Sudheer Shanka84a48952017-03-08 18:19:01 -0800239 /**
240 * Denotes an invalid sequence number corresponding to a process state change.
241 */
242 public static final long INVALID_PROC_STATE_SEQ = -1;
243
Sudheer Shankaf6690102017-10-16 10:20:32 -0700244 /**
245 * Identifier for the sequence no. associated with this process start. It will be provided
246 * as one of the arguments when the process starts.
247 */
248 public static final String PROC_START_SEQ_IDENT = "seq=";
249
Sudheer Shanka84a48952017-03-08 18:19:01 -0800250 private final Object mNetworkPolicyLock = new Object();
251
252 /**
253 * Denotes the sequence number of the process state change for which the main thread needs
254 * to block until the network rules are updated for it.
255 *
256 * Value of {@link #INVALID_PROC_STATE_SEQ} indicates there is no need for blocking.
257 */
258 @GuardedBy("mNetworkPolicyLock")
259 private long mNetworkBlockSeq = INVALID_PROC_STATE_SEQ;
260
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100261 @UnsupportedAppUsage
Jeff Browndefd4a62014-03-10 21:24:37 -0700262 private ContextImpl mSystemContext;
Adam Lesinskia82b6262017-03-21 16:56:17 -0700263 private ContextImpl mSystemUiContext;
Bob Leee5408332009-09-04 18:31:17 -0700264
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100265 @UnsupportedAppUsage
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700266 static volatile IPackageManager sPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100268 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700269 final ApplicationThread mAppThread = new ApplicationThread();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100270 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700271 final Looper mLooper = Looper.myLooper();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100272 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700273 final H mH = new H();
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700274 final Executor mExecutor = new HandlerExecutor(mH);
Garfield Tan0443b372019-01-04 15:00:13 -0800275 /**
276 * Maps from activity token to local record of running activities in this process.
277 *
278 * This variable is readable if the code is running in activity thread or holding {@link
279 * #mResourcesManager}. It's only writable if the code is running in activity thread and holding
280 * {@link #mResourcesManager}.
281 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100282 @UnsupportedAppUsage
Dianne Hackborn782d4982015-07-08 17:36:37 -0700283 final ArrayMap<IBinder, ActivityClientRecord> mActivities = new ArrayMap<>();
Riddle Hsu66b74a82018-07-26 00:20:12 +0800284 /** The activities to be truly destroyed (not include relaunch). */
Riddle Hsud3062cb2018-06-30 02:06:42 +0800285 final Map<IBinder, ClientTransactionItem> mActivitiesToBeDestroyed =
286 Collections.synchronizedMap(new ArrayMap<IBinder, ClientTransactionItem>());
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700287 // List of new activities (via ActivityRecord.nextIdle) that should
288 // be reported when next we idle.
289 ActivityClientRecord mNewActivities = null;
290 // Number of activities that are currently visible on-screen.
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100291 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700292 int mNumVisibleActivities = 0;
Amith Yamasani4f128e42016-05-10 11:44:12 -0700293 ArrayList<WeakReference<AssistStructure>> mLastAssistStructures = new ArrayList<>();
294 private int mLastSessionId;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100295 @UnsupportedAppUsage
Dianne Hackborn782d4982015-07-08 17:36:37 -0700296 final ArrayMap<IBinder, Service> mServices = new ArrayMap<>();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100297 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700298 AppBindData mBoundApplication;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700299 Profiler mProfiler;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100300 @UnsupportedAppUsage
Dianne Hackborn908aecc2012-07-31 16:37:34 -0700301 int mCurDefaultDisplayDpi;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100302 @UnsupportedAppUsage
Dianne Hackborndde331c2012-08-03 14:01:57 -0700303 boolean mDensityCompatMode;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100304 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700305 Configuration mConfiguration;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700306 Configuration mCompatConfiguration;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100307 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700308 Application mInitialApplication;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100309 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700310 final ArrayList<Application> mAllApplications
311 = new ArrayList<Application>();
Annie Mengd5827872019-01-30 20:28:57 +0000312 /**
313 * Bookkeeping of instantiated backup agents indexed first by user id, then by package name.
314 * Indexing by user id supports parallel backups across users on system packages as they run in
315 * the same process with the same package name. Indexing by package name supports multiple
316 * distinct applications running in the same process.
317 */
318 private final SparseArray<ArrayMap<String, BackupAgent>> mBackupAgentsByUser =
319 new SparseArray<>();
Jeff Sharkey66a017b2013-01-17 18:18:22 -0800320 /** Reference to singleton {@link ActivityThread} */
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100321 @UnsupportedAppUsage
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700322 private static volatile ActivityThread sCurrentActivityThread;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100323 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700324 Instrumentation mInstrumentation;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700325 String mInstrumentationPackageName = null;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100326 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700327 String mInstrumentationAppDir = null;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700328 String[] mInstrumentationSplitAppDirs = null;
329 String mInstrumentationLibDir = null;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100330 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700331 String mInstrumentedAppDir = null;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -0700332 String[] mInstrumentedSplitAppDirs = null;
333 String mInstrumentedLibDir = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700334 boolean mSystemThread = false;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700335 boolean mSomeActivitiesChanged = false;
Chong Zhang4951f9d2016-06-23 13:15:08 -0700336 boolean mUpdatingSystemConfig = false;
David Brazdild960cc42018-01-31 07:59:17 +0000337 /* package */ boolean mHiddenApiWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100339 // These can be accessed by multiple threads; mResourcesManager is the lock.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700340 // XXX For now we keep around information about all packages we have
341 // seen, not removing entries from this map.
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800342 // NOTE: The activity and window managers need to call in to
Dianne Hackborn2f0b1752011-05-31 17:59:49 -0700343 // ActivityThread to do things like update resource configurations,
Dianne Hackborn1fbee792011-11-30 11:29:58 -0800344 // which means this lock gets held while the activity and window managers
345 // holds their own lock. Thus you MUST NEVER call back into the activity manager
346 // or window manager or anything that depends on them while holding this lock.
Jeff Sharkeyb9f36742015-04-08 21:02:14 -0700347 // These LoadedApk are only valid for the userId that we're running as.
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100348 @GuardedBy("mResourcesManager")
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100349 @UnsupportedAppUsage
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100350 final ArrayMap<String, WeakReference<LoadedApk>> mPackages = new ArrayMap<>();
351 @GuardedBy("mResourcesManager")
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100352 @UnsupportedAppUsage
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +0100353 final ArrayMap<String, WeakReference<LoadedApk>> mResourcePackages = new ArrayMap<>();
354 @GuardedBy("mResourcesManager")
355 final ArrayList<ActivityClientRecord> mRelaunchingActivities = new ArrayList<>();
356 @GuardedBy("mResourcesManager")
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100357 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700358 Configuration mPendingConfiguration = null;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800359 // An executor that performs multi-step transactions.
360 private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361
Mathew Inwood8c854f82018-09-14 12:35:36 +0100362 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Craig Mautner88c05892013-06-28 09:47:45 -0700363 private final ResourcesManager mResourcesManager;
364
Jeff Sharkey6d515712012-09-20 16:06:08 -0700365 private static final class ProviderKey {
366 final String authority;
367 final int userId;
368
369 public ProviderKey(String authority, int userId) {
370 this.authority = authority;
371 this.userId = userId;
372 }
373
374 @Override
375 public boolean equals(Object o) {
376 if (o instanceof ProviderKey) {
377 final ProviderKey other = (ProviderKey) o;
Kenny Roote6585b32013-12-13 12:00:26 -0800378 return Objects.equals(authority, other.authority) && userId == other.userId;
Jeff Sharkey6d515712012-09-20 16:06:08 -0700379 }
380 return false;
381 }
382
383 @Override
384 public int hashCode() {
385 return ((authority != null) ? authority.hashCode() : 0) ^ userId;
386 }
387 }
388
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700389 // The lock of mProviderMap protects the following variables.
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100390 @UnsupportedAppUsage
Wale Ogunwale1d646122015-04-24 14:45:14 -0700391 final ArrayMap<ProviderKey, ProviderClientRecord> mProviderMap
392 = new ArrayMap<ProviderKey, ProviderClientRecord>();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100393 @UnsupportedAppUsage
Wale Ogunwale1d646122015-04-24 14:45:14 -0700394 final ArrayMap<IBinder, ProviderRefCount> mProviderRefCountMap
395 = new ArrayMap<IBinder, ProviderRefCount>();
Mathew Inwood8c854f82018-09-14 12:35:36 +0100396 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Wale Ogunwale1d646122015-04-24 14:45:14 -0700397 final ArrayMap<IBinder, ProviderClientRecord> mLocalProviders
398 = new ArrayMap<IBinder, ProviderClientRecord>();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100399 @UnsupportedAppUsage
Wale Ogunwale1d646122015-04-24 14:45:14 -0700400 final ArrayMap<ComponentName, ProviderClientRecord> mLocalProvidersByName
401 = new ArrayMap<ComponentName, ProviderClientRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402
Makoto Onukib6c79ea2018-05-31 11:03:56 -0700403 // Mitigation for b/74523247: Used to serialize calls to AM.getContentProvider().
404 // Note we never removes items from this map but that's okay because there are only so many
405 // users and so many authorities.
406 // TODO Remove it once we move CPR.wait() from AMS to the client side.
407 @GuardedBy("mGetProviderLocks")
408 final ArrayMap<ProviderKey, Object> mGetProviderLocks = new ArrayMap<>();
409
Dianne Hackbornadd005c2013-07-17 18:43:12 -0700410 final ArrayMap<Activity, ArrayList<OnActivityPausedListener>> mOnPauseListeners
Wale Ogunwale1d646122015-04-24 14:45:14 -0700411 = new ArrayMap<Activity, ArrayList<OnActivityPausedListener>>();
Jeff Hamilton52d32032011-01-08 15:31:26 -0600412
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700413 final GcIdler mGcIdler = new GcIdler();
Tim Murray59f3dc12018-10-22 15:26:08 -0700414 final PurgeIdler mPurgeIdler = new PurgeIdler();
415
416 boolean mPurgeIdlerScheduled = false;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700417 boolean mGcIdlerScheduled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418
Mathew Inwood8c854f82018-09-14 12:35:36 +0100419 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Jeff Sharkeyd5896632016-03-04 16:16:00 -0700420 static volatile Handler sMainThreadHandler; // set once in main()
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -0700421
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -0800422 Bundle mCoreSettings = null;
423
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800424 /** Activity client record, used for bookkeeping for the real {@link Activity} instance. */
425 public static final class ActivityClientRecord {
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100426 @UnsupportedAppUsage
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800427 public IBinder token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700428 int ident;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100429 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 Intent intent;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800431 String referrer;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700432 IVoiceInteractor voiceInteractor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 Bundle state;
Craig Mautnera0026042014-04-23 11:45:37 -0700434 PersistableBundle persistentState;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100435 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 Activity activity;
437 Window window;
438 Activity parent;
439 String embeddedID;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700440 Activity.NonConfigurationInstances lastNonConfigurationInstances;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800441 // TODO(lifecycler): Use mLifecycleState instead.
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100442 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 boolean paused;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100444 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 boolean stopped;
446 boolean hideForNow;
447 Configuration newConfig;
Dianne Hackborne88846e2009-09-30 21:34:25 -0700448 Configuration createdConfig;
Wale Ogunwale60454db2015-01-23 16:05:07 -0800449 Configuration overrideConfig;
Garfield Tan0443b372019-01-04 15:00:13 -0800450 // Used to save the last reported configuration from server side so that activity
451 // configuration transactions can always use the latest configuration.
452 @GuardedBy("this")
453 private Configuration mPendingOverrideConfig;
Wale Ogunwalec2607b42015-02-07 16:16:59 -0800454 // Used for consolidating configs before sending on to Activity.
455 private Configuration tmpConfig = new Configuration();
Andrii Kulian44607962017-03-16 11:06:24 -0700456 // Callback used for updating activity override config.
457 ViewRootImpl.ActivityConfigCallback configCallback;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700458 ActivityClientRecord nextIdle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459
Andrii Kuliand70cdb92019-01-08 15:03:50 -0800460 // Indicates whether this activity is currently the topmost resumed one in the system.
461 // This holds the last reported value from server.
462 boolean isTopResumedActivity;
463 // This holds the value last sent to the activity. This is needed, because an update from
464 // server may come at random time, but we always need to report changes between ON_RESUME
465 // and ON_PAUSE to the app.
466 boolean lastReportedTopResumedState;
467
Jeff Hao1b012d32014-08-20 10:35:34 -0700468 ProfilerInfo profilerInfo;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700469
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100470 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 ActivityInfo activityInfo;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100472 @UnsupportedAppUsage
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400473 CompatibilityInfo compatInfo;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100474 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +0000475 public LoadedApk packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476
477 List<ResultInfo> pendingResults;
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800478 List<ReferrerIntent> pendingIntents;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479
480 boolean startsNotResumed;
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800481 public final boolean isForward;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800482 int pendingConfigChanges;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800483
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700484 Window mPendingRemoveWindow;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -0800485 WindowManager mPendingRemoveWindowManager;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100486 @UnsupportedAppUsage
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -0700487 boolean mPreserveWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800489 @LifecycleState
490 private int mLifecycleState = PRE_ON_CREATE;
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700491
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800492 @VisibleForTesting
Mathew Inwood8c854f82018-09-14 12:35:36 +0100493 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800494 public ActivityClientRecord() {
495 this.isForward = false;
496 init();
497 }
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -0700498
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800499 public ActivityClientRecord(IBinder token, Intent intent, int ident,
500 ActivityInfo info, Configuration overrideConfig, CompatibilityInfo compatInfo,
501 String referrer, IVoiceInteractor voiceInteractor, Bundle state,
502 PersistableBundle persistentState, List<ResultInfo> pendingResults,
503 List<ReferrerIntent> pendingNewIntents, boolean isForward,
504 ProfilerInfo profilerInfo, ClientTransactionHandler client) {
505 this.token = token;
506 this.ident = ident;
507 this.intent = intent;
508 this.referrer = referrer;
509 this.voiceInteractor = voiceInteractor;
510 this.activityInfo = info;
511 this.compatInfo = compatInfo;
512 this.state = state;
513 this.persistentState = persistentState;
514 this.pendingResults = pendingResults;
515 this.pendingIntents = pendingNewIntents;
516 this.isForward = isForward;
517 this.profilerInfo = profilerInfo;
518 this.overrideConfig = overrideConfig;
Todd Kennedy233a0b12018-01-29 20:30:24 +0000519 this.packageInfo = client.getPackageInfoNoCheck(activityInfo.applicationInfo,
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800520 compatInfo);
521 init();
522 }
523
524 /** Common initializer for all constructors. */
525 private void init() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 parent = null;
527 embeddedID = null;
528 paused = false;
529 stopped = false;
530 hideForNow = false;
531 nextIdle = null;
Andrii Kulian44607962017-03-16 11:06:24 -0700532 configCallback = (Configuration overrideConfig, int newDisplayId) -> {
533 if (activity == null) {
534 throw new IllegalStateException(
535 "Received config update for non-existing activity");
536 }
Andrii Kulian446e8242017-10-26 15:17:29 -0700537 activity.mMainThread.handleActivityConfigurationChanged(token, overrideConfig,
538 newDisplayId);
Andrii Kulian44607962017-03-16 11:06:24 -0700539 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 }
541
Andrii Kulian88e05cb2017-12-05 17:21:10 -0800542 /** Get the current lifecycle state. */
543 public int getLifecycleState() {
544 return mLifecycleState;
545 }
546
547 /** Update the current lifecycle state for internal bookkeeping. */
548 public void setState(@LifecycleState int newLifecycleState) {
549 mLifecycleState = newLifecycleState;
550 switch (mLifecycleState) {
551 case ON_CREATE:
552 paused = true;
553 stopped = true;
554 break;
555 case ON_START:
556 paused = true;
557 stopped = false;
558 break;
559 case ON_RESUME:
560 paused = false;
561 stopped = false;
562 break;
563 case ON_PAUSE:
564 paused = true;
565 stopped = false;
566 break;
567 case ON_STOP:
568 paused = true;
569 stopped = true;
570 break;
571 }
572 }
573
Andrii Kulian391161f2018-01-29 10:50:02 -0800574 private boolean isPreHoneycomb() {
575 return activity != null && activity.getApplicationInfo().targetSdkVersion
576 < android.os.Build.VERSION_CODES.HONEYCOMB;
577 }
578
579 private boolean isPreP() {
580 return activity != null && activity.getApplicationInfo().targetSdkVersion
581 < android.os.Build.VERSION_CODES.P;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800582 }
583
Craig Mautnera0026042014-04-23 11:45:37 -0700584 public boolean isPersistable() {
Craig Mautner43e52ed2014-06-16 17:18:52 -0700585 return activityInfo.persistableMode == ActivityInfo.PERSIST_ACROSS_REBOOTS;
Craig Mautnera0026042014-04-23 11:45:37 -0700586 }
587
Andrii Kulian914aa7d2018-03-19 21:51:53 -0700588 public boolean isVisibleFromServer() {
589 return activity != null && activity.mVisibleFromServer;
590 }
591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 public String toString() {
Dianne Hackbornb61a0262012-05-14 17:19:18 -0700593 ComponentName componentName = intent != null ? intent.getComponent() : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 return "ActivityRecord{"
595 + Integer.toHexString(System.identityHashCode(this))
596 + " token=" + token + " " + (componentName == null
597 ? "no component name" : componentName.toShortString())
598 + "}";
599 }
Andrii Kulian58178f22016-03-16 13:44:56 -0700600
601 public String getStateString() {
602 StringBuilder sb = new StringBuilder();
603 sb.append("ActivityClientRecord{");
604 sb.append("paused=").append(paused);
605 sb.append(", stopped=").append(stopped);
606 sb.append(", hideForNow=").append(hideForNow);
607 sb.append(", startsNotResumed=").append(startsNotResumed);
608 sb.append(", isForward=").append(isForward);
609 sb.append(", pendingConfigChanges=").append(pendingConfigChanges);
Andrii Kulian58178f22016-03-16 13:44:56 -0700610 sb.append(", preserveWindow=").append(mPreserveWindow);
611 if (activity != null) {
612 sb.append(", Activity{");
613 sb.append("resumed=").append(activity.mResumed);
614 sb.append(", stopped=").append(activity.mStopped);
615 sb.append(", finished=").append(activity.isFinishing());
616 sb.append(", destroyed=").append(activity.isDestroyed());
617 sb.append(", startedActivity=").append(activity.mStartedActivity);
618 sb.append(", temporaryPause=").append(activity.mTemporaryPause);
619 sb.append(", changingConfigurations=").append(activity.mChangingConfigurations);
Andrii Kulian58178f22016-03-16 13:44:56 -0700620 sb.append("}");
621 }
622 sb.append("}");
623 return sb.toString();
624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 }
626
Wale Ogunwale1d646122015-04-24 14:45:14 -0700627 final class ProviderClientRecord {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700628 final String[] mNames;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100629 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 final IContentProvider mProvider;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100631 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 final ContentProvider mLocalProvider;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100633 @UnsupportedAppUsage
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700634 final ContentProviderHolder mHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700636 ProviderClientRecord(String[] names, IContentProvider provider,
Sudheer Shankafc46e9b2016-10-21 17:55:27 -0700637 ContentProvider localProvider, ContentProviderHolder holder) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700638 mNames = names;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 mProvider = provider;
640 mLocalProvider = localProvider;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -0700641 mHolder = holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 }
643 }
644
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400645 static final class ReceiverData extends BroadcastReceiver.PendingResult {
Dianne Hackborne829fef2010-10-26 17:44:01 -0700646 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700647 boolean ordered, boolean sticky, IBinder token, int sendingUser) {
648 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky,
riddle_hsu1f5ac4d2015-01-03 15:38:21 +0800649 token, sendingUser, intent.getFlags());
Dianne Hackborne829fef2010-10-26 17:44:01 -0700650 this.intent = intent;
651 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700652
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100653 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 Intent intent;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100655 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 ActivityInfo info;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100657 @UnsupportedAppUsage
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400658 CompatibilityInfo compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 public String toString() {
660 return "ReceiverData{intent=" + intent + " packageName=" +
Dianne Hackborne829fef2010-10-26 17:44:01 -0700661 info.packageName + " resultCode=" + getResultCode()
662 + " resultData=" + getResultData() + " resultExtras="
663 + getResultExtras(false) + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 }
665 }
666
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400667 static final class CreateBackupAgentData {
Christopher Tate181fafa2009-05-14 11:12:14 -0700668 ApplicationInfo appInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400669 CompatibilityInfo compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700670 int backupMode;
Ruslan Tkhakokhov063180f2019-01-28 20:29:46 +0000671 int userId;
Christopher Tate181fafa2009-05-14 11:12:14 -0700672 public String toString() {
673 return "CreateBackupAgentData{appInfo=" + appInfo
674 + " backupAgent=" + appInfo.backupAgentName
Ruslan Tkhakokhov063180f2019-01-28 20:29:46 +0000675 + " mode=" + backupMode + " userId=" + userId + "}";
Christopher Tate181fafa2009-05-14 11:12:14 -0700676 }
677 }
Bob Leee5408332009-09-04 18:31:17 -0700678
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400679 static final class CreateServiceData {
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100680 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 IBinder token;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100682 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 ServiceInfo info;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100684 @UnsupportedAppUsage
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400685 CompatibilityInfo compatInfo;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100686 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 Intent intent;
688 public String toString() {
689 return "CreateServiceData{token=" + token + " className="
690 + info.name + " packageName=" + info.packageName
691 + " intent=" + intent + "}";
692 }
693 }
694
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400695 static final class BindServiceData {
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100696 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 IBinder token;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100698 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 Intent intent;
700 boolean rebind;
701 public String toString() {
702 return "BindServiceData{token=" + token + " intent=" + intent + "}";
703 }
704 }
705
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400706 static final class ServiceArgsData {
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100707 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 IBinder token;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700709 boolean taskRemoved;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 int startId;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700711 int flags;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100712 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 Intent args;
714 public String toString() {
715 return "ServiceArgsData{token=" + token + " startId=" + startId
716 + " args=" + args + "}";
717 }
718 }
719
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400720 static final class AppBindData {
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100721 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +0000722 LoadedApk info;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100723 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 String processName;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100725 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 ApplicationInfo appInfo;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100727 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 List<ProviderInfo> providers;
729 ComponentName instrumentationName;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100730 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 Bundle instrumentationArgs;
732 IInstrumentationWatcher instrumentationWatcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800733 IUiAutomationConnection instrumentationUiAutomationConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 int debugMode;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -0400735 boolean enableBinderTracking;
Man Caocfa78b22015-06-11 20:14:34 -0700736 boolean trackAllocation;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100737 @UnsupportedAppUsage
Christopher Tate181fafa2009-05-14 11:12:14 -0700738 boolean restrictedBackupMode;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100739 @UnsupportedAppUsage
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700740 boolean persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 Configuration config;
Mathew Inwood8c854f82018-09-14 12:35:36 +0100742 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400743 CompatibilityInfo compatInfo;
Svet Ganov37e43272016-09-09 16:01:32 -0700744 String buildSerial;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700745
746 /** Initial values for {@link Profiler}. */
Jeff Hao1b012d32014-08-20 10:35:34 -0700747 ProfilerInfo initProfilerInfo;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700748
Felipe Lemea4f39cd2019-02-19 15:08:59 -0800749 AutofillOptions autofillOptions;
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800750
Felipe Leme326f15a2019-02-19 09:42:24 -0800751 /**
752 * Content capture options for the application - when null, it means ContentCapture is not
753 * enabled for the package.
754 */
755 @Nullable
756 ContentCaptureOptions contentCaptureOptions;
757
758 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 public String toString() {
760 return "AppBindData{appInfo=" + appInfo + "}";
761 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700762 }
763
764 static final class Profiler {
765 String profileFile;
766 ParcelFileDescriptor profileFd;
Jeff Hao1b012d32014-08-20 10:35:34 -0700767 int samplingInterval;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700768 boolean autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800769 boolean streamingOutput;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -0700770 boolean profiling;
771 boolean handlingProfiling;
Jeff Hao1b012d32014-08-20 10:35:34 -0700772 public void setProfiler(ProfilerInfo profilerInfo) {
773 ParcelFileDescriptor fd = profilerInfo.profileFd;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700774 if (profiling) {
775 if (fd != null) {
776 try {
777 fd.close();
778 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700779 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700780 }
781 }
782 return;
783 }
784 if (profileFd != null) {
785 try {
786 profileFd.close();
787 } catch (IOException e) {
Romain Guya998dff2012-03-23 18:58:36 -0700788 // Ignore
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700789 }
790 }
Jeff Hao1b012d32014-08-20 10:35:34 -0700791 profileFile = profilerInfo.profileFile;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700792 profileFd = fd;
Jeff Hao1b012d32014-08-20 10:35:34 -0700793 samplingInterval = profilerInfo.samplingInterval;
794 autoStopProfiler = profilerInfo.autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800795 streamingOutput = profilerInfo.streamingOutput;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700796 }
797 public void startProfiling() {
798 if (profileFd == null || profiling) {
799 return;
800 }
801 try {
Andreas Gampeeff06392016-05-10 12:51:45 -0700802 int bufferSize = SystemProperties.getInt("debug.traceview-buffer-size-mb", 8);
Jeff Hao1b012d32014-08-20 10:35:34 -0700803 VMDebug.startMethodTracing(profileFile, profileFd.getFileDescriptor(),
Shukang Zhou6ffd4f92017-01-25 16:07:57 -0800804 bufferSize * 1024 * 1024, 0, samplingInterval != 0, samplingInterval,
805 streamingOutput);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700806 profiling = true;
807 } catch (RuntimeException e) {
Andreas Gampe4f689242018-03-14 23:13:28 -0700808 Slog.w(TAG, "Profiling failed on path " + profileFile, e);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700809 try {
810 profileFd.close();
811 profileFd = null;
812 } catch (IOException e2) {
813 Slog.w(TAG, "Failure closing profile fd", e2);
814 }
815 }
816 }
817 public void stopProfiling() {
818 if (profiling) {
819 profiling = false;
820 Debug.stopMethodTracing();
821 if (profileFd != null) {
822 try {
823 profileFd.close();
824 } catch (IOException e) {
825 }
826 }
827 profileFd = null;
828 profileFile = null;
829 }
830 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 }
832
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400833 static final class DumpComponentInfo {
Dianne Hackborne17aeb32011-04-07 15:11:57 -0700834 ParcelFileDescriptor fd;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700835 IBinder token;
Dianne Hackborn30d71892010-12-11 10:37:55 -0800836 String prefix;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 String[] args;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 }
839
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400840 static final class ContextCleanupInfo {
Dianne Hackborn21556372010-02-04 16:34:40 -0800841 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 String what;
843 String who;
844 }
845
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400846 static final class DumpHeapData {
Christopher Ferris8d652f82017-04-11 16:29:18 -0700847 public boolean managed;
848 public boolean mallocInfo;
Makoto Onuki4556b7b2017-07-07 14:58:58 -0700849 public boolean runGc;
Andy McFadden824c5102010-07-09 16:26:57 -0700850 String path;
851 ParcelFileDescriptor fd;
Makoto Onuki2c6657f2018-06-06 15:24:02 -0700852 RemoteCallback finishCallback;
Andy McFadden824c5102010-07-09 16:26:57 -0700853 }
854
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400855 static final class UpdateCompatibilityData {
856 String pkg;
857 CompatibilityInfo info;
858 }
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800859
Adam Skorydfc7fd72013-08-05 19:23:41 -0700860 static final class RequestAssistContextExtras {
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800861 IBinder activityToken;
862 IBinder requestToken;
863 int requestType;
Amith Yamasani4f128e42016-05-10 11:44:12 -0700864 int sessionId;
Svet Ganovfd31f852017-04-26 15:54:27 -0700865 int flags;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800866 }
Anwar Ghuloum3a8ce1b2013-04-26 16:18:28 -0700867
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700868 private class ApplicationThread extends IApplicationThread.Stub {
Vasu Nori3c7131f2010-09-21 14:36:57 -0700869 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
Bob Leee5408332009-09-04 18:31:17 -0700870
Dianne Hackborna413dc02013-07-12 12:02:55 -0700871 private int mLastProcessState = -1;
872
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700873 private void updatePendingConfiguration(Configuration config) {
Craig Mautner88c05892013-06-28 09:47:45 -0700874 synchronized (mResourcesManager) {
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700875 if (mPendingConfiguration == null ||
876 mPendingConfiguration.isOtherSeqNewer(config)) {
877 mPendingConfiguration = config;
878 }
879 }
880 }
881
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800882 public final void scheduleSleeping(IBinder token, boolean sleeping) {
Jeff Brown9ef09972013-10-15 20:49:59 -0700883 sendMessage(H.SLEEPING, token, sleeping ? 1 : 0);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800884 }
885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 public final void scheduleReceiver(Intent intent, ActivityInfo info,
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400887 CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700888 boolean sync, int sendingUser, int processState) {
889 updateProcessState(processState, false);
Dianne Hackborne829fef2010-10-26 17:44:01 -0700890 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700891 sync, false, mAppThread.asBinder(), sendingUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 r.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400893 r.compatInfo = compatInfo;
Jeff Brown9ef09972013-10-15 20:49:59 -0700894 sendMessage(H.RECEIVER, r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 }
896
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400897 public final void scheduleCreateBackupAgent(ApplicationInfo app,
Ruslan Tkhakokhov063180f2019-01-28 20:29:46 +0000898 CompatibilityInfo compatInfo, int backupMode, int userId) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700899 CreateBackupAgentData d = new CreateBackupAgentData();
900 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400901 d.compatInfo = compatInfo;
Christopher Tate181fafa2009-05-14 11:12:14 -0700902 d.backupMode = backupMode;
Ruslan Tkhakokhov063180f2019-01-28 20:29:46 +0000903 d.userId = userId;
Christopher Tate181fafa2009-05-14 11:12:14 -0700904
Jeff Brown9ef09972013-10-15 20:49:59 -0700905 sendMessage(H.CREATE_BACKUP_AGENT, d);
Christopher Tate181fafa2009-05-14 11:12:14 -0700906 }
907
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400908 public final void scheduleDestroyBackupAgent(ApplicationInfo app,
Annie Mengd5827872019-01-30 20:28:57 +0000909 CompatibilityInfo compatInfo, int userId) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700910 CreateBackupAgentData d = new CreateBackupAgentData();
911 d.appInfo = app;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400912 d.compatInfo = compatInfo;
Annie Mengd5827872019-01-30 20:28:57 +0000913 d.userId = userId;
Christopher Tate181fafa2009-05-14 11:12:14 -0700914
Jeff Brown9ef09972013-10-15 20:49:59 -0700915 sendMessage(H.DESTROY_BACKUP_AGENT, d);
Christopher Tate181fafa2009-05-14 11:12:14 -0700916 }
917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 public final void scheduleCreateService(IBinder token,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700919 ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
920 updateProcessState(processState, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 CreateServiceData s = new CreateServiceData();
922 s.token = token;
923 s.info = info;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400924 s.compatInfo = compatInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925
Jeff Brown9ef09972013-10-15 20:49:59 -0700926 sendMessage(H.CREATE_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 }
928
929 public final void scheduleBindService(IBinder token, Intent intent,
Dianne Hackborna413dc02013-07-12 12:02:55 -0700930 boolean rebind, int processState) {
931 updateProcessState(processState, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 BindServiceData s = new BindServiceData();
933 s.token = token;
934 s.intent = intent;
935 s.rebind = rebind;
936
Amith Yamasani742a6712011-05-04 14:49:28 -0700937 if (DEBUG_SERVICE)
938 Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
939 + Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
Jeff Brown9ef09972013-10-15 20:49:59 -0700940 sendMessage(H.BIND_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 }
942
943 public final void scheduleUnbindService(IBinder token, Intent intent) {
944 BindServiceData s = new BindServiceData();
945 s.token = token;
946 s.intent = intent;
947
Jeff Brown9ef09972013-10-15 20:49:59 -0700948 sendMessage(H.UNBIND_SERVICE, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 }
950
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -0700951 public final void scheduleServiceArgs(IBinder token, ParceledListSlice args) {
952 List<ServiceStartArgs> list = args.getList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953
Dianne Hackborn3f7c9f22017-04-04 15:36:33 -0700954 for (int i = 0; i < list.size(); i++) {
955 ServiceStartArgs ssa = list.get(i);
956 ServiceArgsData s = new ServiceArgsData();
957 s.token = token;
958 s.taskRemoved = ssa.taskRemoved;
959 s.startId = ssa.startId;
960 s.flags = ssa.flags;
961 s.args = ssa.args;
962
963 sendMessage(H.SERVICE_ARGS, s);
964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 }
966
967 public final void scheduleStopService(IBinder token) {
Jeff Brown9ef09972013-10-15 20:49:59 -0700968 sendMessage(H.STOP_SERVICE, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 }
970
Jeff Hao1b012d32014-08-20 10:35:34 -0700971 public final void bindApplication(String processName, ApplicationInfo appInfo,
972 List<ProviderInfo> providers, ComponentName instrumentationName,
973 ProfilerInfo profilerInfo, Bundle instrumentationArgs,
974 IInstrumentationWatcher instrumentationWatcher,
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800975 IUiAutomationConnection instrumentationUiConnection, int debugMode,
Pablo Ceballosa4d4e822015-10-05 10:27:52 -0700976 boolean enableBinderTracking, boolean trackAllocation,
977 boolean isRestrictedBackupMode, boolean persistent, Configuration config,
Sudheer Shankacc6418f2016-10-13 12:03:44 -0700978 CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
Felipe Lemea4f39cd2019-02-19 15:08:59 -0800979 String buildSerial, AutofillOptions autofillOptions,
Felipe Leme326f15a2019-02-19 09:42:24 -0800980 ContentCaptureOptions contentCaptureOptions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 if (services != null) {
Makoto Onuki45895652018-05-07 14:43:05 -0700982 if (false) {
983 // Test code to make sure the app could see the passed-in services.
984 for (Object oname : services.keySet()) {
985 if (services.get(oname) == null) {
986 continue; // AM just passed in a null service.
987 }
988 String name = (String) oname;
989
990 // See b/79378449 about the following exemption.
991 switch (name) {
992 case "package":
993 case Context.WINDOW_SERVICE:
994 continue;
995 }
996
997 if (ServiceManager.getService(name) == null) {
998 Log.wtf(TAG, "Service " + name + " should be accessible by this app");
999 }
1000 }
1001 }
1002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 // Setup the service cache in the ServiceManager
1004 ServiceManager.initServiceCache(services);
1005 }
1006
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08001007 setCoreSettings(coreSettings);
1008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 AppBindData data = new AppBindData();
1010 data.processName = processName;
1011 data.appInfo = appInfo;
1012 data.providers = providers;
1013 data.instrumentationName = instrumentationName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 data.instrumentationArgs = instrumentationArgs;
1015 data.instrumentationWatcher = instrumentationWatcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -08001016 data.instrumentationUiAutomationConnection = instrumentationUiConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 data.debugMode = debugMode;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001018 data.enableBinderTracking = enableBinderTracking;
Man Caocfa78b22015-06-11 20:14:34 -07001019 data.trackAllocation = trackAllocation;
Christopher Tate181fafa2009-05-14 11:12:14 -07001020 data.restrictedBackupMode = isRestrictedBackupMode;
Dianne Hackborn5d927c22011-09-02 12:22:18 -07001021 data.persistent = persistent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 data.config = config;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001023 data.compatInfo = compatInfo;
Jeff Hao1b012d32014-08-20 10:35:34 -07001024 data.initProfilerInfo = profilerInfo;
Svet Ganov37e43272016-09-09 16:01:32 -07001025 data.buildSerial = buildSerial;
Felipe Lemea4f39cd2019-02-19 15:08:59 -08001026 data.autofillOptions = autofillOptions;
Felipe Leme326f15a2019-02-19 09:42:24 -08001027 data.contentCaptureOptions = contentCaptureOptions;
Jeff Brown9ef09972013-10-15 20:49:59 -07001028 sendMessage(H.BIND_APPLICATION, data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 }
1030
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001031 public final void runIsolatedEntryPoint(String entryPoint, String[] entryPointArgs) {
1032 SomeArgs args = SomeArgs.obtain();
1033 args.arg1 = entryPoint;
1034 args.arg2 = entryPointArgs;
1035 sendMessage(H.RUN_ISOLATED_ENTRY_POINT, args);
1036 }
1037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 public final void scheduleExit() {
Jeff Brown9ef09972013-10-15 20:49:59 -07001039 sendMessage(H.EXIT_APPLICATION, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 }
1041
Christopher Tate5e1ab332009-09-01 20:32:49 -07001042 public final void scheduleSuicide() {
Jeff Brown9ef09972013-10-15 20:49:59 -07001043 sendMessage(H.SUICIDE, null);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001044 }
1045
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001046 public void scheduleApplicationInfoChanged(ApplicationInfo ai) {
1047 sendMessage(H.APPLICATION_INFO_CHANGED, ai);
1048 }
1049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 public void updateTimeZone() {
1051 TimeZone.setDefault(null);
1052 }
1053
Robert Greenwalt03595d02010-11-02 14:08:23 -07001054 public void clearDnsCache() {
1055 // a non-standard API to get this to libcore
1056 InetAddress.clearDnsCache();
Paul Jensene401d172014-09-12 10:47:39 -04001057 // Allow libcore to perform the necessary actions as it sees fit upon a network
1058 // configuration change.
1059 NetworkEventDispatcher.getInstance().onNetworkConfigurationChanged();
Robert Greenwalt03595d02010-11-02 14:08:23 -07001060 }
1061
Irina Dumitrescu18622d32018-12-05 16:19:47 +00001062 public void updateHttpProxy() {
Chalard Jean100df0a2018-05-15 23:11:45 +09001063 final ConnectivityManager cm = ConnectivityManager.from(
1064 getApplication() != null ? getApplication() : getSystemContext());
Irina Dumitrescu18622d32018-12-05 16:19:47 +00001065 Proxy.setHttpProxySystemProperty(cm.getDefaultProxy());
Robert Greenwalt434203a2010-10-11 16:00:27 -07001066 }
1067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 public void processInBackground() {
1069 mH.removeMessages(H.GC_WHEN_IDLE);
1070 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
1071 }
1072
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001073 public void dumpService(ParcelFileDescriptor pfd, IBinder servicetoken, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07001074 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001075 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001076 data.fd = pfd.dup();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001077 data.token = servicetoken;
1078 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001079 sendMessage(H.DUMP_SERVICE, data, 0, 0, true /*async*/);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001080 } catch (IOException e) {
1081 Slog.w(TAG, "dumpService failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001082 } finally {
1083 IoUtils.closeQuietly(pfd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 }
1085 }
1086
1087 // This function exists to make sure all receiver dispatching is
1088 // correctly ordered, since these are one-way calls and the binder driver
1089 // applies transaction ordering per object for such calls.
1090 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07001091 int resultCode, String dataStr, Bundle extras, boolean ordered,
Dianne Hackborna413dc02013-07-12 12:02:55 -07001092 boolean sticky, int sendingUser, int processState) throws RemoteException {
1093 updateProcessState(processState, false);
Dianne Hackborn20e80982012-08-31 19:00:44 -07001094 receiver.performReceive(intent, resultCode, dataStr, extras, ordered,
1095 sticky, sendingUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 }
Bob Leee5408332009-09-04 18:31:17 -07001097
Wale Ogunwalec2607b42015-02-07 16:16:59 -08001098 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 public void scheduleLowMemory() {
Jeff Brown9ef09972013-10-15 20:49:59 -07001100 sendMessage(H.LOW_MEMORY, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 }
1102
Wale Ogunwale60454db2015-01-23 16:05:07 -08001103 @Override
Jeff Hao1b012d32014-08-20 10:35:34 -07001104 public void profilerControl(boolean start, ProfilerInfo profilerInfo, int profileType) {
1105 sendMessage(H.PROFILER_CONTROL, profilerInfo, start ? 1 : 0, profileType);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001106 }
1107
Makoto Onuki4556b7b2017-07-07 14:58:58 -07001108 @Override
Christopher Ferris8d652f82017-04-11 16:29:18 -07001109 public void dumpHeap(boolean managed, boolean mallocInfo, boolean runGc, String path,
Makoto Onuki2c6657f2018-06-06 15:24:02 -07001110 ParcelFileDescriptor fd, RemoteCallback finishCallback) {
Andy McFadden824c5102010-07-09 16:26:57 -07001111 DumpHeapData dhd = new DumpHeapData();
Christopher Ferris8d652f82017-04-11 16:29:18 -07001112 dhd.managed = managed;
1113 dhd.mallocInfo = mallocInfo;
Makoto Onuki4556b7b2017-07-07 14:58:58 -07001114 dhd.runGc = runGc;
Andy McFadden824c5102010-07-09 16:26:57 -07001115 dhd.path = path;
1116 dhd.fd = fd;
Makoto Onuki2c6657f2018-06-06 15:24:02 -07001117 dhd.finishCallback = finishCallback;
Christopher Ferris8d652f82017-04-11 16:29:18 -07001118 sendMessage(H.DUMP_HEAP, dhd, 0, 0, true /*async*/);
Andy McFadden824c5102010-07-09 16:26:57 -07001119 }
1120
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001121 public void attachAgent(String agent) {
1122 sendMessage(H.ATTACH_AGENT, agent);
1123 }
1124
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001125 public void setSchedulingGroup(int group) {
1126 // Note: do this immediately, since going into the foreground
1127 // should happen regardless of what pending work we have to do
1128 // and the activity manager will wait for us to report back that
1129 // we are done before sending us to the background.
1130 try {
1131 Process.setProcessGroup(Process.myPid(), group);
1132 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08001133 Slog.w(TAG, "Failed setting process group to " + group, e);
Dianne Hackborn06de2ea2009-05-21 12:56:43 -07001134 }
1135 }
Bob Leee5408332009-09-04 18:31:17 -07001136
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001137 public void dispatchPackageBroadcast(int cmd, String[] packages) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001138 sendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001139 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001140
1141 public void scheduleCrash(String msg) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001142 sendMessage(H.SCHEDULE_CRASH, msg);
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001143 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07001144
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001145 public void dumpActivity(ParcelFileDescriptor pfd, IBinder activitytoken,
Dianne Hackborn30d71892010-12-11 10:37:55 -08001146 String prefix, String[] args) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07001147 DumpComponentInfo data = new DumpComponentInfo();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001148 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001149 data.fd = pfd.dup();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001150 data.token = activitytoken;
1151 data.prefix = prefix;
1152 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001153 sendMessage(H.DUMP_ACTIVITY, data, 0, 0, true /*async*/);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001154 } catch (IOException e) {
1155 Slog.w(TAG, "dumpActivity failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001156 } finally {
1157 IoUtils.closeQuietly(pfd);
Dianne Hackborn625ac272010-09-17 18:29:22 -07001158 }
1159 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07001160
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001161 public void dumpProvider(ParcelFileDescriptor pfd, IBinder providertoken,
Marco Nelissen18cb2872011-11-15 11:19:53 -08001162 String[] args) {
1163 DumpComponentInfo data = new DumpComponentInfo();
1164 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001165 data.fd = pfd.dup();
Marco Nelissen18cb2872011-11-15 11:19:53 -08001166 data.token = providertoken;
1167 data.args = args;
Jeff Brown9ef09972013-10-15 20:49:59 -07001168 sendMessage(H.DUMP_PROVIDER, data, 0, 0, true /*async*/);
Marco Nelissen18cb2872011-11-15 11:19:53 -08001169 } catch (IOException e) {
1170 Slog.w(TAG, "dumpProvider failed", e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001171 } finally {
1172 IoUtils.closeQuietly(pfd);
Marco Nelissen18cb2872011-11-15 11:19:53 -08001173 }
1174 }
1175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001177 public void dumpMemInfo(ParcelFileDescriptor pfd, Debug.MemoryInfo mem, boolean checkin,
Colin Crossc4fb5f92016-02-02 16:51:15 -08001178 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
1179 boolean dumpUnreachable, String[] args) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001180 FileOutputStream fout = new FileOutputStream(pfd.getFileDescriptor());
Dianne Hackborn8c841092013-06-24 13:46:13 -07001181 PrintWriter pw = new FastPrintWriter(fout);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001182 try {
Colin Crossc4fb5f92016-02-02 16:51:15 -08001183 dumpMemInfo(pw, mem, checkin, dumpFullInfo, dumpDalvik, dumpSummaryOnly, dumpUnreachable);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001184 } finally {
Chet Haase9c1e23b2011-03-24 10:51:31 -07001185 pw.flush();
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001186 IoUtils.closeQuietly(pfd);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001187 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001188 }
1189
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001190 private void dumpMemInfo(PrintWriter pw, Debug.MemoryInfo memInfo, boolean checkin,
Colin Crossc4fb5f92016-02-02 16:51:15 -08001191 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly, boolean dumpUnreachable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 long nativeMax = Debug.getNativeHeapSize() / 1024;
1193 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1194 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 Runtime runtime = Runtime.getRuntime();
Mathieu Chartierd288a262015-07-10 13:44:42 -07001197 runtime.gc(); // Do GC since countInstancesOfClass counts unreachable objects.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 long dalvikMax = runtime.totalMemory() / 1024;
1199 long dalvikFree = runtime.freeMemory() / 1024;
1200 long dalvikAllocated = dalvikMax - dalvikFree;
Richard Uhler2c036192016-09-14 09:48:31 +01001201
1202 Class[] classesToCount = new Class[] {
1203 ContextImpl.class,
1204 Activity.class,
1205 WebView.class,
1206 OpenSSLSocketImpl.class
1207 };
1208 long[] instanceCounts = VMDebug.countInstancesOfClasses(classesToCount, true);
1209 long appContextInstanceCount = instanceCounts[0];
1210 long activityInstanceCount = instanceCounts[1];
1211 long webviewInstanceCount = instanceCounts[2];
1212 long openSslSocketCount = instanceCounts[3];
1213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 long viewInstanceCount = ViewDebug.getViewInstanceCount();
Romain Guy65b345f2011-07-27 18:51:50 -07001215 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 int globalAssetCount = AssetManager.getGlobalAssetCount();
1217 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1218 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1219 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1220 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
Dianne Hackbornfabb70b2014-11-11 12:22:36 -08001221 long parcelSize = Parcel.getGlobalAllocSize();
1222 long parcelCount = Parcel.getGlobalAllocCount();
Vasu Noric3849202010-03-09 10:47:25 -08001223 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
Bob Leee5408332009-09-04 18:31:17 -07001224
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07001225 dumpMemInfoTable(pw, memInfo, checkin, dumpFullInfo, dumpDalvik, dumpSummaryOnly,
1226 Process.myPid(),
Dianne Hackborne77187d2013-10-25 16:32:41 -07001227 (mBoundApplication != null) ? mBoundApplication.processName : "unknown",
1228 nativeMax, nativeAllocated, nativeFree,
1229 dalvikMax, dalvikAllocated, dalvikFree);
1230
Dianne Hackbornb437e092011-08-05 17:50:29 -07001231 if (checkin) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 // NOTE: if you change anything significant below, also consider changing
1233 // ACTIVITY_THREAD_CHECKIN_VERSION.
Anwar Ghuloum3c615062013-05-13 14:18:02 -07001234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 // Object counts
1236 pw.print(viewInstanceCount); pw.print(',');
1237 pw.print(viewRootInstanceCount); pw.print(',');
1238 pw.print(appContextInstanceCount); pw.print(',');
1239 pw.print(activityInstanceCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 pw.print(globalAssetCount); pw.print(',');
1242 pw.print(globalAssetManagerCount); pw.print(',');
1243 pw.print(binderLocalObjectCount); pw.print(',');
1244 pw.print(binderProxyObjectCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 pw.print(binderDeathObjectCount); pw.print(',');
1247 pw.print(openSslSocketCount); pw.print(',');
Bob Leee5408332009-09-04 18:31:17 -07001248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 // SQL
Vasu Noric3849202010-03-09 10:47:25 -08001250 pw.print(stats.memoryUsed / 1024); pw.print(',');
Jeff Brown2a293b62012-01-19 14:02:22 -08001251 pw.print(stats.memoryUsed / 1024); pw.print(',');
1252 pw.print(stats.pageCacheOverflow / 1024); pw.print(',');
Dianne Hackbornb437e092011-08-05 17:50:29 -07001253 pw.print(stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001254 for (int i = 0; i < stats.dbStats.size(); i++) {
1255 DbStats dbStats = stats.dbStats.get(i);
Dianne Hackbornb437e092011-08-05 17:50:29 -07001256 pw.print(','); pw.print(dbStats.dbName);
1257 pw.print(','); pw.print(dbStats.pageSize);
1258 pw.print(','); pw.print(dbStats.dbSize);
1259 pw.print(','); pw.print(dbStats.lookaside);
1260 pw.print(','); pw.print(dbStats.cache);
1261 pw.print(','); pw.print(dbStats.cache);
Vasu Noric3849202010-03-09 10:47:25 -08001262 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07001263 pw.println();
Bob Leee5408332009-09-04 18:31:17 -07001264
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001265 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 }
Bob Leee5408332009-09-04 18:31:17 -07001267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 pw.println(" ");
1269 pw.println(" Objects");
Romain Guy65b345f2011-07-27 18:51:50 -07001270 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRootImpl:",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 viewRootInstanceCount);
1272
1273 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
1274 "Activities:", activityInstanceCount);
1275
1276 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
1277 "AssetManagers:", globalAssetManagerCount);
1278
1279 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
1280 "Proxy Binders:", binderProxyObjectCount);
Dianne Hackbornfabb70b2014-11-11 12:22:36 -08001281 printRow(pw, TWO_COUNT_COLUMNS, "Parcel memory:", parcelSize/1024,
1282 "Parcel count:", parcelCount);
1283 printRow(pw, TWO_COUNT_COLUMNS, "Death Recipients:", binderDeathObjectCount,
1284 "OpenSSL Sockets:", openSslSocketCount);
Richard Uhler2c036192016-09-14 09:48:31 +01001285 printRow(pw, ONE_COUNT_COLUMN, "WebViews:", webviewInstanceCount);
Bob Leee5408332009-09-04 18:31:17 -07001286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 // SQLite mem info
1288 pw.println(" ");
1289 pw.println(" SQL");
Jeff Brown2a293b62012-01-19 14:02:22 -08001290 printRow(pw, ONE_COUNT_COLUMN, "MEMORY_USED:", stats.memoryUsed / 1024);
1291 printRow(pw, TWO_COUNT_COLUMNS, "PAGECACHE_OVERFLOW:",
1292 stats.pageCacheOverflow / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
Vasu Noric3849202010-03-09 10:47:25 -08001293 pw.println(" ");
1294 int N = stats.dbStats.size();
1295 if (N > 0) {
1296 pw.println(" DATABASES");
Kweku Adams983829f2017-12-06 14:53:50 -08001297 printRow(pw, DB_INFO_FORMAT, "pgsz", "dbsz", "Lookaside(b)", "cache",
Vasu Nori3c7131f2010-09-21 14:36:57 -07001298 "Dbname");
Vasu Noric3849202010-03-09 10:47:25 -08001299 for (int i = 0; i < N; i++) {
1300 DbStats dbStats = stats.dbStats.get(i);
Vasu Nori3c7131f2010-09-21 14:36:57 -07001301 printRow(pw, DB_INFO_FORMAT,
1302 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
1303 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
1304 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
1305 dbStats.cache, dbStats.dbName);
Vasu Noric3849202010-03-09 10:47:25 -08001306 }
1307 }
Bob Leee5408332009-09-04 18:31:17 -07001308
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07001309 // Asset details.
1310 String assetAlloc = AssetManager.getAssetAllocations();
1311 if (assetAlloc != null) {
1312 pw.println(" ");
1313 pw.println(" Asset Allocations");
1314 pw.print(assetAlloc);
1315 }
Colin Crossc4fb5f92016-02-02 16:51:15 -08001316
1317 // Unreachable native memory
1318 if (dumpUnreachable) {
1319 boolean showContents = ((mBoundApplication != null)
1320 && ((mBoundApplication.appInfo.flags&ApplicationInfo.FLAG_DEBUGGABLE) != 0))
1321 || android.os.Build.IS_DEBUGGABLE;
1322 pw.println(" ");
1323 pw.println(" Unreachable memory");
1324 pw.print(Debug.getUnreachableMemory(100, showContents));
1325 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07001326 }
1327
1328 @Override
Kweku Adams983829f2017-12-06 14:53:50 -08001329 public void dumpMemInfoProto(ParcelFileDescriptor pfd, Debug.MemoryInfo mem,
1330 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
1331 boolean dumpUnreachable, String[] args) {
1332 ProtoOutputStream proto = new ProtoOutputStream(pfd.getFileDescriptor());
1333 try {
1334 dumpMemInfo(proto, mem, dumpFullInfo, dumpDalvik, dumpSummaryOnly, dumpUnreachable);
1335 } finally {
1336 proto.flush();
1337 IoUtils.closeQuietly(pfd);
1338 }
1339 }
1340
1341 private void dumpMemInfo(ProtoOutputStream proto, Debug.MemoryInfo memInfo,
1342 boolean dumpFullInfo, boolean dumpDalvik,
1343 boolean dumpSummaryOnly, boolean dumpUnreachable) {
1344 long nativeMax = Debug.getNativeHeapSize() / 1024;
1345 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1346 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1347
1348 Runtime runtime = Runtime.getRuntime();
1349 runtime.gc(); // Do GC since countInstancesOfClass counts unreachable objects.
1350 long dalvikMax = runtime.totalMemory() / 1024;
1351 long dalvikFree = runtime.freeMemory() / 1024;
1352 long dalvikAllocated = dalvikMax - dalvikFree;
1353
1354 Class[] classesToCount = new Class[] {
1355 ContextImpl.class,
1356 Activity.class,
1357 WebView.class,
1358 OpenSSLSocketImpl.class
1359 };
1360 long[] instanceCounts = VMDebug.countInstancesOfClasses(classesToCount, true);
1361 long appContextInstanceCount = instanceCounts[0];
1362 long activityInstanceCount = instanceCounts[1];
1363 long webviewInstanceCount = instanceCounts[2];
1364 long openSslSocketCount = instanceCounts[3];
1365
1366 long viewInstanceCount = ViewDebug.getViewInstanceCount();
1367 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
1368 int globalAssetCount = AssetManager.getGlobalAssetCount();
1369 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1370 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1371 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1372 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
1373 long parcelSize = Parcel.getGlobalAllocSize();
1374 long parcelCount = Parcel.getGlobalAllocCount();
1375 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
1376
Yi Jin2b30f322018-02-20 15:41:47 -08001377 final long mToken = proto.start(MemInfoDumpProto.AppData.PROCESS_MEMORY);
1378 proto.write(MemInfoDumpProto.ProcessMemory.PID, Process.myPid());
1379 proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME,
Kweku Adams983829f2017-12-06 14:53:50 -08001380 (mBoundApplication != null) ? mBoundApplication.processName : "unknown");
1381 dumpMemInfoTable(proto, memInfo, dumpDalvik, dumpSummaryOnly,
1382 nativeMax, nativeAllocated, nativeFree,
1383 dalvikMax, dalvikAllocated, dalvikFree);
1384 proto.end(mToken);
1385
Yi Jin2b30f322018-02-20 15:41:47 -08001386 final long oToken = proto.start(MemInfoDumpProto.AppData.OBJECTS);
1387 proto.write(MemInfoDumpProto.AppData.ObjectStats.VIEW_INSTANCE_COUNT,
1388 viewInstanceCount);
1389 proto.write(MemInfoDumpProto.AppData.ObjectStats.VIEW_ROOT_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001390 viewRootInstanceCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001391 proto.write(MemInfoDumpProto.AppData.ObjectStats.APP_CONTEXT_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001392 appContextInstanceCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001393 proto.write(MemInfoDumpProto.AppData.ObjectStats.ACTIVITY_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001394 activityInstanceCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001395 proto.write(MemInfoDumpProto.AppData.ObjectStats.GLOBAL_ASSET_COUNT,
1396 globalAssetCount);
1397 proto.write(MemInfoDumpProto.AppData.ObjectStats.GLOBAL_ASSET_MANAGER_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001398 globalAssetManagerCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001399 proto.write(MemInfoDumpProto.AppData.ObjectStats.LOCAL_BINDER_OBJECT_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001400 binderLocalObjectCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001401 proto.write(MemInfoDumpProto.AppData.ObjectStats.PROXY_BINDER_OBJECT_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001402 binderProxyObjectCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001403 proto.write(MemInfoDumpProto.AppData.ObjectStats.PARCEL_MEMORY_KB,
1404 parcelSize / 1024);
1405 proto.write(MemInfoDumpProto.AppData.ObjectStats.PARCEL_COUNT, parcelCount);
1406 proto.write(MemInfoDumpProto.AppData.ObjectStats.BINDER_OBJECT_DEATH_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001407 binderDeathObjectCount);
Yi Jin2b30f322018-02-20 15:41:47 -08001408 proto.write(MemInfoDumpProto.AppData.ObjectStats.OPEN_SSL_SOCKET_COUNT,
1409 openSslSocketCount);
1410 proto.write(MemInfoDumpProto.AppData.ObjectStats.WEBVIEW_INSTANCE_COUNT,
Kweku Adams983829f2017-12-06 14:53:50 -08001411 webviewInstanceCount);
1412 proto.end(oToken);
1413
1414 // SQLite mem info
Yi Jin2b30f322018-02-20 15:41:47 -08001415 final long sToken = proto.start(MemInfoDumpProto.AppData.SQL);
1416 proto.write(MemInfoDumpProto.AppData.SqlStats.MEMORY_USED_KB,
1417 stats.memoryUsed / 1024);
1418 proto.write(MemInfoDumpProto.AppData.SqlStats.PAGECACHE_OVERFLOW_KB,
Kweku Adams983829f2017-12-06 14:53:50 -08001419 stats.pageCacheOverflow / 1024);
Yi Jin2b30f322018-02-20 15:41:47 -08001420 proto.write(MemInfoDumpProto.AppData.SqlStats.MALLOC_SIZE_KB,
1421 stats.largestMemAlloc / 1024);
Kweku Adams983829f2017-12-06 14:53:50 -08001422 int n = stats.dbStats.size();
1423 for (int i = 0; i < n; i++) {
1424 DbStats dbStats = stats.dbStats.get(i);
1425
Yi Jin2b30f322018-02-20 15:41:47 -08001426 final long dToken = proto.start(MemInfoDumpProto.AppData.SqlStats.DATABASES);
1427 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.NAME, dbStats.dbName);
1428 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.PAGE_SIZE, dbStats.pageSize);
1429 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.DB_SIZE, dbStats.dbSize);
1430 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.LOOKASIDE_B,
1431 dbStats.lookaside);
1432 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.CACHE, dbStats.cache);
Kweku Adams983829f2017-12-06 14:53:50 -08001433 proto.end(dToken);
1434 }
1435 proto.end(sToken);
1436
1437 // Asset details.
1438 String assetAlloc = AssetManager.getAssetAllocations();
1439 if (assetAlloc != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08001440 proto.write(MemInfoDumpProto.AppData.ASSET_ALLOCATIONS, assetAlloc);
Kweku Adams983829f2017-12-06 14:53:50 -08001441 }
1442
1443 // Unreachable native memory
1444 if (dumpUnreachable) {
1445 int flags = mBoundApplication == null ? 0 : mBoundApplication.appInfo.flags;
1446 boolean showContents = (flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0
1447 || android.os.Build.IS_DEBUGGABLE;
Yi Jin2b30f322018-02-20 15:41:47 -08001448 proto.write(MemInfoDumpProto.AppData.UNREACHABLE_MEMORY,
Kweku Adams983829f2017-12-06 14:53:50 -08001449 Debug.getUnreachableMemory(100, showContents));
1450 }
1451 }
1452
1453 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001454 public void dumpGfxInfo(ParcelFileDescriptor pfd, String[] args) {
Chris Craikfc294242016-12-13 18:10:46 -08001455 nDumpGraphicsInfo(pfd.getFileDescriptor());
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001456 WindowManagerGlobal.getInstance().dumpGfxInfo(pfd.getFileDescriptor(), args);
1457 IoUtils.closeQuietly(pfd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 }
1459
Makoto Onuki016dc592018-08-14 12:26:45 -07001460 private File getDatabasesDir(Context context) {
1461 // There's no simple way to get the databases/ path, so do it this way.
1462 return context.getDatabasePath("a").getParentFile();
1463 }
1464
1465 private void dumpDatabaseInfo(ParcelFileDescriptor pfd, String[] args, boolean isSystem) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001466 PrintWriter pw = new FastPrintWriter(
1467 new FileOutputStream(pfd.getFileDescriptor()));
Jeff Brown6754ba22011-12-14 20:20:01 -08001468 PrintWriterPrinter printer = new PrintWriterPrinter(pw);
Makoto Onukiee93ad22018-10-18 16:24:13 -07001469 SQLiteDebug.dump(printer, args, isSystem);
Jeff Brown6754ba22011-12-14 20:20:01 -08001470 pw.flush();
1471 }
1472
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001473 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001474 public void dumpDbInfo(final ParcelFileDescriptor pfd, final String[] args) {
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001475 if (mSystemThread) {
Felipe Leme29de4922016-06-07 16:14:07 -07001476 // Ensure this invocation is asynchronous to prevent writer waiting if buffer cannot
1477 // be consumed. But it must duplicate the file descriptor first, since caller might
1478 // be closing it.
1479 final ParcelFileDescriptor dup;
1480 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001481 dup = pfd.dup();
Felipe Leme29de4922016-06-07 16:14:07 -07001482 } catch (IOException e) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001483 Log.w(TAG, "Could not dup FD " + pfd.getFileDescriptor().getInt$());
Felipe Leme29de4922016-06-07 16:14:07 -07001484 return;
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001485 } finally {
1486 IoUtils.closeQuietly(pfd);
Felipe Leme29de4922016-06-07 16:14:07 -07001487 }
1488
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001489 AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
1490 @Override
1491 public void run() {
Felipe Lemec74972f2016-06-08 09:12:37 -07001492 try {
Makoto Onuki016dc592018-08-14 12:26:45 -07001493 dumpDatabaseInfo(dup, args, true);
Felipe Lemec74972f2016-06-08 09:12:37 -07001494 } finally {
1495 IoUtils.closeQuietly(dup);
1496 }
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001497 }
1498 });
1499 } else {
Makoto Onuki016dc592018-08-14 12:26:45 -07001500 dumpDatabaseInfo(pfd, args, false);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001501 IoUtils.closeQuietly(pfd);
riddle_hsu1d6c40a2014-07-31 00:18:00 +08001502 }
1503 }
1504
1505 @Override
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001506 public void unstableProviderDied(IBinder provider) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001507 sendMessage(H.UNSTABLE_PROVIDER_DIED, provider);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001508 }
1509
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001510 @Override
Adam Skorydfc7fd72013-08-05 19:23:41 -07001511 public void requestAssistContextExtras(IBinder activityToken, IBinder requestToken,
Svet Ganovfd31f852017-04-26 15:54:27 -07001512 int requestType, int sessionId, int flags) {
Adam Skorydfc7fd72013-08-05 19:23:41 -07001513 RequestAssistContextExtras cmd = new RequestAssistContextExtras();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001514 cmd.activityToken = activityToken;
1515 cmd.requestToken = requestToken;
1516 cmd.requestType = requestType;
Amith Yamasani4f128e42016-05-10 11:44:12 -07001517 cmd.sessionId = sessionId;
Svet Ganovfd31f852017-04-26 15:54:27 -07001518 cmd.flags = flags;
Jeff Brown9ef09972013-10-15 20:49:59 -07001519 sendMessage(H.REQUEST_ASSIST_CONTEXT_EXTRAS, cmd);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001520 }
1521
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08001522 public void setCoreSettings(Bundle coreSettings) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001523 sendMessage(H.SET_CORE_SETTINGS, coreSettings);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001524 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001525
1526 public void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) {
1527 UpdateCompatibilityData ucd = new UpdateCompatibilityData();
1528 ucd.pkg = pkg;
1529 ucd.info = info;
Jeff Brown9ef09972013-10-15 20:49:59 -07001530 sendMessage(H.UPDATE_PACKAGE_COMPATIBILITY_INFO, ucd);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001531 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001532
1533 public void scheduleTrimMemory(int level) {
Jorim Jaggib29e3182018-04-30 18:51:56 +02001534 final Runnable r = PooledLambda.obtainRunnable(ActivityThread::handleTrimMemory,
Yohei Yukawae2fa39e2018-09-22 13:13:10 -07001535 ActivityThread.this, level).recycleOnUse();
Jorim Jaggib29e3182018-04-30 18:51:56 +02001536 // Schedule trimming memory after drawing the frame to minimize jank-risk.
1537 Choreographer choreographer = Choreographer.getMainThreadInstance();
1538 if (choreographer != null) {
1539 choreographer.postCallback(Choreographer.CALLBACK_COMMIT, r, null);
1540 } else {
1541 mH.post(r);
1542 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001543 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001544
Craig Mautner5eda9b32013-07-02 11:58:16 -07001545 public void scheduleTranslucentConversionComplete(IBinder token, boolean drawComplete) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001546 sendMessage(H.TRANSLUCENT_CONVERSION_COMPLETE, token, drawComplete ? 1 : 0);
Craig Mautner5eda9b32013-07-02 11:58:16 -07001547 }
Dianne Hackborna413dc02013-07-12 12:02:55 -07001548
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001549 public void scheduleOnNewActivityOptions(IBinder token, Bundle options) {
Craig Mautnereb8abf72014-07-02 15:04:09 -07001550 sendMessage(H.ON_NEW_ACTIVITY_OPTIONS,
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001551 new Pair<IBinder, ActivityOptions>(token, ActivityOptions.fromBundle(options)));
Craig Mautnereb8abf72014-07-02 15:04:09 -07001552 }
1553
Dianne Hackborna413dc02013-07-12 12:02:55 -07001554 public void setProcessState(int state) {
1555 updateProcessState(state, true);
1556 }
1557
1558 public void updateProcessState(int processState, boolean fromIpc) {
1559 synchronized (this) {
1560 if (mLastProcessState != processState) {
1561 mLastProcessState = processState;
Mathieu Chartier1e370902013-07-18 10:58:01 -07001562 // Update Dalvik state based on ActivityManager.PROCESS_STATE_* constants.
1563 final int DALVIK_PROCESS_STATE_JANK_PERCEPTIBLE = 0;
1564 final int DALVIK_PROCESS_STATE_JANK_IMPERCEPTIBLE = 1;
1565 int dalvikProcessState = DALVIK_PROCESS_STATE_JANK_IMPERCEPTIBLE;
1566 // TODO: Tune this since things like gmail sync are important background but not jank perceptible.
1567 if (processState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
1568 dalvikProcessState = DALVIK_PROCESS_STATE_JANK_PERCEPTIBLE;
1569 }
1570 VMRuntime.getRuntime().updateProcessState(dalvikProcessState);
Dianne Hackborna413dc02013-07-12 12:02:55 -07001571 if (false) {
1572 Slog.i(TAG, "******************* PROCESS STATE CHANGED TO: " + processState
1573 + (fromIpc ? " (from ipc": ""));
1574 }
1575 }
1576 }
1577 }
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001578
Sudheer Shanka84a48952017-03-08 18:19:01 -08001579 /**
1580 * Updates {@link #mNetworkBlockSeq}. This is used by ActivityManagerService to inform
1581 * the main thread that it needs to wait for the network rules to get updated before
1582 * launching an activity.
1583 */
1584 @Override
1585 public void setNetworkBlockSeq(long procStateSeq) {
1586 synchronized (mNetworkPolicyLock) {
1587 mNetworkBlockSeq = procStateSeq;
1588 }
1589 }
1590
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001591 @Override
1592 public void scheduleInstallProvider(ProviderInfo provider) {
Jeff Brown9ef09972013-10-15 20:49:59 -07001593 sendMessage(H.INSTALL_PROVIDER, provider);
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001594 }
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001595
1596 @Override
Neil Fullerb7146fe2016-11-15 16:52:15 +00001597 public final void updateTimePrefs(int timeFormatPreference) {
1598 final Boolean timeFormatPreferenceBool;
1599 // For convenience we are using the Intent extra values.
1600 if (timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_12_HOUR) {
1601 timeFormatPreferenceBool = Boolean.FALSE;
1602 } else if (timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_24_HOUR) {
1603 timeFormatPreferenceBool = Boolean.TRUE;
1604 } else {
1605 // timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_LOCALE_DEFAULT
1606 // (or unknown).
1607 timeFormatPreferenceBool = null;
1608 }
1609 DateFormat.set24HourTimePref(timeFormatPreferenceBool);
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001610 }
Craig Mautneree2e45a2014-06-27 12:10:03 -07001611
1612 @Override
Craig Mautner8746a472014-07-24 15:12:54 -07001613 public void scheduleEnterAnimationComplete(IBinder token) {
1614 sendMessage(H.ENTER_ANIMATION_COMPLETE, token);
1615 }
Jeff Sharkey605eb792014-11-04 13:34:06 -08001616
1617 @Override
1618 public void notifyCleartextNetwork(byte[] firstPacket) {
1619 if (StrictMode.vmCleartextNetworkEnabled()) {
1620 StrictMode.onCleartextNetworkDetected(firstPacket);
1621 }
1622 }
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001623
1624 @Override
1625 public void startBinderTracking() {
1626 sendMessage(H.START_BINDER_TRACKING, null);
1627 }
1628
1629 @Override
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001630 public void stopBinderTrackingAndDump(ParcelFileDescriptor pfd) {
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001631 try {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001632 sendMessage(H.STOP_BINDER_TRACKING_AND_DUMP, pfd.dup());
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001633 } catch (IOException e) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07001634 } finally {
1635 IoUtils.closeQuietly(pfd);
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001636 }
1637 }
Wale Ogunwale5f986092015-12-04 15:35:38 -08001638
1639 @Override
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001640 public void scheduleLocalVoiceInteractionStarted(IBinder token,
1641 IVoiceInteractor voiceInteractor) throws RemoteException {
1642 SomeArgs args = SomeArgs.obtain();
1643 args.arg1 = token;
1644 args.arg2 = voiceInteractor;
1645 sendMessage(H.LOCAL_VOICE_INTERACTION_STARTED, args);
1646 }
Chad Brubakerc72875b2016-04-27 16:35:11 -07001647
1648 @Override
1649 public void handleTrustStorageUpdate() {
1650 NetworkSecurityPolicy.getInstance().handleTrustStorageUpdate();
1651 }
Andrii Kulian446e8242017-10-26 15:17:29 -07001652
1653 @Override
1654 public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
1655 ActivityThread.this.scheduleTransaction(transaction);
1656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 }
1658
Andrii Kulian446e8242017-10-26 15:17:29 -07001659 @Override
1660 public void updatePendingConfiguration(Configuration config) {
1661 mAppThread.updatePendingConfiguration(config);
1662 }
1663
1664 @Override
1665 public void updateProcessState(int processState, boolean fromIpc) {
1666 mAppThread.updateProcessState(processState, fromIpc);
1667 }
1668
Andrii Kulian446e8242017-10-26 15:17:29 -07001669 class H extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 public static final int BIND_APPLICATION = 110;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001671 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 public static final int EXIT_APPLICATION = 111;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001673 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 public static final int RECEIVER = 113;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001675 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 public static final int CREATE_SERVICE = 114;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001677 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 public static final int SERVICE_ARGS = 115;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001679 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 public static final int STOP_SERVICE = 116;
Dianne Hackborn09233282014-04-30 11:33:59 -07001681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 public static final int CONFIGURATION_CHANGED = 118;
1683 public static final int CLEAN_UP_CONTEXT = 119;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001684 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 public static final int GC_WHEN_IDLE = 120;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001686 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 public static final int BIND_SERVICE = 121;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001688 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 public static final int UNBIND_SERVICE = 122;
1690 public static final int DUMP_SERVICE = 123;
1691 public static final int LOW_MEMORY = 124;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001692 public static final int PROFILER_CONTROL = 127;
Christopher Tate181fafa2009-05-14 11:12:14 -07001693 public static final int CREATE_BACKUP_AGENT = 128;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001694 public static final int DESTROY_BACKUP_AGENT = 129;
1695 public static final int SUICIDE = 130;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001696 @UnsupportedAppUsage
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001697 public static final int REMOVE_PROVIDER = 131;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001698 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001699 @UnsupportedAppUsage
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001700 public static final int SCHEDULE_CRASH = 134;
Andy McFadden824c5102010-07-09 16:26:57 -07001701 public static final int DUMP_HEAP = 135;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001702 public static final int DUMP_ACTIVITY = 136;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001703 public static final int SLEEPING = 137;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001704 public static final int SET_CORE_SETTINGS = 138;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001705 public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001706 @UnsupportedAppUsage
Marco Nelissen18cb2872011-11-15 11:19:53 -08001707 public static final int DUMP_PROVIDER = 141;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001708 public static final int UNSTABLE_PROVIDER_DIED = 142;
Adam Skorydfc7fd72013-08-05 19:23:41 -07001709 public static final int REQUEST_ASSIST_CONTEXT_EXTRAS = 143;
Craig Mautner5eda9b32013-07-02 11:58:16 -07001710 public static final int TRANSLUCENT_CONVERSION_COMPLETE = 144;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001711 @UnsupportedAppUsage
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001712 public static final int INSTALL_PROVIDER = 145;
Craig Mautnereb8abf72014-07-02 15:04:09 -07001713 public static final int ON_NEW_ACTIVITY_OPTIONS = 146;
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001714 @UnsupportedAppUsage
Craig Mautner8746a472014-07-24 15:12:54 -07001715 public static final int ENTER_ANIMATION_COMPLETE = 149;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001716 public static final int START_BINDER_TRACKING = 150;
1717 public static final int STOP_BINDER_TRACKING_AND_DUMP = 151;
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001718 public static final int LOCAL_VOICE_INTERACTION_STARTED = 154;
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001719 public static final int ATTACH_AGENT = 155;
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001720 public static final int APPLICATION_INFO_CHANGED = 156;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001721 public static final int RUN_ISOLATED_ENTRY_POINT = 158;
Andrii Kulian446e8242017-10-26 15:17:29 -07001722 public static final int EXECUTE_TRANSACTION = 159;
Andrii Kulian320e3b52018-05-03 16:26:25 -07001723 public static final int RELAUNCH_ACTIVITY = 160;
Tim Murray59f3dc12018-10-22 15:26:08 -07001724 public static final int PURGE_RESOURCES = 161;
Narayan Kamathccb2a0862013-12-19 14:49:36 +00001725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 String codeToString(int code) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001727 if (DEBUG_MESSAGES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 switch (code) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 case BIND_APPLICATION: return "BIND_APPLICATION";
1730 case EXIT_APPLICATION: return "EXIT_APPLICATION";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 case RECEIVER: return "RECEIVER";
1732 case CREATE_SERVICE: return "CREATE_SERVICE";
1733 case SERVICE_ARGS: return "SERVICE_ARGS";
1734 case STOP_SERVICE: return "STOP_SERVICE";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
1736 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
1737 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
1738 case BIND_SERVICE: return "BIND_SERVICE";
1739 case UNBIND_SERVICE: return "UNBIND_SERVICE";
1740 case DUMP_SERVICE: return "DUMP_SERVICE";
1741 case LOW_MEMORY: return "LOW_MEMORY";
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001742 case PROFILER_CONTROL: return "PROFILER_CONTROL";
Christopher Tate181fafa2009-05-14 11:12:14 -07001743 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
1744 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
Christopher Tate5e1ab332009-09-01 20:32:49 -07001745 case SUICIDE: return "SUICIDE";
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001746 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001747 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001748 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
Andy McFadden824c5102010-07-09 16:26:57 -07001749 case DUMP_HEAP: return "DUMP_HEAP";
Dianne Hackborn625ac272010-09-17 18:29:22 -07001750 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001751 case SLEEPING: return "SLEEPING";
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001752 case SET_CORE_SETTINGS: return "SET_CORE_SETTINGS";
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001753 case UPDATE_PACKAGE_COMPATIBILITY_INFO: return "UPDATE_PACKAGE_COMPATIBILITY_INFO";
Marco Nelissen18cb2872011-11-15 11:19:53 -08001754 case DUMP_PROVIDER: return "DUMP_PROVIDER";
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001755 case UNSTABLE_PROVIDER_DIED: return "UNSTABLE_PROVIDER_DIED";
Adam Skorydfc7fd72013-08-05 19:23:41 -07001756 case REQUEST_ASSIST_CONTEXT_EXTRAS: return "REQUEST_ASSIST_CONTEXT_EXTRAS";
Craig Mautner5eda9b32013-07-02 11:58:16 -07001757 case TRANSLUCENT_CONVERSION_COMPLETE: return "TRANSLUCENT_CONVERSION_COMPLETE";
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001758 case INSTALL_PROVIDER: return "INSTALL_PROVIDER";
Craig Mautnereb8abf72014-07-02 15:04:09 -07001759 case ON_NEW_ACTIVITY_OPTIONS: return "ON_NEW_ACTIVITY_OPTIONS";
Craig Mautner8746a472014-07-24 15:12:54 -07001760 case ENTER_ANIMATION_COMPLETE: return "ENTER_ANIMATION_COMPLETE";
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001761 case LOCAL_VOICE_INTERACTION_STARTED: return "LOCAL_VOICE_INTERACTION_STARTED";
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07001762 case ATTACH_AGENT: return "ATTACH_AGENT";
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001763 case APPLICATION_INFO_CHANGED: return "APPLICATION_INFO_CHANGED";
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001764 case RUN_ISOLATED_ENTRY_POINT: return "RUN_ISOLATED_ENTRY_POINT";
Andrii Kulian446e8242017-10-26 15:17:29 -07001765 case EXECUTE_TRANSACTION: return "EXECUTE_TRANSACTION";
Andrii Kulian320e3b52018-05-03 16:26:25 -07001766 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
Tim Murray59f3dc12018-10-22 15:26:08 -07001767 case PURGE_RESOURCES: return "PURGE_RESOURCES";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 }
1769 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001770 return Integer.toString(code);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 }
1772 public void handleMessage(Message msg) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001773 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 switch (msg.what) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 case BIND_APPLICATION:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001776 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 AppBindData data = (AppBindData)msg.obj;
1778 handleBindApplication(data);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001779 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 break;
1781 case EXIT_APPLICATION:
1782 if (mInitialApplication != null) {
1783 mInitialApplication.onTerminate();
1784 }
1785 Looper.myLooper().quit();
1786 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 case RECEIVER:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001788 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveComp");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 handleReceiver((ReceiverData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001790 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 break;
1792 case CREATE_SERVICE:
Tim Murrayb6f5a422016-04-07 15:25:22 -07001793 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceCreate: " + String.valueOf(msg.obj)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 handleCreateService((CreateServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001795 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 break;
1797 case BIND_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001798 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 handleBindService((BindServiceData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001800 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 break;
1802 case UNBIND_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001803 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceUnbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 handleUnbindService((BindServiceData)msg.obj);
Tim Murray59f3dc12018-10-22 15:26:08 -07001805 schedulePurgeIdler();
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001806 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 break;
1808 case SERVICE_ARGS:
Tim Murrayb6f5a422016-04-07 15:25:22 -07001809 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceStart: " + String.valueOf(msg.obj)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 handleServiceArgs((ServiceArgsData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001811 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 break;
1813 case STOP_SERVICE:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001814 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 handleStopService((IBinder)msg.obj);
Tim Murray59f3dc12018-10-22 15:26:08 -07001816 schedulePurgeIdler();
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001817 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 case CONFIGURATION_CHANGED:
Andrii Kulian446e8242017-10-26 15:17:29 -07001820 handleConfigurationChanged((Configuration) msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 break;
1822 case CLEAN_UP_CONTEXT:
1823 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
1824 cci.context.performFinalCleanup(cci.who, cci.what);
1825 break;
1826 case GC_WHEN_IDLE:
1827 scheduleGcIdler();
1828 break;
1829 case DUMP_SERVICE:
Dianne Hackborn625ac272010-09-17 18:29:22 -07001830 handleDumpService((DumpComponentInfo)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 break;
1832 case LOW_MEMORY:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001833 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "lowMemory");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 handleLowMemory();
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001835 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 break;
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001837 case PROFILER_CONTROL:
Jeff Hao1b012d32014-08-20 10:35:34 -07001838 handleProfilerControl(msg.arg1 != 0, (ProfilerInfo)msg.obj, msg.arg2);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08001839 break;
Christopher Tate181fafa2009-05-14 11:12:14 -07001840 case CREATE_BACKUP_AGENT:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001841 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupCreateAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001842 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001843 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate181fafa2009-05-14 11:12:14 -07001844 break;
1845 case DESTROY_BACKUP_AGENT:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001846 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupDestroyAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -07001847 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001848 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate181fafa2009-05-14 11:12:14 -07001849 break;
Christopher Tate5e1ab332009-09-01 20:32:49 -07001850 case SUICIDE:
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07001851 Process.killProcess(Process.myPid());
1852 break;
1853 case REMOVE_PROVIDER:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001854 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "providerRemove");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001855 completeRemoveProvider((ProviderRefCount)msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001856 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001857 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001858 case DISPATCH_PACKAGE_BROADCAST:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001859 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastPackage");
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001860 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001861 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07001862 break;
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001863 case SCHEDULE_CRASH:
1864 throw new RemoteServiceException((String)msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001865 case DUMP_HEAP:
Christopher Ferris8d652f82017-04-11 16:29:18 -07001866 handleDumpHeap((DumpHeapData) msg.obj);
Andy McFadden824c5102010-07-09 16:26:57 -07001867 break;
Dianne Hackborn625ac272010-09-17 18:29:22 -07001868 case DUMP_ACTIVITY:
1869 handleDumpActivity((DumpComponentInfo)msg.obj);
1870 break;
Marco Nelissen18cb2872011-11-15 11:19:53 -08001871 case DUMP_PROVIDER:
1872 handleDumpProvider((DumpComponentInfo)msg.obj);
1873 break;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001874 case SLEEPING:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001875 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "sleeping");
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001876 handleSleeping((IBinder)msg.obj, msg.arg1 != 0);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001877 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001878 break;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001879 case SET_CORE_SETTINGS:
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001880 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setCoreSettings");
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001881 handleSetCoreSettings((Bundle) msg.obj);
Dianne Hackborn1ded0b12012-04-26 14:14:50 -07001882 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08001883 break;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001884 case UPDATE_PACKAGE_COMPATIBILITY_INFO:
1885 handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07001886 break;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001887 case UNSTABLE_PROVIDER_DIED:
1888 handleUnstableProviderDied((IBinder)msg.obj, false);
1889 break;
Adam Skorydfc7fd72013-08-05 19:23:41 -07001890 case REQUEST_ASSIST_CONTEXT_EXTRAS:
1891 handleRequestAssistContextExtras((RequestAssistContextExtras)msg.obj);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08001892 break;
Craig Mautner5eda9b32013-07-02 11:58:16 -07001893 case TRANSLUCENT_CONVERSION_COMPLETE:
1894 handleTranslucentConversionComplete((IBinder)msg.obj, msg.arg1 == 1);
1895 break;
Jeff Sharkeydd97f422013-10-08 17:01:30 -07001896 case INSTALL_PROVIDER:
1897 handleInstallProvider((ProviderInfo) msg.obj);
1898 break;
Craig Mautnereb8abf72014-07-02 15:04:09 -07001899 case ON_NEW_ACTIVITY_OPTIONS:
1900 Pair<IBinder, ActivityOptions> pair = (Pair<IBinder, ActivityOptions>) msg.obj;
1901 onNewActivityOptions(pair.first, pair.second);
Dake Gu7ef70b02014-07-08 18:37:12 -07001902 break;
Craig Mautner8746a472014-07-24 15:12:54 -07001903 case ENTER_ANIMATION_COMPLETE:
1904 handleEnterAnimationComplete((IBinder) msg.obj);
1905 break;
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04001906 case START_BINDER_TRACKING:
1907 handleStartBinderTracking();
1908 break;
1909 case STOP_BINDER_TRACKING_AND_DUMP:
1910 handleStopBinderTrackingAndDump((ParcelFileDescriptor) msg.obj);
1911 break;
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001912 case LOCAL_VOICE_INTERACTION_STARTED:
1913 handleLocalVoiceInteractionStarted((IBinder) ((SomeArgs) msg.obj).arg1,
1914 (IVoiceInteractor) ((SomeArgs) msg.obj).arg2);
Amith Yamasani61019112017-01-10 15:05:00 -08001915 break;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08001916 case ATTACH_AGENT: {
1917 Application app = getApplication();
1918 handleAttachAgent((String) msg.obj, app != null ? app.mLoadedApk : null);
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001919 break;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08001920 }
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01001921 case APPLICATION_INFO_CHANGED:
1922 mUpdatingSystemConfig = true;
1923 try {
1924 handleApplicationInfoChanged((ApplicationInfo) msg.obj);
1925 } finally {
1926 mUpdatingSystemConfig = false;
1927 }
1928 break;
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04001929 case RUN_ISOLATED_ENTRY_POINT:
1930 handleRunIsolatedEntryPoint((String) ((SomeArgs) msg.obj).arg1,
1931 (String[]) ((SomeArgs) msg.obj).arg2);
1932 break;
Andrii Kulian446e8242017-10-26 15:17:29 -07001933 case EXECUTE_TRANSACTION:
Andrii Kulian04470682018-01-10 15:32:31 -08001934 final ClientTransaction transaction = (ClientTransaction) msg.obj;
1935 mTransactionExecutor.execute(transaction);
1936 if (isSystem()) {
1937 // Client transactions inside system process are recycled on the client side
1938 // instead of ClientLifecycleManager to avoid being cleared before this
1939 // message is handled.
1940 transaction.recycle();
1941 }
Andrii Kulian914aa7d2018-03-19 21:51:53 -07001942 // TODO(lifecycler): Recycle locally scheduled transactions.
Andrii Kulian446e8242017-10-26 15:17:29 -07001943 break;
Andrii Kulian320e3b52018-05-03 16:26:25 -07001944 case RELAUNCH_ACTIVITY:
1945 handleRelaunchActivityLocally((IBinder) msg.obj);
1946 break;
Tim Murray59f3dc12018-10-22 15:26:08 -07001947 case PURGE_RESOURCES:
1948 schedulePurgeIdler();
1949 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 }
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07001951 Object obj = msg.obj;
1952 if (obj instanceof SomeArgs) {
1953 ((SomeArgs) obj).recycle();
1954 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07001955 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 }
1957 }
1958
Romain Guy65b345f2011-07-27 18:51:50 -07001959 private class Idler implements MessageQueue.IdleHandler {
Craig Mautner48d0d182013-06-11 07:53:06 -07001960 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 public final boolean queueIdle() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001962 ActivityClientRecord a = mNewActivities;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001963 boolean stopProfiling = false;
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001964 if (mBoundApplication != null && mProfiler.profileFd != null
1965 && mProfiler.autoStopProfiler) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001966 stopProfiling = true;
1967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 if (a != null) {
1969 mNewActivities = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001970 IActivityTaskManager am = ActivityTaskManager.getService();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001971 ActivityClientRecord prev;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 do {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001973 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 TAG, "Reporting idle of " + a +
1975 " finished=" +
Romain Guy65b345f2011-07-27 18:51:50 -07001976 (a.activity != null && a.activity.mFinished));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 if (a.activity != null && !a.activity.mFinished) {
1978 try {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001979 am.activityIdle(a.token, a.createdConfig, stopProfiling);
Dianne Hackborne88846e2009-09-30 21:34:25 -07001980 a.createdConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001982 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983 }
1984 }
1985 prev = a;
1986 a = a.nextIdle;
1987 prev.nextIdle = null;
1988 } while (a != null);
1989 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001990 if (stopProfiling) {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07001991 mProfiler.stopProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07001992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 return false;
1994 }
1995 }
1996
1997 final class GcIdler implements MessageQueue.IdleHandler {
Craig Mautner48d0d182013-06-11 07:53:06 -07001998 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 public final boolean queueIdle() {
2000 doGcIfNeeded();
Tim Murray59f3dc12018-10-22 15:26:08 -07002001 nPurgePendingResources();
2002 return false;
2003 }
2004 }
2005
2006 final class PurgeIdler implements MessageQueue.IdleHandler {
2007 @Override
2008 public boolean queueIdle() {
2009 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "purgePendingResources");
2010 nPurgePendingResources();
2011 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 return false;
2013 }
2014 }
2015
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002016 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07002017 public static ActivityThread currentActivityThread() {
Jeff Sharkey66a017b2013-01-17 18:18:22 -08002018 return sCurrentActivityThread;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020
Wale Ogunwale9a6ef1e2015-06-02 13:41:00 -07002021 public static boolean isSystem() {
2022 return (sCurrentActivityThread != null) ? sCurrentActivityThread.mSystemThread : false;
2023 }
2024
Svetoslavfbf0eca2015-05-01 16:52:41 -07002025 public static String currentOpPackageName() {
2026 ActivityThread am = currentActivityThread();
2027 return (am != null && am.getApplication() != null)
2028 ? am.getApplication().getOpPackageName() : null;
2029 }
2030
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002031 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07002032 public static String currentPackageName() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002033 ActivityThread am = currentActivityThread();
2034 return (am != null && am.mBoundApplication != null)
Dianne Hackbornb57a50b2013-04-11 17:29:32 -07002035 ? am.mBoundApplication.appInfo.packageName : null;
2036 }
2037
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002038 @UnsupportedAppUsage
Dianne Hackbornb57a50b2013-04-11 17:29:32 -07002039 public static String currentProcessName() {
2040 ActivityThread am = currentActivityThread();
2041 return (am != null && am.mBoundApplication != null)
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002042 ? am.mBoundApplication.processName : null;
2043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002045 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07002046 public static Application currentApplication() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002047 ActivityThread am = currentActivityThread();
2048 return am != null ? am.mInitialApplication : null;
2049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002051 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002052 public static IPackageManager getPackageManager() {
2053 if (sPackageManager != null) {
2054 //Slog.v("PackageManager", "returning cur default = " + sPackageManager);
2055 return sPackageManager;
2056 }
2057 IBinder b = ServiceManager.getService("package");
2058 //Slog.v("PackageManager", "default service binder = " + b);
2059 sPackageManager = IPackageManager.Stub.asInterface(b);
2060 //Slog.v("PackageManager", "default service = " + sPackageManager);
2061 return sPackageManager;
2062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063
Romain Guy65b345f2011-07-27 18:51:50 -07002064 private Configuration mMainThreadConfig = new Configuration();
Amith Yamasani4f128e42016-05-10 11:44:12 -07002065
Dianne Hackborn908aecc2012-07-31 16:37:34 -07002066 Configuration applyConfigCompatMainThread(int displayDensity, Configuration config,
2067 CompatibilityInfo compat) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002068 if (config == null) {
2069 return null;
2070 }
Craig Mautner48d0d182013-06-11 07:53:06 -07002071 if (!compat.supportsScreen()) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002072 mMainThreadConfig.setTo(config);
2073 config = mMainThreadConfig;
Dianne Hackborn908aecc2012-07-31 16:37:34 -07002074 compat.applyToConfiguration(displayDensity, config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002075 }
2076 return config;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002079 /**
Todd Kennedy39bfee52016-02-24 10:28:21 -08002080 * Creates the top level resources for the given package. Will return an existing
2081 * Resources if one has already been created.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002082 */
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07002083 Resources getTopLevelResources(String resDir, String[] splitResDirs, String[] overlayDirs,
Adam Lesinski082614c2016-03-04 14:33:47 -08002084 String[] libDirs, int displayId, LoadedApk pkgInfo) {
2085 return mResourcesManager.getResources(null, resDir, splitResDirs, overlayDirs, libDirs,
2086 displayId, null, pkgInfo.getCompatibilityInfo(), pkgInfo.getClassLoader());
Todd Kennedy39bfee52016-02-24 10:28:21 -08002087 }
2088
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002089 @UnsupportedAppUsage
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002090 final Handler getHandler() {
2091 return mH;
2092 }
2093
Mathew Inwood8c854f82018-09-14 12:35:36 +01002094 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Todd Kennedy233a0b12018-01-29 20:30:24 +00002095 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
2096 int flags) {
2097 return getPackageInfo(packageName, compatInfo, flags, UserHandle.myUserId());
Amith Yamasani98edc952012-09-25 14:09:27 -07002098 }
2099
Todd Kennedy233a0b12018-01-29 20:30:24 +00002100 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
2101 int flags, int userId) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002102 final boolean differentUser = (UserHandle.myUserId() != userId);
Craig Mautner88c05892013-06-28 09:47:45 -07002103 synchronized (mResourcesManager) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002104 WeakReference<LoadedApk> ref;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002105 if (differentUser) {
2106 // Caching not supported across users
2107 ref = null;
2108 } else if ((flags & Context.CONTEXT_INCLUDE_CODE) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 ref = mPackages.get(packageName);
2110 } else {
2111 ref = mResourcePackages.get(packageName);
2112 }
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002113
Todd Kennedy233a0b12018-01-29 20:30:24 +00002114 LoadedApk packageInfo = ref != null ? ref.get() : null;
2115 //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
2116 //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
2117 // + ": " + packageInfo.mResources.getAssets().isUpToDate());
2118 if (packageInfo != null && (packageInfo.mResources == null
2119 || packageInfo.mResources.getAssets().isUpToDate())) {
2120 if (packageInfo.isSecurityViolation()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
2122 throw new SecurityException(
2123 "Requesting code from " + packageName
2124 + " to be run in process "
2125 + mBoundApplication.processName
2126 + "/" + mBoundApplication.appInfo.uid);
2127 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00002128 return packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 }
2130 }
2131
2132 ApplicationInfo ai = null;
2133 try {
2134 ai = getPackageManager().getApplicationInfo(packageName,
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002135 PackageManager.GET_SHARED_LIBRARY_FILES
2136 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
Jeff Sharkeyec5f7d12018-08-08 09:15:04 -06002137 (userId < 0) ? UserHandle.myUserId() : userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002139 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002140 }
2141
2142 if (ai != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002143 return getPackageInfo(ai, compatInfo, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002144 }
2145
2146 return null;
2147 }
2148
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002149 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +00002150 public final LoadedApk getPackageInfo(ApplicationInfo ai, CompatibilityInfo compatInfo,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002151 int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
2153 boolean securityViolation = includeCode && ai.uid != 0
2154 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002155 ? !UserHandle.isSameApp(ai.uid, mBoundApplication.appInfo.uid)
Amith Yamasani742a6712011-05-04 14:49:28 -07002156 : true);
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002157 boolean registerPackage = includeCode && (flags&Context.CONTEXT_REGISTER_PACKAGE) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002158 if ((flags&(Context.CONTEXT_INCLUDE_CODE
2159 |Context.CONTEXT_IGNORE_SECURITY))
2160 == Context.CONTEXT_INCLUDE_CODE) {
2161 if (securityViolation) {
2162 String msg = "Requesting code from " + ai.packageName
2163 + " (with uid " + ai.uid + ")";
2164 if (mBoundApplication != null) {
2165 msg = msg + " to be run in process "
2166 + mBoundApplication.processName + " (with uid "
2167 + mBoundApplication.appInfo.uid + ")";
2168 }
2169 throw new SecurityException(msg);
2170 }
2171 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00002172 return getPackageInfo(ai, compatInfo, null, securityViolation, includeCode,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002173 registerPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 }
2175
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002176 @Override
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002177 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +00002178 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002179 CompatibilityInfo compatInfo) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002180 return getPackageInfo(ai, compatInfo, null, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002181 }
2182
Mathew Inwood8c854f82018-09-14 12:35:36 +01002183 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Todd Kennedy233a0b12018-01-29 20:30:24 +00002184 public final LoadedApk peekPackageInfo(String packageName, boolean includeCode) {
Craig Mautner88c05892013-06-28 09:47:45 -07002185 synchronized (mResourcesManager) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002186 WeakReference<LoadedApk> ref;
2187 if (includeCode) {
2188 ref = mPackages.get(packageName);
2189 } else {
2190 ref = mResourcePackages.get(packageName);
2191 }
2192 return ref != null ? ref.get() : null;
2193 }
2194 }
2195
Todd Kennedy233a0b12018-01-29 20:30:24 +00002196 private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002197 ClassLoader baseLoader, boolean securityViolation, boolean includeCode,
2198 boolean registerPackage) {
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002199 final boolean differentUser = (UserHandle.myUserId() != UserHandle.getUserId(aInfo.uid));
Craig Mautner88c05892013-06-28 09:47:45 -07002200 synchronized (mResourcesManager) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002201 WeakReference<LoadedApk> ref;
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002202 if (differentUser) {
2203 // Caching not supported across users
2204 ref = null;
2205 } else if (includeCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002206 ref = mPackages.get(aInfo.packageName);
2207 } else {
2208 ref = mResourcePackages.get(aInfo.packageName);
2209 }
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002210
Todd Kennedy233a0b12018-01-29 20:30:24 +00002211 LoadedApk packageInfo = ref != null ? ref.get() : null;
2212 if (packageInfo == null || (packageInfo.mResources != null
2213 && !packageInfo.mResources.getAssets().isUpToDate())) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002214 if (localLOGV) Slog.v(TAG, (includeCode ? "Loading code package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002215 : "Loading resource-only package ") + aInfo.packageName
2216 + " (in " + (mBoundApplication != null
2217 ? mBoundApplication.processName : null)
2218 + ")");
Todd Kennedy233a0b12018-01-29 20:30:24 +00002219 packageInfo =
Jeff Browndefd4a62014-03-10 21:24:37 -07002220 new LoadedApk(this, aInfo, compatInfo, baseLoader,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002221 securityViolation, includeCode &&
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002222 (aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0, registerPackage);
Narayan Kamathcb383182014-10-29 17:56:42 +00002223
2224 if (mSystemThread && "android".equals(aInfo.packageName)) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002225 packageInfo.installSystemApplicationInfo(aInfo,
2226 getSystemContext().mPackageInfo.getClassLoader());
Narayan Kamathcb383182014-10-29 17:56:42 +00002227 }
2228
Jeff Sharkeyb9f36742015-04-08 21:02:14 -07002229 if (differentUser) {
2230 // Caching not supported across users
2231 } else if (includeCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002232 mPackages.put(aInfo.packageName,
Todd Kennedy233a0b12018-01-29 20:30:24 +00002233 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 } else {
2235 mResourcePackages.put(aInfo.packageName,
Todd Kennedy233a0b12018-01-29 20:30:24 +00002236 new WeakReference<LoadedApk>(packageInfo));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002237 }
2238 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00002239 return packageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002240 }
2241 }
2242
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002243 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 ActivityThread() {
Craig Mautner88c05892013-06-28 09:47:45 -07002245 mResourcesManager = ResourcesManager.getInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002246 }
2247
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002248 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 public ApplicationThread getApplicationThread()
2250 {
2251 return mAppThread;
2252 }
2253
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002254 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002255 public Instrumentation getInstrumentation()
2256 {
2257 return mInstrumentation;
2258 }
2259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 public boolean isProfiling() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002261 return mProfiler != null && mProfiler.profileFile != null
2262 && mProfiler.profileFd == null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 }
2264
2265 public String getProfileFilePath() {
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002266 return mProfiler.profileFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 }
2268
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002269 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002270 public Looper getLooper() {
2271 return mLooper;
2272 }
2273
Jeff Sharkey8439ac02017-12-12 17:26:23 -07002274 public Executor getExecutor() {
2275 return mExecutor;
2276 }
2277
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002278 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 public Application getApplication() {
2280 return mInitialApplication;
2281 }
Bob Leee5408332009-09-04 18:31:17 -07002282
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002283 @UnsupportedAppUsage
Dianne Hackbornd97c7ad2009-06-19 11:37:35 -07002284 public String getProcessName() {
2285 return mBoundApplication.processName;
2286 }
Bob Leee5408332009-09-04 18:31:17 -07002287
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002288 @UnsupportedAppUsage
Dianne Hackborn21556372010-02-04 16:34:40 -08002289 public ContextImpl getSystemContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002290 synchronized (this) {
2291 if (mSystemContext == null) {
Jeff Browndefd4a62014-03-10 21:24:37 -07002292 mSystemContext = ContextImpl.createSystemContext(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002293 }
Jeff Browndefd4a62014-03-10 21:24:37 -07002294 return mSystemContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002296 }
2297
Adam Lesinskia82b6262017-03-21 16:56:17 -07002298 public ContextImpl getSystemUiContext() {
2299 synchronized (this) {
2300 if (mSystemUiContext == null) {
Adam Lesinski6f1a9172017-04-10 16:35:19 -07002301 mSystemUiContext = ContextImpl.createSystemUiContext(getSystemContext());
Adam Lesinskia82b6262017-03-21 16:56:17 -07002302 }
2303 return mSystemUiContext;
2304 }
2305 }
2306
lumark0b05f9e2018-11-26 15:09:06 +08002307 /**
2308 * Create the context instance base on system resources & display information which used for UI.
2309 * @param displayId The ID of the display where the UI is shown.
2310 * @see ContextImpl#createSystemUiContext(ContextImpl, int)
2311 */
2312 public ContextImpl createSystemUiContext(int displayId) {
2313 return ContextImpl.createSystemUiContext(getSystemUiContext(), displayId);
2314 }
2315
Narayan Kamath29564cd2014-08-07 10:57:40 +01002316 public void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
Mike Cleron432b7132009-09-24 15:28:29 -07002317 synchronized (this) {
Narayan Kamath29564cd2014-08-07 10:57:40 +01002318 getSystemContext().installSystemApplicationInfo(info, classLoader);
Adam Lesinskia82b6262017-03-21 16:56:17 -07002319 getSystemUiContext().installSystemApplicationInfo(info, classLoader);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07002320
2321 // give ourselves a default profiler
2322 mProfiler = new Profiler();
Mike Cleron432b7132009-09-24 15:28:29 -07002323 }
2324 }
2325
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002326 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002327 void scheduleGcIdler() {
2328 if (!mGcIdlerScheduled) {
2329 mGcIdlerScheduled = true;
2330 Looper.myQueue().addIdleHandler(mGcIdler);
2331 }
2332 mH.removeMessages(H.GC_WHEN_IDLE);
2333 }
2334
2335 void unscheduleGcIdler() {
2336 if (mGcIdlerScheduled) {
2337 mGcIdlerScheduled = false;
2338 Looper.myQueue().removeIdleHandler(mGcIdler);
2339 }
2340 mH.removeMessages(H.GC_WHEN_IDLE);
2341 }
2342
Tim Murray59f3dc12018-10-22 15:26:08 -07002343 void schedulePurgeIdler() {
2344 if (!mPurgeIdlerScheduled) {
2345 mPurgeIdlerScheduled = true;
2346 Looper.myQueue().addIdleHandler(mPurgeIdler);
2347 }
2348 mH.removeMessages(H.PURGE_RESOURCES);
2349 }
2350
2351 void unschedulePurgeIdler() {
2352 if (mPurgeIdlerScheduled) {
2353 mPurgeIdlerScheduled = false;
2354 Looper.myQueue().removeIdleHandler(mPurgeIdler);
2355 }
2356 mH.removeMessages(H.PURGE_RESOURCES);
2357 }
2358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 void doGcIfNeeded() {
2360 mGcIdlerScheduled = false;
2361 final long now = SystemClock.uptimeMillis();
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002362 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 // + "m now=" + now);
2364 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002365 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 BinderInternal.forceGc("bg");
2367 }
2368 }
2369
Dianne Hackborne77187d2013-10-25 16:32:41 -07002370 private static final String HEAP_FULL_COLUMN
2371 = "%13s %8s %8s %8s %8s %8s %8s %8s %8s %8s %8s";
2372 private static final String HEAP_COLUMN
2373 = "%13s %8s %8s %8s %8s %8s %8s %8s";
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002374 private static final String ONE_COUNT_COLUMN = "%21s %8d";
2375 private static final String TWO_COUNT_COLUMNS = "%21s %8d %21s %8d";
2376 private static final String ONE_COUNT_COLUMN_HEADER = "%21s %8s";
Dianne Hackborne77187d2013-10-25 16:32:41 -07002377
2378 // Formatting for checkin service - update version if row format changes
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002379 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 4;
Dianne Hackborne77187d2013-10-25 16:32:41 -07002380
2381 static void printRow(PrintWriter pw, String format, Object...objs) {
2382 pw.println(String.format(format, objs));
2383 }
2384
2385 public static void dumpMemInfoTable(PrintWriter pw, Debug.MemoryInfo memInfo, boolean checkin,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002386 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
2387 int pid, String processName,
Dianne Hackborne77187d2013-10-25 16:32:41 -07002388 long nativeMax, long nativeAllocated, long nativeFree,
2389 long dalvikMax, long dalvikAllocated, long dalvikFree) {
2390
2391 // For checkin, we print one long comma-separated list of values
2392 if (checkin) {
2393 // NOTE: if you change anything significant below, also consider changing
2394 // ACTIVITY_THREAD_CHECKIN_VERSION.
2395
2396 // Header
2397 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
2398 pw.print(pid); pw.print(',');
2399 pw.print(processName); pw.print(',');
2400
2401 // Heap info - max
2402 pw.print(nativeMax); pw.print(',');
2403 pw.print(dalvikMax); pw.print(',');
2404 pw.print("N/A,");
2405 pw.print(nativeMax + dalvikMax); pw.print(',');
2406
2407 // Heap info - allocated
2408 pw.print(nativeAllocated); pw.print(',');
2409 pw.print(dalvikAllocated); pw.print(',');
2410 pw.print("N/A,");
2411 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
2412
2413 // Heap info - free
2414 pw.print(nativeFree); pw.print(',');
2415 pw.print(dalvikFree); pw.print(',');
2416 pw.print("N/A,");
2417 pw.print(nativeFree + dalvikFree); pw.print(',');
2418
2419 // Heap info - proportional set size
2420 pw.print(memInfo.nativePss); pw.print(',');
2421 pw.print(memInfo.dalvikPss); pw.print(',');
2422 pw.print(memInfo.otherPss); pw.print(',');
2423 pw.print(memInfo.getTotalPss()); pw.print(',');
2424
2425 // Heap info - swappable set size
2426 pw.print(memInfo.nativeSwappablePss); pw.print(',');
2427 pw.print(memInfo.dalvikSwappablePss); pw.print(',');
2428 pw.print(memInfo.otherSwappablePss); pw.print(',');
2429 pw.print(memInfo.getTotalSwappablePss()); pw.print(',');
2430
2431 // Heap info - shared dirty
2432 pw.print(memInfo.nativeSharedDirty); pw.print(',');
2433 pw.print(memInfo.dalvikSharedDirty); pw.print(',');
2434 pw.print(memInfo.otherSharedDirty); pw.print(',');
2435 pw.print(memInfo.getTotalSharedDirty()); pw.print(',');
2436
2437 // Heap info - shared clean
2438 pw.print(memInfo.nativeSharedClean); pw.print(',');
2439 pw.print(memInfo.dalvikSharedClean); pw.print(',');
2440 pw.print(memInfo.otherSharedClean); pw.print(',');
2441 pw.print(memInfo.getTotalSharedClean()); pw.print(',');
2442
2443 // Heap info - private Dirty
2444 pw.print(memInfo.nativePrivateDirty); pw.print(',');
2445 pw.print(memInfo.dalvikPrivateDirty); pw.print(',');
2446 pw.print(memInfo.otherPrivateDirty); pw.print(',');
2447 pw.print(memInfo.getTotalPrivateDirty()); pw.print(',');
2448
2449 // Heap info - private Clean
2450 pw.print(memInfo.nativePrivateClean); pw.print(',');
2451 pw.print(memInfo.dalvikPrivateClean); pw.print(',');
2452 pw.print(memInfo.otherPrivateClean); pw.print(',');
2453 pw.print(memInfo.getTotalPrivateClean()); pw.print(',');
2454
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002455 // Heap info - swapped out
2456 pw.print(memInfo.nativeSwappedOut); pw.print(',');
2457 pw.print(memInfo.dalvikSwappedOut); pw.print(',');
2458 pw.print(memInfo.otherSwappedOut); pw.print(',');
2459 pw.print(memInfo.getTotalSwappedOut()); pw.print(',');
2460
2461 // Heap info - swapped out pss
2462 if (memInfo.hasSwappedOutPss) {
2463 pw.print(memInfo.nativeSwappedOutPss); pw.print(',');
2464 pw.print(memInfo.dalvikSwappedOutPss); pw.print(',');
2465 pw.print(memInfo.otherSwappedOutPss); pw.print(',');
2466 pw.print(memInfo.getTotalSwappedOutPss()); pw.print(',');
2467 } else {
2468 pw.print("N/A,");
2469 pw.print("N/A,");
2470 pw.print("N/A,");
2471 pw.print("N/A,");
2472 }
2473
Dianne Hackborne77187d2013-10-25 16:32:41 -07002474 // Heap info - other areas
2475 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
2476 pw.print(Debug.MemoryInfo.getOtherLabel(i)); pw.print(',');
2477 pw.print(memInfo.getOtherPss(i)); pw.print(',');
2478 pw.print(memInfo.getOtherSwappablePss(i)); pw.print(',');
2479 pw.print(memInfo.getOtherSharedDirty(i)); pw.print(',');
2480 pw.print(memInfo.getOtherSharedClean(i)); pw.print(',');
2481 pw.print(memInfo.getOtherPrivateDirty(i)); pw.print(',');
2482 pw.print(memInfo.getOtherPrivateClean(i)); pw.print(',');
Martijn Coenen41f94ed2015-12-14 15:28:51 +01002483 pw.print(memInfo.getOtherSwappedOut(i)); pw.print(',');
2484 if (memInfo.hasSwappedOutPss) {
2485 pw.print(memInfo.getOtherSwappedOutPss(i)); pw.print(',');
2486 } else {
2487 pw.print("N/A,");
2488 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002489 }
2490 return;
2491 }
2492
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002493 if (!dumpSummaryOnly) {
2494 if (dumpFullInfo) {
2495 printRow(pw, HEAP_FULL_COLUMN, "", "Pss", "Pss", "Shared", "Private",
Martijn Coenene0764852016-01-07 17:04:22 -08002496 "Shared", "Private", memInfo.hasSwappedOutPss ? "SwapPss" : "Swap",
2497 "Heap", "Heap", "Heap");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002498 printRow(pw, HEAP_FULL_COLUMN, "", "Total", "Clean", "Dirty", "Dirty",
Martijn Coenene0764852016-01-07 17:04:22 -08002499 "Clean", "Clean", "Dirty",
2500 "Size", "Alloc", "Free");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002501 printRow(pw, HEAP_FULL_COLUMN, "", "------", "------", "------", "------",
2502 "------", "------", "------", "------", "------", "------");
2503 printRow(pw, HEAP_FULL_COLUMN, "Native Heap", memInfo.nativePss,
2504 memInfo.nativeSwappablePss, memInfo.nativeSharedDirty,
2505 memInfo.nativePrivateDirty, memInfo.nativeSharedClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002506 memInfo.nativePrivateClean, memInfo.hasSwappedOutPss ?
Richard Uhler91702eb32017-06-23 16:54:25 +01002507 memInfo.nativeSwappedOutPss : memInfo.nativeSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002508 nativeMax, nativeAllocated, nativeFree);
2509 printRow(pw, HEAP_FULL_COLUMN, "Dalvik Heap", memInfo.dalvikPss,
2510 memInfo.dalvikSwappablePss, memInfo.dalvikSharedDirty,
2511 memInfo.dalvikPrivateDirty, memInfo.dalvikSharedClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002512 memInfo.dalvikPrivateClean, memInfo.hasSwappedOutPss ?
Richard Uhler91702eb32017-06-23 16:54:25 +01002513 memInfo.dalvikSwappedOutPss : memInfo.dalvikSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002514 dalvikMax, dalvikAllocated, dalvikFree);
2515 } else {
2516 printRow(pw, HEAP_COLUMN, "", "Pss", "Private",
Martijn Coenene0764852016-01-07 17:04:22 -08002517 "Private", memInfo.hasSwappedOutPss ? "SwapPss" : "Swap",
2518 "Heap", "Heap", "Heap");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002519 printRow(pw, HEAP_COLUMN, "", "Total", "Dirty",
2520 "Clean", "Dirty", "Size", "Alloc", "Free");
2521 printRow(pw, HEAP_COLUMN, "", "------", "------", "------",
2522 "------", "------", "------", "------", "------");
2523 printRow(pw, HEAP_COLUMN, "Native Heap", memInfo.nativePss,
2524 memInfo.nativePrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002525 memInfo.nativePrivateClean,
2526 memInfo.hasSwappedOutPss ? memInfo.nativeSwappedOutPss :
2527 memInfo.nativeSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002528 nativeMax, nativeAllocated, nativeFree);
2529 printRow(pw, HEAP_COLUMN, "Dalvik Heap", memInfo.dalvikPss,
2530 memInfo.dalvikPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002531 memInfo.dalvikPrivateClean,
2532 memInfo.hasSwappedOutPss ? memInfo.dalvikSwappedOutPss :
2533 memInfo.dalvikSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002534 dalvikMax, dalvikAllocated, dalvikFree);
Dianne Hackborne77187d2013-10-25 16:32:41 -07002535 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002536
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002537 int otherPss = memInfo.otherPss;
2538 int otherSwappablePss = memInfo.otherSwappablePss;
2539 int otherSharedDirty = memInfo.otherSharedDirty;
2540 int otherPrivateDirty = memInfo.otherPrivateDirty;
2541 int otherSharedClean = memInfo.otherSharedClean;
2542 int otherPrivateClean = memInfo.otherPrivateClean;
2543 int otherSwappedOut = memInfo.otherSwappedOut;
Martijn Coenene0764852016-01-07 17:04:22 -08002544 int otherSwappedOutPss = memInfo.otherSwappedOutPss;
Dianne Hackborne77187d2013-10-25 16:32:41 -07002545
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002546 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
Dianne Hackborne77187d2013-10-25 16:32:41 -07002547 final int myPss = memInfo.getOtherPss(i);
2548 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2549 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2550 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2551 final int mySharedClean = memInfo.getOtherSharedClean(i);
2552 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2553 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
Martijn Coenene0764852016-01-07 17:04:22 -08002554 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Dianne Hackborne77187d2013-10-25 16:32:41 -07002555 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
Martijn Coenene0764852016-01-07 17:04:22 -08002556 || mySharedClean != 0 || myPrivateClean != 0
2557 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Dianne Hackborne77187d2013-10-25 16:32:41 -07002558 if (dumpFullInfo) {
2559 printRow(pw, HEAP_FULL_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2560 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002561 mySharedClean, myPrivateClean,
2562 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2563 "", "", "");
Dianne Hackborne77187d2013-10-25 16:32:41 -07002564 } else {
2565 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2566 myPss, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002567 myPrivateClean,
2568 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2569 "", "", "");
Dianne Hackborne77187d2013-10-25 16:32:41 -07002570 }
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002571 otherPss -= myPss;
2572 otherSwappablePss -= mySwappablePss;
2573 otherSharedDirty -= mySharedDirty;
2574 otherPrivateDirty -= myPrivateDirty;
2575 otherSharedClean -= mySharedClean;
2576 otherPrivateClean -= myPrivateClean;
2577 otherSwappedOut -= mySwappedOut;
Martijn Coenene0764852016-01-07 17:04:22 -08002578 otherSwappedOutPss -= mySwappedOutPss;
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002579 }
2580 }
2581
2582 if (dumpFullInfo) {
2583 printRow(pw, HEAP_FULL_COLUMN, "Unknown", otherPss, otherSwappablePss,
2584 otherSharedDirty, otherPrivateDirty, otherSharedClean, otherPrivateClean,
Martijn Coenene0764852016-01-07 17:04:22 -08002585 memInfo.hasSwappedOutPss ? otherSwappedOutPss : otherSwappedOut,
2586 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002587 printRow(pw, HEAP_FULL_COLUMN, "TOTAL", memInfo.getTotalPss(),
2588 memInfo.getTotalSwappablePss(),
2589 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
2590 memInfo.getTotalSharedClean(), memInfo.getTotalPrivateClean(),
Thierry Strudel9b511602016-02-25 17:46:38 -08002591 memInfo.hasSwappedOutPss ? memInfo.getTotalSwappedOutPss() :
2592 memInfo.getTotalSwappedOut(),
Martijn Coenene0764852016-01-07 17:04:22 -08002593 nativeMax+dalvikMax, nativeAllocated+dalvikAllocated,
2594 nativeFree+dalvikFree);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002595 } else {
2596 printRow(pw, HEAP_COLUMN, "Unknown", otherPss,
Martijn Coenene0764852016-01-07 17:04:22 -08002597 otherPrivateDirty, otherPrivateClean,
2598 memInfo.hasSwappedOutPss ? otherSwappedOutPss : otherSwappedOut,
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002599 "", "", "");
2600 printRow(pw, HEAP_COLUMN, "TOTAL", memInfo.getTotalPss(),
2601 memInfo.getTotalPrivateDirty(),
2602 memInfo.getTotalPrivateClean(),
Martijn Coenene0764852016-01-07 17:04:22 -08002603 memInfo.hasSwappedOutPss ? memInfo.getTotalSwappedOutPss() :
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002604 memInfo.getTotalSwappedOut(),
2605 nativeMax+dalvikMax,
2606 nativeAllocated+dalvikAllocated, nativeFree+dalvikFree);
2607 }
2608
2609 if (dumpDalvik) {
2610 pw.println(" ");
2611 pw.println(" Dalvik Details");
2612
2613 for (int i=Debug.MemoryInfo.NUM_OTHER_STATS;
2614 i<Debug.MemoryInfo.NUM_OTHER_STATS + Debug.MemoryInfo.NUM_DVK_STATS; i++) {
2615 final int myPss = memInfo.getOtherPss(i);
2616 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2617 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2618 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2619 final int mySharedClean = memInfo.getOtherSharedClean(i);
2620 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2621 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
Martijn Coenene0764852016-01-07 17:04:22 -08002622 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002623 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
Martijn Coenene0764852016-01-07 17:04:22 -08002624 || mySharedClean != 0 || myPrivateClean != 0
2625 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002626 if (dumpFullInfo) {
2627 printRow(pw, HEAP_FULL_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2628 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002629 mySharedClean, myPrivateClean,
2630 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2631 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002632 } else {
2633 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
2634 myPss, myPrivateDirty,
Martijn Coenene0764852016-01-07 17:04:22 -08002635 myPrivateClean,
2636 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
2637 "", "", "");
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002638 }
2639 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002640 }
2641 }
2642 }
Richard Uhlerc14b9cf2015-03-13 12:38:38 -07002643
2644 pw.println(" ");
2645 pw.println(" App Summary");
2646 printRow(pw, ONE_COUNT_COLUMN_HEADER, "", "Pss(KB)");
2647 printRow(pw, ONE_COUNT_COLUMN_HEADER, "", "------");
2648 printRow(pw, ONE_COUNT_COLUMN,
2649 "Java Heap:", memInfo.getSummaryJavaHeap());
2650 printRow(pw, ONE_COUNT_COLUMN,
2651 "Native Heap:", memInfo.getSummaryNativeHeap());
2652 printRow(pw, ONE_COUNT_COLUMN,
2653 "Code:", memInfo.getSummaryCode());
2654 printRow(pw, ONE_COUNT_COLUMN,
2655 "Stack:", memInfo.getSummaryStack());
2656 printRow(pw, ONE_COUNT_COLUMN,
2657 "Graphics:", memInfo.getSummaryGraphics());
2658 printRow(pw, ONE_COUNT_COLUMN,
2659 "Private Other:", memInfo.getSummaryPrivateOther());
2660 printRow(pw, ONE_COUNT_COLUMN,
2661 "System:", memInfo.getSummarySystem());
2662 pw.println(" ");
Martijn Coenene0764852016-01-07 17:04:22 -08002663 if (memInfo.hasSwappedOutPss) {
2664 printRow(pw, TWO_COUNT_COLUMNS,
2665 "TOTAL:", memInfo.getSummaryTotalPss(),
2666 "TOTAL SWAP PSS:", memInfo.getSummaryTotalSwapPss());
2667 } else {
2668 printRow(pw, TWO_COUNT_COLUMNS,
2669 "TOTAL:", memInfo.getSummaryTotalPss(),
2670 "TOTAL SWAP (KB):", memInfo.getSummaryTotalSwap());
2671 }
Dianne Hackborne77187d2013-10-25 16:32:41 -07002672 }
2673
Kweku Adams598e9a22017-11-02 17:12:20 -07002674 /**
2675 * Dump heap info to proto.
2676 *
2677 * @param hasSwappedOutPss determines whether to use dirtySwap or dirtySwapPss
2678 */
Kweku Adams983829f2017-12-06 14:53:50 -08002679 private static void dumpMemoryInfo(ProtoOutputStream proto, long fieldId, String name,
Kweku Adams598e9a22017-11-02 17:12:20 -07002680 int pss, int cleanPss, int sharedDirty, int privateDirty,
2681 int sharedClean, int privateClean,
2682 boolean hasSwappedOutPss, int dirtySwap, int dirtySwapPss) {
2683 final long token = proto.start(fieldId);
2684
Yi Jin2b30f322018-02-20 15:41:47 -08002685 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.NAME, name);
2686 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.TOTAL_PSS_KB, pss);
2687 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.CLEAN_PSS_KB, cleanPss);
2688 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.SHARED_DIRTY_KB, sharedDirty);
2689 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.PRIVATE_DIRTY_KB, privateDirty);
2690 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.SHARED_CLEAN_KB, sharedClean);
2691 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.PRIVATE_CLEAN_KB, privateClean);
Kweku Adams598e9a22017-11-02 17:12:20 -07002692 if (hasSwappedOutPss) {
Yi Jin2b30f322018-02-20 15:41:47 -08002693 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.DIRTY_SWAP_PSS_KB, dirtySwapPss);
Kweku Adams598e9a22017-11-02 17:12:20 -07002694 } else {
Yi Jin2b30f322018-02-20 15:41:47 -08002695 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.DIRTY_SWAP_KB, dirtySwap);
Kweku Adams598e9a22017-11-02 17:12:20 -07002696 }
2697
2698 proto.end(token);
2699 }
2700
2701 /**
2702 * Dump mem info data to proto.
2703 */
2704 public static void dumpMemInfoTable(ProtoOutputStream proto, Debug.MemoryInfo memInfo,
2705 boolean dumpDalvik, boolean dumpSummaryOnly,
2706 long nativeMax, long nativeAllocated, long nativeFree,
2707 long dalvikMax, long dalvikAllocated, long dalvikFree) {
2708
2709 if (!dumpSummaryOnly) {
Yi Jin2b30f322018-02-20 15:41:47 -08002710 final long nhToken = proto.start(MemInfoDumpProto.ProcessMemory.NATIVE_HEAP);
2711 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "Native Heap",
Kweku Adams598e9a22017-11-02 17:12:20 -07002712 memInfo.nativePss, memInfo.nativeSwappablePss, memInfo.nativeSharedDirty,
2713 memInfo.nativePrivateDirty, memInfo.nativeSharedClean,
2714 memInfo.nativePrivateClean, memInfo.hasSwappedOutPss,
2715 memInfo.nativeSwappedOut, memInfo.nativeSwappedOutPss);
Yi Jin2b30f322018-02-20 15:41:47 -08002716 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB, nativeMax);
2717 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB, nativeAllocated);
2718 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB, nativeFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002719 proto.end(nhToken);
2720
Yi Jin2b30f322018-02-20 15:41:47 -08002721 final long dvToken = proto.start(MemInfoDumpProto.ProcessMemory.DALVIK_HEAP);
2722 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "Dalvik Heap",
Kweku Adams598e9a22017-11-02 17:12:20 -07002723 memInfo.dalvikPss, memInfo.dalvikSwappablePss, memInfo.dalvikSharedDirty,
2724 memInfo.dalvikPrivateDirty, memInfo.dalvikSharedClean,
2725 memInfo.dalvikPrivateClean, memInfo.hasSwappedOutPss,
2726 memInfo.dalvikSwappedOut, memInfo.dalvikSwappedOutPss);
Yi Jin2b30f322018-02-20 15:41:47 -08002727 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB, dalvikMax);
2728 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB, dalvikAllocated);
2729 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB, dalvikFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002730 proto.end(dvToken);
2731
2732 int otherPss = memInfo.otherPss;
2733 int otherSwappablePss = memInfo.otherSwappablePss;
2734 int otherSharedDirty = memInfo.otherSharedDirty;
2735 int otherPrivateDirty = memInfo.otherPrivateDirty;
2736 int otherSharedClean = memInfo.otherSharedClean;
2737 int otherPrivateClean = memInfo.otherPrivateClean;
2738 int otherSwappedOut = memInfo.otherSwappedOut;
2739 int otherSwappedOutPss = memInfo.otherSwappedOutPss;
2740
2741 for (int i = 0; i < Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
2742 final int myPss = memInfo.getOtherPss(i);
2743 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2744 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2745 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2746 final int mySharedClean = memInfo.getOtherSharedClean(i);
2747 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2748 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
2749 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
2750 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
2751 || mySharedClean != 0 || myPrivateClean != 0
2752 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Yi Jin2b30f322018-02-20 15:41:47 -08002753 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.OTHER_HEAPS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002754 Debug.MemoryInfo.getOtherLabel(i),
2755 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
2756 mySharedClean, myPrivateClean,
2757 memInfo.hasSwappedOutPss, mySwappedOut, mySwappedOutPss);
2758
2759 otherPss -= myPss;
2760 otherSwappablePss -= mySwappablePss;
2761 otherSharedDirty -= mySharedDirty;
2762 otherPrivateDirty -= myPrivateDirty;
2763 otherSharedClean -= mySharedClean;
2764 otherPrivateClean -= myPrivateClean;
2765 otherSwappedOut -= mySwappedOut;
2766 otherSwappedOutPss -= mySwappedOutPss;
2767 }
2768 }
2769
Yi Jin2b30f322018-02-20 15:41:47 -08002770 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.UNKNOWN_HEAP, "Unknown",
Kweku Adams598e9a22017-11-02 17:12:20 -07002771 otherPss, otherSwappablePss,
2772 otherSharedDirty, otherPrivateDirty, otherSharedClean, otherPrivateClean,
2773 memInfo.hasSwappedOutPss, otherSwappedOut, otherSwappedOutPss);
Yi Jin2b30f322018-02-20 15:41:47 -08002774 final long tToken = proto.start(MemInfoDumpProto.ProcessMemory.TOTAL_HEAP);
2775 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "TOTAL",
Kweku Adams598e9a22017-11-02 17:12:20 -07002776 memInfo.getTotalPss(), memInfo.getTotalSwappablePss(),
2777 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
2778 memInfo.getTotalSharedClean(), memInfo.getTotalPrivateClean(),
2779 memInfo.hasSwappedOutPss, memInfo.getTotalSwappedOut(),
2780 memInfo.getTotalSwappedOutPss());
Yi Jin2b30f322018-02-20 15:41:47 -08002781 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB,
2782 nativeMax + dalvikMax);
2783 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002784 nativeAllocated + dalvikAllocated);
Yi Jin2b30f322018-02-20 15:41:47 -08002785 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB,
2786 nativeFree + dalvikFree);
Kweku Adams598e9a22017-11-02 17:12:20 -07002787 proto.end(tToken);
2788
2789 if (dumpDalvik) {
2790 for (int i = Debug.MemoryInfo.NUM_OTHER_STATS;
2791 i < Debug.MemoryInfo.NUM_OTHER_STATS + Debug.MemoryInfo.NUM_DVK_STATS;
2792 i++) {
2793 final int myPss = memInfo.getOtherPss(i);
2794 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
2795 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
2796 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
2797 final int mySharedClean = memInfo.getOtherSharedClean(i);
2798 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
2799 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
2800 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
2801 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
2802 || mySharedClean != 0 || myPrivateClean != 0
2803 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
Yi Jin2b30f322018-02-20 15:41:47 -08002804 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.DALVIK_DETAILS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002805 Debug.MemoryInfo.getOtherLabel(i),
2806 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
2807 mySharedClean, myPrivateClean,
2808 memInfo.hasSwappedOutPss, mySwappedOut, mySwappedOutPss);
2809 }
2810 }
2811 }
2812 }
2813
Yi Jin2b30f322018-02-20 15:41:47 -08002814 final long asToken = proto.start(MemInfoDumpProto.ProcessMemory.APP_SUMMARY);
2815 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.JAVA_HEAP_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002816 memInfo.getSummaryJavaHeap());
Yi Jin2b30f322018-02-20 15:41:47 -08002817 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.NATIVE_HEAP_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002818 memInfo.getSummaryNativeHeap());
Yi Jin2b30f322018-02-20 15:41:47 -08002819 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.CODE_PSS_KB,
2820 memInfo.getSummaryCode());
2821 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.STACK_PSS_KB,
2822 memInfo.getSummaryStack());
2823 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.GRAPHICS_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002824 memInfo.getSummaryGraphics());
Yi Jin2b30f322018-02-20 15:41:47 -08002825 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.PRIVATE_OTHER_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002826 memInfo.getSummaryPrivateOther());
Yi Jin2b30f322018-02-20 15:41:47 -08002827 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.SYSTEM_PSS_KB,
Kweku Adams598e9a22017-11-02 17:12:20 -07002828 memInfo.getSummarySystem());
2829 if (memInfo.hasSwappedOutPss) {
Yi Jin2b30f322018-02-20 15:41:47 -08002830 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.TOTAL_SWAP_PSS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002831 memInfo.getSummaryTotalSwapPss());
2832 } else {
Yi Jin2b30f322018-02-20 15:41:47 -08002833 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.TOTAL_SWAP_PSS,
Kweku Adams598e9a22017-11-02 17:12:20 -07002834 memInfo.getSummaryTotalSwap());
2835 }
2836 proto.end(asToken);
2837 }
2838
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002839 @UnsupportedAppUsage
Jeff Hamilton52d32032011-01-08 15:31:26 -06002840 public void registerOnActivityPausedListener(Activity activity,
2841 OnActivityPausedListener listener) {
2842 synchronized (mOnPauseListeners) {
2843 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
2844 if (list == null) {
2845 list = new ArrayList<OnActivityPausedListener>();
2846 mOnPauseListeners.put(activity, list);
2847 }
2848 list.add(listener);
2849 }
2850 }
2851
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002852 @UnsupportedAppUsage
Jeff Hamiltonce3224c2011-01-17 11:05:03 -08002853 public void unregisterOnActivityPausedListener(Activity activity,
2854 OnActivityPausedListener listener) {
2855 synchronized (mOnPauseListeners) {
2856 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
2857 if (list != null) {
2858 list.remove(listener);
2859 }
2860 }
2861 }
2862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 public final ActivityInfo resolveActivityInfo(Intent intent) {
2864 ActivityInfo aInfo = intent.resolveActivityInfo(
2865 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
2866 if (aInfo == null) {
2867 // Throw an exception.
2868 Instrumentation.checkStartActivityResult(
Dianne Hackborna4972e92012-03-14 10:38:05 -07002869 ActivityManager.START_CLASS_NOT_FOUND, intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 }
2871 return aInfo;
2872 }
Bob Leee5408332009-09-04 18:31:17 -07002873
Mathew Inwood8c854f82018-09-14 12:35:36 +01002874 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002875 public final Activity startActivityNow(Activity parent, String id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002877 Activity.NonConfigurationInstances lastNonConfigurationInstances) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002878 ActivityClientRecord r = new ActivityClientRecord();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 r.token = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002880 r.ident = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 r.intent = intent;
2882 r.state = state;
2883 r.parent = parent;
2884 r.embeddedID = id;
2885 r.activityInfo = activityInfo;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002886 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 if (localLOGV) {
2888 ComponentName compname = intent.getComponent();
2889 String name;
2890 if (compname != null) {
2891 name = compname.toShortString();
2892 } else {
2893 name = "(Intent " + intent + ").getComponent() returned null";
2894 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002895 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896 + ", comp=" + name
2897 + ", token=" + token);
2898 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002899 // TODO(lifecycler): Can't switch to use #handleLaunchActivity() because it will try to
2900 // call #reportSizeConfigurations(), but the server might not know anything about the
2901 // activity if it was launched from LocalAcvitivyManager.
Andrii Kulian770c4032018-05-02 18:40:59 -07002902 return performLaunchActivity(r, null /* customIntent */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 }
2904
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002905 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 public final Activity getActivity(IBinder token) {
Andrii Kuliand56ed0c2018-06-14 12:22:18 -07002907 final ActivityClientRecord activityRecord = mActivities.get(token);
2908 return activityRecord != null ? activityRecord.activity : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 }
2910
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002911 @Override
2912 public ActivityClientRecord getActivityClient(IBinder token) {
2913 return mActivities.get(token);
2914 }
2915
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002916 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 public final void sendActivityResult(
2918 IBinder token, String id, int requestCode,
2919 int resultCode, Intent data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07002920 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
Chris Tate8a7dc172009-03-24 20:11:42 -07002921 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2923 list.add(new ResultInfo(id, requestCode, resultCode, data));
Andrii Kulian9c5ea9c2017-12-07 09:31:01 -08002924 final ClientTransaction clientTransaction = ClientTransaction.obtain(mAppThread, token);
2925 clientTransaction.addCallback(ActivityResultItem.obtain(list));
Andrii Kulian446e8242017-10-26 15:17:29 -07002926 try {
2927 mAppThread.scheduleTransaction(clientTransaction);
2928 } catch (RemoteException e) {
2929 // Local scheduling
2930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 }
2932
Andrii Kulian914aa7d2018-03-19 21:51:53 -07002933 @Override
2934 TransactionExecutor getTransactionExecutor() {
2935 return mTransactionExecutor;
2936 }
2937
Andrii Kulian446e8242017-10-26 15:17:29 -07002938 void sendMessage(int what, Object obj) {
Jeff Brown9ef09972013-10-15 20:49:59 -07002939 sendMessage(what, obj, 0, 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 }
2941
Jeff Brown9ef09972013-10-15 20:49:59 -07002942 private void sendMessage(int what, Object obj, int arg1) {
2943 sendMessage(what, obj, arg1, 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 }
2945
Jeff Brown9ef09972013-10-15 20:49:59 -07002946 private void sendMessage(int what, Object obj, int arg1, int arg2) {
2947 sendMessage(what, obj, arg1, arg2, false);
2948 }
2949
2950 private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
2951 if (DEBUG_MESSAGES) Slog.v(
2952 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
2953 + ": " + arg1 + " / " + obj);
2954 Message msg = Message.obtain();
2955 msg.what = what;
2956 msg.obj = obj;
2957 msg.arg1 = arg1;
2958 msg.arg2 = arg2;
2959 if (async) {
2960 msg.setAsynchronous(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002961 }
Jeff Brown9ef09972013-10-15 20:49:59 -07002962 mH.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002963 }
2964
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07002965 private void sendMessage(int what, Object obj, int arg1, int arg2, int seq) {
2966 if (DEBUG_MESSAGES) Slog.v(
2967 TAG, "SCHEDULE " + mH.codeToString(what) + " arg1=" + arg1 + " arg2=" + arg2 +
2968 "seq= " + seq);
2969 Message msg = Message.obtain();
2970 msg.what = what;
2971 SomeArgs args = SomeArgs.obtain();
2972 args.arg1 = obj;
2973 args.argi1 = arg1;
2974 args.argi2 = arg2;
2975 args.argi3 = seq;
2976 msg.obj = args;
2977 mH.sendMessage(msg);
2978 }
2979
Dianne Hackborn21556372010-02-04 16:34:40 -08002980 final void scheduleContextCleanup(ContextImpl context, String who,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002981 String what) {
2982 ContextCleanupInfo cci = new ContextCleanupInfo();
2983 cci.context = context;
2984 cci.who = who;
2985 cci.what = what;
Jeff Brown9ef09972013-10-15 20:49:59 -07002986 sendMessage(H.CLEAN_UP_CONTEXT, cci);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002987 }
2988
Andrii Kulian88e05cb2017-12-05 17:21:10 -08002989 /** Core implementation of activity launch. */
Andrii Kulian770c4032018-05-02 18:40:59 -07002990 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 ActivityInfo aInfo = r.activityInfo;
Todd Kennedy233a0b12018-01-29 20:30:24 +00002992 if (r.packageInfo == null) {
2993 r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002994 Context.CONTEXT_INCLUDE_CODE);
2995 }
Bob Leee5408332009-09-04 18:31:17 -07002996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002997 ComponentName component = r.intent.getComponent();
2998 if (component == null) {
2999 component = r.intent.resolveActivity(
3000 mInitialApplication.getPackageManager());
3001 r.intent.setComponent(component);
3002 }
3003
3004 if (r.activityInfo.targetActivity != null) {
3005 component = new ComponentName(r.activityInfo.packageName,
3006 r.activityInfo.targetActivity);
3007 }
3008
Adam Lesinski4e862812016-11-21 16:02:24 -08003009 ContextImpl appContext = createBaseContextForActivity(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003010 Activity activity = null;
3011 try {
Adam Lesinski4e862812016-11-21 16:02:24 -08003012 java.lang.ClassLoader cl = appContext.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04003013 activity = mInstrumentation.newActivity(
3014 cl, component.getClassName(), r.intent);
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08003015 StrictMode.incrementExpectedActivityCount(activity.getClass());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016 r.intent.setExtrasClassLoader(cl);
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003017 r.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003018 if (r.state != null) {
3019 r.state.setClassLoader(cl);
3020 }
3021 } catch (Exception e) {
3022 if (!mInstrumentation.onException(activity, e)) {
3023 throw new RuntimeException(
3024 "Unable to instantiate activity " + component
3025 + ": " + e.toString(), e);
3026 }
3027 }
3028
3029 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00003030 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
Bob Leee5408332009-09-04 18:31:17 -07003031
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003032 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
3033 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003034 TAG, r + ": app=" + app
3035 + ", appName=" + app.getPackageName()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003036 + ", pkg=" + r.packageInfo.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003037 + ", comp=" + r.intent.getComponent().toShortString()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003038 + ", dir=" + r.packageInfo.getAppDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003039
3040 if (activity != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003041 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003042 Configuration config = new Configuration(mCompatConfiguration);
Andrii Kuliand0ad9382016-04-18 20:54:20 -07003043 if (r.overrideConfig != null) {
3044 config.updateFrom(r.overrideConfig);
3045 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003046 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003047 + r.activityInfo.name + " with config " + config);
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003048 Window window = null;
3049 if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
3050 window = r.mPendingRemoveWindow;
3051 r.mPendingRemoveWindow = null;
3052 r.mPendingRemoveWindowManager = null;
3053 }
Adam Lesinski4e862812016-11-21 16:02:24 -08003054 appContext.setOuterContext(activity);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003055 activity.attach(appContext, this, getInstrumentation(), r.token,
3056 r.ident, app, r.intent, r.activityInfo, title, r.parent,
Craig Mautner233ceee2014-05-09 17:05:11 -07003057 r.embeddedID, r.lastNonConfigurationInstances, config,
Andrii Kulian51c1b672017-04-07 18:39:32 -07003058 r.referrer, r.voiceInteractor, window, r.configCallback);
Bob Leee5408332009-09-04 18:31:17 -07003059
Andrii Kulian770c4032018-05-02 18:40:59 -07003060 if (customIntent != null) {
3061 activity.mIntent = customIntent;
3062 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003063 r.lastNonConfigurationInstances = null;
Sudheer Shanka84a48952017-03-08 18:19:01 -08003064 checkAndBlockForNetworkAccess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 activity.mStartedActivity = false;
3066 int theme = r.activityInfo.getThemeResource();
3067 if (theme != 0) {
3068 activity.setTheme(theme);
3069 }
3070
3071 activity.mCalled = false;
Craig Mautnera0026042014-04-23 11:45:37 -07003072 if (r.isPersistable()) {
3073 mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
3074 } else {
3075 mInstrumentation.callActivityOnCreate(activity, r.state);
3076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003077 if (!activity.mCalled) {
3078 throw new SuperNotCalledException(
3079 "Activity " + r.intent.getComponent().toShortString() +
3080 " did not call through to super.onCreate()");
3081 }
3082 r.activity = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003083 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003084 r.setState(ON_CREATE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003085
Garfield Tan0443b372019-01-04 15:00:13 -08003086 // updatePendingActivityConfiguration() reads from mActivities to update
3087 // ActivityClientRecord which runs in a different thread. Protect modifications to
3088 // mActivities to avoid race.
3089 synchronized (mResourcesManager) {
3090 mActivities.put(r.token, r);
3091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092
3093 } catch (SuperNotCalledException e) {
3094 throw e;
3095
3096 } catch (Exception e) {
3097 if (!mInstrumentation.onException(activity, e)) {
3098 throw new RuntimeException(
3099 "Unable to start activity " + component
3100 + ": " + e.toString(), e);
3101 }
3102 }
3103
3104 return activity;
3105 }
3106
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003107 @Override
3108 public void handleStartActivity(ActivityClientRecord r,
3109 PendingTransactionActions pendingActions) {
3110 final Activity activity = r.activity;
3111 if (r.activity == null) {
3112 // TODO(lifecycler): What do we do in this case?
3113 return;
3114 }
3115 if (!r.stopped) {
3116 throw new IllegalStateException("Can't start activity that is not stopped.");
3117 }
Andrii Kulianc10482f2019-03-07 18:09:28 +00003118 if (r.activity.mFinished) {
3119 // TODO(lifecycler): How can this happen?
3120 return;
3121 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003122
3123 // Start
Andrii Kuliand25680c2018-02-21 15:16:58 -08003124 activity.performStart("handleStartActivity");
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003125 r.setState(ON_START);
3126
3127 if (pendingActions == null) {
3128 // No more work to do.
3129 return;
3130 }
3131
3132 // Restore instance state
3133 if (pendingActions.shouldRestoreInstanceState()) {
3134 if (r.isPersistable()) {
3135 if (r.state != null || r.persistentState != null) {
3136 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
3137 r.persistentState);
3138 }
3139 } else if (r.state != null) {
3140 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
3141 }
3142 }
3143
3144 // Call postOnCreate()
3145 if (pendingActions.shouldCallOnPostCreate()) {
3146 activity.mCalled = false;
3147 if (r.isPersistable()) {
3148 mInstrumentation.callActivityOnPostCreate(activity, r.state,
3149 r.persistentState);
3150 } else {
3151 mInstrumentation.callActivityOnPostCreate(activity, r.state);
3152 }
3153 if (!activity.mCalled) {
3154 throw new SuperNotCalledException(
3155 "Activity " + r.intent.getComponent().toShortString()
3156 + " did not call through to super.onPostCreate()");
3157 }
3158 }
3159 }
3160
Sudheer Shanka84a48952017-03-08 18:19:01 -08003161 /**
3162 * Checks if {@link #mNetworkBlockSeq} is {@link #INVALID_PROC_STATE_SEQ} and if so, returns
3163 * immediately. Otherwise, makes a blocking call to ActivityManagerService to wait for the
3164 * network rules to get updated.
3165 */
3166 private void checkAndBlockForNetworkAccess() {
3167 synchronized (mNetworkPolicyLock) {
3168 if (mNetworkBlockSeq != INVALID_PROC_STATE_SEQ) {
3169 try {
3170 ActivityManager.getService().waitForNetworkStateUpdate(mNetworkBlockSeq);
3171 mNetworkBlockSeq = INVALID_PROC_STATE_SEQ;
3172 } catch (RemoteException ignored) {}
3173 }
3174 }
3175 }
3176
Adam Lesinski4e862812016-11-21 16:02:24 -08003177 private ContextImpl createBaseContextForActivity(ActivityClientRecord r) {
3178 final int displayId;
Craig Mautnere0a38842013-12-16 16:14:02 -08003179 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003180 displayId = ActivityTaskManager.getService().getActivityDisplayId(r.token);
Craig Mautnere0a38842013-12-16 16:14:02 -08003181 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003182 throw e.rethrowFromSystemServer();
Craig Mautnere0a38842013-12-16 16:14:02 -08003183 }
Jeff Brownefd43bd2012-09-21 17:02:35 -07003184
Wale Ogunwale7c726682015-02-06 17:34:28 -08003185 ContextImpl appContext = ContextImpl.createActivityContext(
Todd Kennedy233a0b12018-01-29 20:30:24 +00003186 this, r.packageInfo, r.activityInfo, r.token, displayId, r.overrideConfig);
Wale Ogunwale7c726682015-02-06 17:34:28 -08003187
3188 final DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance();
Jeff Brownefd43bd2012-09-21 17:02:35 -07003189 // For debugging purposes, if the activity's package name contains the value of
3190 // the "debug.use-second-display" system property as a substring, then show
3191 // its content on a secondary display if there is one.
Jeff Brownefd43bd2012-09-21 17:02:35 -07003192 String pkgName = SystemProperties.get("debug.second-display.pkg");
3193 if (pkgName != null && !pkgName.isEmpty()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003194 && r.packageInfo.mPackageName.contains(pkgName)) {
Wale Ogunwale7c726682015-02-06 17:34:28 -08003195 for (int id : dm.getDisplayIds()) {
3196 if (id != Display.DEFAULT_DISPLAY) {
Wale Ogunwale26698512015-06-05 16:55:33 -07003197 Display display =
Bryce Lee609bf652017-02-09 16:50:13 -08003198 dm.getCompatibleDisplay(id, appContext.getResources());
Adam Lesinski4e862812016-11-21 16:02:24 -08003199 appContext = (ContextImpl) appContext.createDisplayContext(display);
Jeff Brownefd43bd2012-09-21 17:02:35 -07003200 break;
3201 }
3202 }
3203 }
Adam Lesinski4e862812016-11-21 16:02:24 -08003204 return appContext;
Jeff Brownefd43bd2012-09-21 17:02:35 -07003205 }
3206
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003207 /**
3208 * Extended implementation of activity launch. Used when server requests a launch or relaunch.
3209 */
Andrii Kulian446e8242017-10-26 15:17:29 -07003210 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003211 public Activity handleLaunchActivity(ActivityClientRecord r,
Andrii Kulian770c4032018-05-02 18:40:59 -07003212 PendingTransactionActions pendingActions, Intent customIntent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213 // If we are getting ready to gc after going to the background, well
3214 // we are back active so skip it.
3215 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003216 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003217
Jeff Hao1b012d32014-08-20 10:35:34 -07003218 if (r.profilerInfo != null) {
3219 mProfiler.setProfiler(r.profilerInfo);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07003220 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003221 }
3222
Dianne Hackborn58f42a52011-10-10 13:46:34 -07003223 // Make sure we are running with the most recent config.
3224 handleConfigurationChanged(null, null);
3225
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003226 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003227 TAG, "Handling launch of " + r);
Adam Powellcfbe9be2013-11-06 14:58:58 -08003228
Chet Haase0d1c27a2014-11-03 18:35:16 +00003229 // Initialize before creating the activity
Stan Iliev898123b2019-02-14 14:57:44 -05003230 if (!ThreadedRenderer.sRendererDisabled
3231 && (r.activityInfo.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
3232 HardwareRenderer.preload();
Jesse Hallc37984f2017-05-23 16:55:08 -07003233 }
Chet Haase0d1c27a2014-11-03 18:35:16 +00003234 WindowManagerGlobal.initialize();
3235
Andrii Kulian770c4032018-05-02 18:40:59 -07003236 final Activity a = performLaunchActivity(r, customIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003237
3238 if (a != null) {
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08003239 r.createdConfig = new Configuration(mConfiguration);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003240 reportSizeConfigurations(r);
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003241 if (!r.activity.mFinished && pendingActions != null) {
3242 pendingActions.setOldState(r.state);
3243 pendingActions.setRestoreInstanceState(true);
3244 pendingActions.setCallOnPostCreate(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003245 }
3246 } else {
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07003247 // 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 -08003248 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003249 ActivityTaskManager.getService()
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003250 .finishActivity(r.token, Activity.RESULT_CANCELED, null,
3251 Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003252 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003253 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 }
3255 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08003256
3257 return a;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258 }
3259
Filip Gruszczynski23493322015-07-29 17:02:59 -07003260 private void reportSizeConfigurations(ActivityClientRecord r) {
Riddle Hsu66b74a82018-07-26 00:20:12 +08003261 if (mActivitiesToBeDestroyed.containsKey(r.token)) {
3262 // Size configurations of a destroyed activity is meaningless.
3263 return;
3264 }
Filip Gruszczynski23493322015-07-29 17:02:59 -07003265 Configuration[] configurations = r.activity.getResources().getSizeConfigurations();
3266 if (configurations == null) {
3267 return;
3268 }
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003269 SparseIntArray horizontal = new SparseIntArray();
3270 SparseIntArray vertical = new SparseIntArray();
3271 SparseIntArray smallest = new SparseIntArray();
Filip Gruszczynski23493322015-07-29 17:02:59 -07003272 for (int i = configurations.length - 1; i >= 0; i--) {
3273 Configuration config = configurations[i];
3274 if (config.screenHeightDp != Configuration.SCREEN_HEIGHT_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003275 vertical.put(config.screenHeightDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003276 }
3277 if (config.screenWidthDp != Configuration.SCREEN_WIDTH_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003278 horizontal.put(config.screenWidthDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003279 }
3280 if (config.smallestScreenWidthDp != Configuration.SMALLEST_SCREEN_WIDTH_DP_UNDEFINED) {
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003281 smallest.put(config.smallestScreenWidthDp, 0);
Filip Gruszczynski23493322015-07-29 17:02:59 -07003282 }
3283 }
Filip Gruszczynski23493322015-07-29 17:02:59 -07003284 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003285 ActivityTaskManager.getService().reportSizeConfigurations(r.token,
Filip Gruszczynski20aa0ae2015-10-30 10:08:27 -07003286 horizontal.copyKeys(), vertical.copyKeys(), smallest.copyKeys());
Filip Gruszczynski23493322015-07-29 17:02:59 -07003287 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003288 throw ex.rethrowFromSystemServer();
Filip Gruszczynski23493322015-07-29 17:02:59 -07003289 }
3290
3291 }
3292
Dianne Hackborn85d558c2014-11-04 10:31:54 -08003293 private void deliverNewIntents(ActivityClientRecord r, List<ReferrerIntent> intents) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294 final int N = intents.size();
3295 for (int i=0; i<N; i++) {
Dianne Hackborna01a0fa2014-12-02 10:33:14 -08003296 ReferrerIntent intent = intents.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 intent.setExtrasClassLoader(r.activity.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003298 intent.prepareToEnterProcess();
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07003299 r.activity.mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
3301 }
3302 }
3303
Mathew Inwood61e8ae62018-08-14 14:17:44 +01003304 @UnsupportedAppUsage
Wale Ogunwale826c7062016-09-13 08:25:54 -07003305 void performNewIntents(IBinder token, List<ReferrerIntent> intents, boolean andPause) {
3306 final ActivityClientRecord r = mActivities.get(token);
3307 if (r == null) {
3308 return;
3309 }
3310
3311 final boolean resumed = !r.paused;
3312 if (resumed) {
3313 r.activity.mTemporaryPause = true;
Andrii Kuliand70cdb92019-01-08 15:03:50 -08003314 performPauseActivityIfNeeded(r, "performNewIntents");
Wale Ogunwale826c7062016-09-13 08:25:54 -07003315 }
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07003316 checkAndBlockForNetworkAccess();
Wale Ogunwale826c7062016-09-13 08:25:54 -07003317 deliverNewIntents(r, intents);
3318 if (resumed) {
Andrii Kuliand70cdb92019-01-08 15:03:50 -08003319 performResumeActivity(token, false, "performNewIntents");
Wale Ogunwale826c7062016-09-13 08:25:54 -07003320 r.activity.mTemporaryPause = false;
Andrii Kuliand70cdb92019-01-08 15:03:50 -08003321 } else if (andPause) {
Wale Ogunwale826c7062016-09-13 08:25:54 -07003322 // In this case the activity was in the paused state when we delivered the intent,
3323 // to guarantee onResume gets called after onNewIntent we temporarily resume the
3324 // activity and pause again as the caller wanted.
3325 performResumeActivity(token, false, "performNewIntents");
3326 performPauseActivityIfNeeded(r, "performNewIntents");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327 }
3328 }
Bob Leee5408332009-09-04 18:31:17 -07003329
Andrii Kulian446e8242017-10-26 15:17:29 -07003330 @Override
3331 public void handleNewIntent(IBinder token, List<ReferrerIntent> intents, boolean andPause) {
3332 performNewIntents(token, intents, andPause);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 }
3334
Adam Skorydfc7fd72013-08-05 19:23:41 -07003335 public void handleRequestAssistContextExtras(RequestAssistContextExtras cmd) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003336 // Filling for autofill has a few differences:
Felipe Leme1ca634a2016-11-28 17:21:21 -08003337 // - it does not need an AssistContent
3338 // - it does not call onProvideAssistData()
3339 // - it needs an IAutoFillCallback
Felipe Leme640f30a2017-03-06 15:44:06 -08003340 boolean forAutofill = cmd.requestType == ActivityManager.ASSIST_CONTEXT_AUTOFILL;
Felipe Leme1ca634a2016-11-28 17:21:21 -08003341
Felipe Leme85d1c2d2017-04-21 08:56:04 -07003342 // TODO: decide if lastSessionId logic applies to autofill sessions
Amith Yamasani4f128e42016-05-10 11:44:12 -07003343 if (mLastSessionId != cmd.sessionId) {
3344 // Clear the existing structures
3345 mLastSessionId = cmd.sessionId;
3346 for (int i = mLastAssistStructures.size() - 1; i >= 0; i--) {
3347 AssistStructure structure = mLastAssistStructures.get(i).get();
3348 if (structure != null) {
3349 structure.clearSendChannel();
3350 }
3351 mLastAssistStructures.remove(i);
Dianne Hackborn782d4982015-07-08 17:36:37 -07003352 }
3353 }
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003354
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003355 Bundle data = new Bundle();
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003356 AssistStructure structure = null;
Felipe Leme640f30a2017-03-06 15:44:06 -08003357 AssistContent content = forAutofill ? null : new AssistContent();
Amith Yamasani858f98d2017-02-22 12:59:53 -08003358 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003359 ActivityClientRecord r = mActivities.get(cmd.activityToken);
Dianne Hackborna3acdb32015-06-08 17:07:40 -07003360 Uri referrer = null;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003361 if (r != null) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003362 if (!forAutofill) {
Felipe Leme1ca634a2016-11-28 17:21:21 -08003363 r.activity.getApplication().dispatchOnProvideAssistData(r.activity, data);
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003364 r.activity.onProvideAssistData(data);
Felipe Leme6d553872016-12-08 17:13:25 -08003365 referrer = r.activity.onProvideReferrer();
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003366 }
Felipe Leme640f30a2017-03-06 15:44:06 -08003367 if (cmd.requestType == ActivityManager.ASSIST_CONTEXT_FULL || forAutofill) {
Svet Ganovfd31f852017-04-26 15:54:27 -07003368 structure = new AssistStructure(r.activity, forAutofill, cmd.flags);
Adam Skory4aaed142015-04-22 11:29:31 -06003369 Intent activityIntent = r.activity.getIntent();
Felipe Leme6d553872016-12-08 17:13:25 -08003370 boolean notSecure = r.window == null ||
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003371 (r.window.getAttributes().flags
Felipe Leme6d553872016-12-08 17:13:25 -08003372 & WindowManager.LayoutParams.FLAG_SECURE) == 0;
3373 if (activityIntent != null && notSecure) {
Felipe Leme640f30a2017-03-06 15:44:06 -08003374 if (!forAutofill) {
Felipe Leme1ca634a2016-11-28 17:21:21 -08003375 Intent intent = new Intent(activityIntent);
3376 intent.setFlags(intent.getFlags() & ~(Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3377 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION));
3378 intent.removeUnsafeExtras();
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003379 content.setDefaultIntent(intent);
3380 }
Adam Skory4aaed142015-04-22 11:29:31 -06003381 } else {
Felipe Leme640f30a2017-03-06 15:44:06 -08003382 if (!forAutofill) {
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003383 content.setDefaultIntent(new Intent());
3384 }
Adam Skory4aaed142015-04-22 11:29:31 -06003385 }
Felipe Leme640f30a2017-03-06 15:44:06 -08003386 if (!forAutofill) {
Felipe Leme29a5b0d2016-10-25 14:57:11 -07003387 r.activity.onProvideAssistContent(content);
3388 }
Dianne Hackborna83ce1d2015-03-11 15:16:13 -07003389 }
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003390 }
Dianne Hackborn09d57fe2015-05-27 18:05:52 -07003391 if (structure == null) {
3392 structure = new AssistStructure();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003393 }
Felipe Leme0200d9e2017-01-24 15:10:26 -08003394
Felipe Leme85d1c2d2017-04-21 08:56:04 -07003395 // TODO: decide if lastSessionId logic applies to autofill sessions
Amith Yamasani858f98d2017-02-22 12:59:53 -08003396
3397 structure.setAcquisitionStartTime(startTime);
3398 structure.setAcquisitionEndTime(SystemClock.uptimeMillis());
3399
Amith Yamasani4f128e42016-05-10 11:44:12 -07003400 mLastAssistStructures.add(new WeakReference<>(structure));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003401 IActivityTaskManager mgr = ActivityTaskManager.getService();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003402 try {
Dianne Hackborna3acdb32015-06-08 17:07:40 -07003403 mgr.reportAssistContextExtras(cmd.requestToken, data, structure, content, referrer);
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003404 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003405 throw e.rethrowFromSystemServer();
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08003406 }
3407 }
Craig Mautner5eda9b32013-07-02 11:58:16 -07003408
3409 public void handleTranslucentConversionComplete(IBinder token, boolean drawComplete) {
3410 ActivityClientRecord r = mActivities.get(token);
3411 if (r != null) {
3412 r.activity.onTranslucentConversionComplete(drawComplete);
3413 }
3414 }
3415
Craig Mautnereb8abf72014-07-02 15:04:09 -07003416 public void onNewActivityOptions(IBinder token, ActivityOptions options) {
3417 ActivityClientRecord r = mActivities.get(token);
3418 if (r != null) {
3419 r.activity.onNewActivityOptions(options);
3420 }
3421 }
3422
Jeff Sharkeydd97f422013-10-08 17:01:30 -07003423 public void handleInstallProvider(ProviderInfo info) {
Jeff Sharkeybb2e2ca2014-10-23 11:42:31 -07003424 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3425 try {
Jeff Sharkeya6bfeae2017-07-05 16:50:24 -06003426 installContentProviders(mInitialApplication, Arrays.asList(info));
Jeff Sharkeybb2e2ca2014-10-23 11:42:31 -07003427 } finally {
3428 StrictMode.setThreadPolicy(oldPolicy);
3429 }
Jeff Sharkeydd97f422013-10-08 17:01:30 -07003430 }
3431
Craig Mautner8746a472014-07-24 15:12:54 -07003432 private void handleEnterAnimationComplete(IBinder token) {
3433 ActivityClientRecord r = mActivities.get(token);
3434 if (r != null) {
Filip Gruszczynski6eafa902014-11-14 14:24:37 -08003435 r.activity.dispatchEnterAnimationComplete();
Craig Mautner8746a472014-07-24 15:12:54 -07003436 }
3437 }
3438
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04003439 private void handleStartBinderTracking() {
3440 Binder.enableTracing();
3441 }
3442
3443 private void handleStopBinderTrackingAndDump(ParcelFileDescriptor fd) {
3444 try {
3445 Binder.disableTracing();
3446 Binder.getTransactionTracker().writeTracesToFile(fd);
3447 } finally {
3448 IoUtils.closeQuietly(fd);
3449 Binder.getTransactionTracker().clearTraces();
3450 }
3451 }
3452
Andrii Kulian446e8242017-10-26 15:17:29 -07003453 @Override
3454 public void handleMultiWindowModeChanged(IBinder token, boolean isInMultiWindowMode,
Winson Chung5af42fc2017-03-24 17:11:33 -07003455 Configuration overrideConfig) {
Wale Ogunwale5f986092015-12-04 15:35:38 -08003456 final ActivityClientRecord r = mActivities.get(token);
3457 if (r != null) {
Winson Chung5af42fc2017-03-24 17:11:33 -07003458 final Configuration newConfig = new Configuration(mConfiguration);
3459 if (overrideConfig != null) {
3460 newConfig.updateFrom(overrideConfig);
3461 }
3462 r.activity.dispatchMultiWindowModeChanged(isInMultiWindowMode, newConfig);
Wale Ogunwale5f986092015-12-04 15:35:38 -08003463 }
3464 }
3465
Andrii Kulian446e8242017-10-26 15:17:29 -07003466 @Override
3467 public void handlePictureInPictureModeChanged(IBinder token, boolean isInPipMode,
Winson Chung5af42fc2017-03-24 17:11:33 -07003468 Configuration overrideConfig) {
Wale Ogunwale5f986092015-12-04 15:35:38 -08003469 final ActivityClientRecord r = mActivities.get(token);
3470 if (r != null) {
Winson Chung5af42fc2017-03-24 17:11:33 -07003471 final Configuration newConfig = new Configuration(mConfiguration);
3472 if (overrideConfig != null) {
3473 newConfig.updateFrom(overrideConfig);
3474 }
3475 r.activity.dispatchPictureInPictureModeChanged(isInPipMode, newConfig);
Wale Ogunwale5f986092015-12-04 15:35:38 -08003476 }
3477 }
3478
Amith Yamasani0af6fa72016-01-17 15:36:19 -08003479 private void handleLocalVoiceInteractionStarted(IBinder token, IVoiceInteractor interactor) {
3480 final ActivityClientRecord r = mActivities.get(token);
3481 if (r != null) {
3482 r.voiceInteractor = interactor;
3483 r.activity.setVoiceInteractor(interactor);
3484 if (interactor == null) {
3485 r.activity.onLocalVoiceInteractionStopped();
3486 } else {
3487 r.activity.onLocalVoiceInteractionStarted();
3488 }
3489 }
3490 }
3491
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003492 private static boolean attemptAttachAgent(String agent, ClassLoader classLoader) {
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003493 try {
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003494 VMDebug.attachAgent(agent, classLoader);
3495 return true;
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003496 } catch (IOException e) {
Andreas Gampeab8a63b2018-01-05 13:55:15 -08003497 Slog.e(TAG, "Attaching agent with " + classLoader + " failed: " + agent);
3498 return false;
3499 }
3500 }
3501
3502 static void handleAttachAgent(String agent, LoadedApk loadedApk) {
3503 ClassLoader classLoader = loadedApk != null ? loadedApk.getClassLoader() : null;
3504 if (attemptAttachAgent(agent, classLoader)) {
3505 return;
3506 }
3507 if (classLoader != null) {
3508 attemptAttachAgent(agent, null);
Leonard Mosescuf3409ce2016-10-06 17:32:05 -07003509 }
3510 }
3511
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003512 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
3513
3514 /**
3515 * Return the Intent that's currently being handled by a
3516 * BroadcastReceiver on this thread, or null if none.
3517 * @hide
3518 */
3519 public static Intent getIntentBeingBroadcast() {
3520 return sCurrentBroadcastIntent.get();
3521 }
3522
Mathew Inwood31755f92018-12-20 13:53:36 +00003523 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Romain Guy65b345f2011-07-27 18:51:50 -07003524 private void handleReceiver(ReceiverData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003525 // If we are getting ready to gc after going to the background, well
3526 // we are back active so skip it.
3527 unscheduleGcIdler();
3528
3529 String component = data.intent.getComponent().getClassName();
3530
Todd Kennedy233a0b12018-01-29 20:30:24 +00003531 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003532 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003533
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003534 IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003535
Adam Lesinski4e862812016-11-21 16:02:24 -08003536 Application app;
Romain Guy65b345f2011-07-27 18:51:50 -07003537 BroadcastReceiver receiver;
Adam Lesinski4e862812016-11-21 16:02:24 -08003538 ContextImpl context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00003540 app = packageInfo.makeApplication(false, mInstrumentation);
Adam Lesinski4e862812016-11-21 16:02:24 -08003541 context = (ContextImpl) app.getBaseContext();
3542 if (data.info.splitName != null) {
3543 context = (ContextImpl) context.createContextForSplit(data.info.splitName);
3544 }
3545 java.lang.ClassLoader cl = context.getClassLoader();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003546 data.intent.setExtrasClassLoader(cl);
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003547 data.intent.prepareToEnterProcess();
Dianne Hackborne829fef2010-10-26 17:44:01 -07003548 data.setExtrasClassLoader(cl);
Todd Kennedy233a0b12018-01-29 20:30:24 +00003549 receiver = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05003550 .instantiateReceiver(cl, data.info.name, data.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07003552 if (DEBUG_BROADCAST) Slog.i(TAG,
3553 "Finishing failed broadcast to " + data.intent.getComponent());
3554 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003555 throw new RuntimeException(
3556 "Unable to instantiate receiver " + component
3557 + ": " + e.toString(), e);
3558 }
3559
3560 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003561 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003562 TAG, "Performing receive of " + data.intent
3563 + ": app=" + app
3564 + ", appName=" + app.getPackageName()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003565 + ", pkg=" + packageInfo.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566 + ", comp=" + data.intent.getComponent().toShortString()
Todd Kennedy233a0b12018-01-29 20:30:24 +00003567 + ", dir=" + packageInfo.getAppDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003569 sCurrentBroadcastIntent.set(data.intent);
Dianne Hackborne829fef2010-10-26 17:44:01 -07003570 receiver.setPendingResult(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571 receiver.onReceive(context.getReceiverRestrictedContext(),
3572 data.intent);
3573 } catch (Exception e) {
Dianne Hackborne829fef2010-10-26 17:44:01 -07003574 if (DEBUG_BROADCAST) Slog.i(TAG,
3575 "Finishing failed broadcast to " + data.intent.getComponent());
3576 data.sendFinished(mgr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 if (!mInstrumentation.onException(receiver, e)) {
3578 throw new RuntimeException(
3579 "Unable to start receiver " + component
3580 + ": " + e.toString(), e);
3581 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07003582 } finally {
3583 sCurrentBroadcastIntent.set(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003584 }
3585
Dianne Hackborne829fef2010-10-26 17:44:01 -07003586 if (receiver.getPendingResult() != null) {
3587 data.finish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003588 }
3589 }
3590
Christopher Tate181fafa2009-05-14 11:12:14 -07003591 // Instantiate a BackupAgent and tell it that it's alive
Romain Guy65b345f2011-07-27 18:51:50 -07003592 private void handleCreateBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003593 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07003594
Christopher Tate346acb12012-10-15 19:20:25 -07003595 // Sanity check the requested target package's uid against ours
3596 try {
3597 PackageInfo requestedPackage = getPackageManager().getPackageInfo(
3598 data.appInfo.packageName, 0, UserHandle.myUserId());
3599 if (requestedPackage.applicationInfo.uid != Process.myUid()) {
3600 Slog.w(TAG, "Asked to instantiate non-matching package "
3601 + data.appInfo.packageName);
3602 return;
3603 }
3604 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003605 throw e.rethrowFromSystemServer();
Christopher Tate346acb12012-10-15 19:20:25 -07003606 }
3607
Christopher Tate181fafa2009-05-14 11:12:14 -07003608 // no longer idle; we have backup work to do
3609 unscheduleGcIdler();
3610
3611 // instantiate the BackupAgent class named in the manifest
Todd Kennedy233a0b12018-01-29 20:30:24 +00003612 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
3613 String packageName = packageInfo.mPackageName;
Christopher Tate346acb12012-10-15 19:20:25 -07003614 if (packageName == null) {
3615 Slog.d(TAG, "Asked to create backup agent for nonexistent package");
3616 return;
3617 }
3618
Christopher Tate181fafa2009-05-14 11:12:14 -07003619 String classname = data.appInfo.backupAgentName;
Christopher Tate79ec80d2011-06-24 14:58:49 -07003620 // full backup operation but no app-supplied agent? use the default implementation
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003621 if (classname == null && (data.backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL
3622 || data.backupMode == ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL)) {
Christopher Tate4a627c72011-04-01 14:43:32 -07003623 classname = "android.app.backup.FullBackupAgent";
Christopher Tate181fafa2009-05-14 11:12:14 -07003624 }
Christopher Tate4a627c72011-04-01 14:43:32 -07003625
Christopher Tate181fafa2009-05-14 11:12:14 -07003626 try {
Christopher Tated1475e02009-07-09 15:36:17 -07003627 IBinder binder = null;
Annie Mengd5827872019-01-30 20:28:57 +00003628 ArrayMap<String, BackupAgent> backupAgents = getBackupAgentsForUser(data.userId);
3629 BackupAgent agent = backupAgents.get(packageName);
Christopher Tate2e40d112014-07-15 12:37:38 -07003630 if (agent != null) {
3631 // reusing the existing instance
3632 if (DEBUG_BACKUP) {
3633 Slog.v(TAG, "Reusing existing agent instance");
Christopher Tated1475e02009-07-09 15:36:17 -07003634 }
Christopher Tate2e40d112014-07-15 12:37:38 -07003635 binder = agent.onBind();
3636 } else {
3637 try {
3638 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing agent class " + classname);
3639
Todd Kennedy233a0b12018-01-29 20:30:24 +00003640 java.lang.ClassLoader cl = packageInfo.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04003641 agent = (BackupAgent) cl.loadClass(classname).newInstance();
Christopher Tate2e40d112014-07-15 12:37:38 -07003642
3643 // set up the agent's context
Todd Kennedy233a0b12018-01-29 20:30:24 +00003644 ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
Christopher Tate2e40d112014-07-15 12:37:38 -07003645 context.setOuterContext(agent);
3646 agent.attach(context);
3647
Ruslan Tkhakokhov063180f2019-01-28 20:29:46 +00003648 agent.onCreate(UserHandle.of(data.userId));
Christopher Tate2e40d112014-07-15 12:37:38 -07003649 binder = agent.onBind();
Annie Mengd5827872019-01-30 20:28:57 +00003650 backupAgents.put(packageName, agent);
Christopher Tate2e40d112014-07-15 12:37:38 -07003651 } catch (Exception e) {
3652 // If this is during restore, fail silently; otherwise go
3653 // ahead and let the user see the crash.
3654 Slog.e(TAG, "Agent threw during creation: " + e);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07003655 if (data.backupMode != ApplicationThreadConstants.BACKUP_MODE_RESTORE
3656 && data.backupMode !=
3657 ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL) {
Christopher Tate2e40d112014-07-15 12:37:38 -07003658 throw e;
3659 }
3660 // falling through with 'binder' still null
3661 }
Christopher Tated1475e02009-07-09 15:36:17 -07003662 }
Christopher Tate181fafa2009-05-14 11:12:14 -07003663
3664 // tell the OS that we're live now
Christopher Tate181fafa2009-05-14 11:12:14 -07003665 try {
Annie Mengd5827872019-01-30 20:28:57 +00003666 ActivityManager.getService().backupAgentCreated(packageName, binder, data.userId);
Christopher Tate181fafa2009-05-14 11:12:14 -07003667 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003668 throw e.rethrowFromSystemServer();
Christopher Tate181fafa2009-05-14 11:12:14 -07003669 }
Christopher Tate181fafa2009-05-14 11:12:14 -07003670 } catch (Exception e) {
3671 throw new RuntimeException("Unable to create BackupAgent "
Christopher Tate4a627c72011-04-01 14:43:32 -07003672 + classname + ": " + e.toString(), e);
Christopher Tate181fafa2009-05-14 11:12:14 -07003673 }
3674 }
3675
3676 // Tear down a BackupAgent
Romain Guy65b345f2011-07-27 18:51:50 -07003677 private void handleDestroyBackupAgent(CreateBackupAgentData data) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003678 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
Bob Leee5408332009-09-04 18:31:17 -07003679
Todd Kennedy233a0b12018-01-29 20:30:24 +00003680 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
3681 String packageName = packageInfo.mPackageName;
Annie Mengd5827872019-01-30 20:28:57 +00003682 ArrayMap<String, BackupAgent> backupAgents = getBackupAgentsForUser(data.userId);
3683 BackupAgent agent = backupAgents.get(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07003684 if (agent != null) {
3685 try {
3686 agent.onDestroy();
3687 } catch (Exception e) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003688 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
Christopher Tate181fafa2009-05-14 11:12:14 -07003689 e.printStackTrace();
3690 }
Annie Mengd5827872019-01-30 20:28:57 +00003691 backupAgents.remove(packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07003692 } else {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08003693 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
Christopher Tate181fafa2009-05-14 11:12:14 -07003694 }
3695 }
3696
Annie Mengd5827872019-01-30 20:28:57 +00003697 private ArrayMap<String, BackupAgent> getBackupAgentsForUser(int userId) {
3698 ArrayMap<String, BackupAgent> backupAgents = mBackupAgentsByUser.get(userId);
3699 if (backupAgents == null) {
3700 backupAgents = new ArrayMap<>();
3701 mBackupAgentsByUser.put(userId, backupAgents);
3702 }
3703 return backupAgents;
3704 }
3705
Mathew Inwood61e8ae62018-08-14 14:17:44 +01003706 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07003707 private void handleCreateService(CreateServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003708 // If we are getting ready to gc after going to the background, well
3709 // we are back active so skip it.
3710 unscheduleGcIdler();
3711
Todd Kennedy233a0b12018-01-29 20:30:24 +00003712 LoadedApk packageInfo = getPackageInfoNoCheck(
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003713 data.info.applicationInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003714 Service service = null;
3715 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00003716 java.lang.ClassLoader cl = packageInfo.getClassLoader();
3717 service = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05003718 .instantiateService(cl, data.info.name, data.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003719 } catch (Exception e) {
3720 if (!mInstrumentation.onException(service, e)) {
3721 throw new RuntimeException(
3722 "Unable to instantiate service " + data.info.name
3723 + ": " + e.toString(), e);
3724 }
3725 }
3726
3727 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003728 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729
Todd Kennedy233a0b12018-01-29 20:30:24 +00003730 ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
Jeff Browndefd4a62014-03-10 21:24:37 -07003731 context.setOuterContext(service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732
Todd Kennedy233a0b12018-01-29 20:30:24 +00003733 Application app = packageInfo.makeApplication(false, mInstrumentation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003734 service.attach(context, this, data.info.name, data.token, app,
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003735 ActivityManager.getService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003736 service.onCreate();
3737 mServices.put(data.token, service);
3738 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003739 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003740 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003742 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003743 }
3744 } catch (Exception e) {
3745 if (!mInstrumentation.onException(service, e)) {
3746 throw new RuntimeException(
3747 "Unable to create service " + data.info.name
3748 + ": " + e.toString(), e);
3749 }
3750 }
3751 }
3752
Romain Guy65b345f2011-07-27 18:51:50 -07003753 private void handleBindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003754 Service s = mServices.get(data.token);
Amith Yamasani742a6712011-05-04 14:49:28 -07003755 if (DEBUG_SERVICE)
3756 Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757 if (s != null) {
3758 try {
3759 data.intent.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003760 data.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003761 try {
3762 if (!data.rebind) {
3763 IBinder binder = s.onBind(data.intent);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003764 ActivityManager.getService().publishService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765 data.token, data.intent, binder);
3766 } else {
3767 s.onRebind(data.intent);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003768 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003769 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 }
3771 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003772 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003773 }
3774 } catch (Exception e) {
3775 if (!mInstrumentation.onException(s, e)) {
3776 throw new RuntimeException(
3777 "Unable to bind to service " + s
3778 + " with " + data.intent + ": " + e.toString(), e);
3779 }
3780 }
3781 }
3782 }
3783
Romain Guy65b345f2011-07-27 18:51:50 -07003784 private void handleUnbindService(BindServiceData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003785 Service s = mServices.get(data.token);
3786 if (s != null) {
3787 try {
3788 data.intent.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003789 data.intent.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790 boolean doRebind = s.onUnbind(data.intent);
3791 try {
3792 if (doRebind) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003793 ActivityManager.getService().unbindFinished(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794 data.token, data.intent, doRebind);
3795 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003796 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003797 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003798 }
3799 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003800 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 }
3802 } catch (Exception e) {
3803 if (!mInstrumentation.onException(s, e)) {
3804 throw new RuntimeException(
3805 "Unable to unbind to service " + s
3806 + " with " + data.intent + ": " + e.toString(), e);
3807 }
3808 }
3809 }
3810 }
3811
Dianne Hackborn625ac272010-09-17 18:29:22 -07003812 private void handleDumpService(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08003813 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3814 try {
3815 Service s = mServices.get(info.token);
3816 if (s != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07003817 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
3818 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08003819 s.dump(info.fd.getFileDescriptor(), pw, info.args);
3820 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003821 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08003822 } finally {
3823 IoUtils.closeQuietly(info.fd);
3824 StrictMode.setThreadPolicy(oldPolicy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 }
3826 }
3827
Dianne Hackborn625ac272010-09-17 18:29:22 -07003828 private void handleDumpActivity(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08003829 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3830 try {
3831 ActivityClientRecord r = mActivities.get(info.token);
3832 if (r != null && r.activity != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07003833 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
3834 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08003835 r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
3836 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07003837 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08003838 } finally {
3839 IoUtils.closeQuietly(info.fd);
3840 StrictMode.setThreadPolicy(oldPolicy);
Dianne Hackborn625ac272010-09-17 18:29:22 -07003841 }
3842 }
3843
Marco Nelissen18cb2872011-11-15 11:19:53 -08003844 private void handleDumpProvider(DumpComponentInfo info) {
Jeff Sharkeye861b422012-03-01 20:59:22 -08003845 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
3846 try {
3847 ProviderClientRecord r = mLocalProviders.get(info.token);
3848 if (r != null && r.mLocalProvider != null) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07003849 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
3850 info.fd.getFileDescriptor()));
Jeff Sharkeye861b422012-03-01 20:59:22 -08003851 r.mLocalProvider.dump(info.fd.getFileDescriptor(), pw, info.args);
3852 pw.flush();
Marco Nelissen18cb2872011-11-15 11:19:53 -08003853 }
Jeff Sharkeye861b422012-03-01 20:59:22 -08003854 } finally {
3855 IoUtils.closeQuietly(info.fd);
3856 StrictMode.setThreadPolicy(oldPolicy);
Marco Nelissen18cb2872011-11-15 11:19:53 -08003857 }
3858 }
3859
Romain Guy65b345f2011-07-27 18:51:50 -07003860 private void handleServiceArgs(ServiceArgsData data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003861 Service s = mServices.get(data.token);
3862 if (s != null) {
3863 try {
3864 if (data.args != null) {
3865 data.args.setExtrasClassLoader(s.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01003866 data.args.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003868 int res;
3869 if (!data.taskRemoved) {
3870 res = s.onStartCommand(data.args, data.flags, data.startId);
3871 } else {
3872 s.onTaskRemoved(data.args);
3873 res = Service.START_TASK_REMOVED_COMPLETE;
3874 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003875
3876 QueuedWork.waitToFinish();
3877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003879 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003880 data.token, SERVICE_DONE_EXECUTING_START, data.startId, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003881 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003882 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 }
3884 } catch (Exception e) {
3885 if (!mInstrumentation.onException(s, e)) {
3886 throw new RuntimeException(
3887 "Unable to start service " + s
3888 + " with " + data.args + ": " + e.toString(), e);
3889 }
3890 }
3891 }
3892 }
3893
Romain Guy65b345f2011-07-27 18:51:50 -07003894 private void handleStopService(IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895 Service s = mServices.remove(token);
3896 if (s != null) {
3897 try {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003898 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 s.onDestroy();
Amith Yamasani75928252017-05-22 15:10:47 -07003900 s.detachAndCleanUp();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901 Context context = s.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08003902 if (context instanceof ContextImpl) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 final String who = s.getClassName();
Dianne Hackborn21556372010-02-04 16:34:40 -08003904 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 }
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07003906
3907 QueuedWork.waitToFinish();
3908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003909 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003910 ActivityManager.getService().serviceDoneExecuting(
Dianne Hackborn455625e2015-01-21 09:55:13 -08003911 token, SERVICE_DONE_EXECUTING_STOP, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07003913 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003914 }
3915 } catch (Exception e) {
3916 if (!mInstrumentation.onException(s, e)) {
3917 throw new RuntimeException(
3918 "Unable to stop service " + s
3919 + ": " + e.toString(), e);
3920 }
Craig Mautner66c4a822015-01-16 12:48:16 -08003921 Slog.i(TAG, "handleStopService: exception for " + token, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 }
Craig Mautner9776ad42015-01-15 14:38:39 -08003923 } else {
3924 Slog.i(TAG, "handleStopService: token=" + token + " not found.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07003926 //Slog.i(TAG, "Running services: " + mServices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 }
3928
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003929 /**
3930 * Resume the activity.
3931 * @param token Target activity token.
3932 * @param finalStateRequest Flag indicating if this is part of final state resolution for a
3933 * transaction.
3934 * @param reason Reason for performing the action.
3935 *
3936 * @return The {@link ActivityClientRecord} that was resumed, {@code null} otherwise.
3937 */
3938 @VisibleForTesting
3939 public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
Andrii Kuliandfbf9712018-03-08 15:42:24 -08003940 String reason) {
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003941 final ActivityClientRecord r = mActivities.get(token);
3942 if (localLOGV) {
3943 Slog.v(TAG, "Performing resume of " + r + " finished=" + r.activity.mFinished);
3944 }
Andrii Kulianc10482f2019-03-07 18:09:28 +00003945 if (r == null || r.activity.mFinished) {
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003946 return null;
3947 }
3948 if (r.getLifecycleState() == ON_RESUME) {
3949 if (!finalStateRequest) {
3950 final RuntimeException e = new IllegalStateException(
3951 "Trying to resume activity which is already resumed");
3952 Slog.e(TAG, e.getMessage(), e);
3953 Slog.e(TAG, r.getStateString());
3954 // TODO(lifecycler): A double resume request is possible when an activity
3955 // receives two consequent transactions with relaunch requests and "resumed"
3956 // final state requests and the second relaunch is omitted. We still try to
3957 // handle two resume requests for the final state. For cases other than this
3958 // one, we don't expect it to happen.
Andrii Kulian9956d892018-02-14 13:48:56 -08003959 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003960 return null;
3961 }
3962 if (finalStateRequest) {
3963 r.hideForNow = false;
3964 r.activity.mStartedActivity = false;
3965 }
3966 try {
3967 r.activity.onStateNotSaved();
3968 r.activity.mFragments.noteStateNotSaved();
3969 checkAndBlockForNetworkAccess();
3970 if (r.pendingIntents != null) {
3971 deliverNewIntents(r, r.pendingIntents);
3972 r.pendingIntents = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003973 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003974 if (r.pendingResults != null) {
Andrii Kuliane55b0092018-04-19 15:29:22 -07003975 deliverResults(r, r.pendingResults, reason);
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003976 r.pendingResults = null;
3977 }
3978 r.activity.performResume(r.startsNotResumed, reason);
Bob Leee5408332009-09-04 18:31:17 -07003979
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003980 r.state = null;
3981 r.persistentState = null;
3982 r.setState(ON_RESUME);
Andrii Kuliand70cdb92019-01-08 15:03:50 -08003983
3984 reportTopResumedActivityChanged(r, r.isTopResumedActivity);
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07003985 } catch (Exception e) {
3986 if (!mInstrumentation.onException(r.activity, e)) {
3987 throw new RuntimeException("Unable to resume activity "
3988 + r.intent.getComponent().toShortString() + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003989 }
3990 }
3991 return r;
3992 }
3993
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003994 static final void cleanUpPendingRemoveWindows(ActivityClientRecord r, boolean force) {
3995 if (r.mPreserveWindow && !force) {
3996 return;
3997 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003998 if (r.mPendingRemoveWindow != null) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07003999 r.mPendingRemoveWindowManager.removeViewImmediate(
4000 r.mPendingRemoveWindow.getDecorView());
4001 IBinder wtoken = r.mPendingRemoveWindow.getDecorView().getWindowToken();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004002 if (wtoken != null) {
Jeff Brown98365d72012-08-19 20:30:52 -07004003 WindowManagerGlobal.getInstance().closeAll(wtoken,
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004004 r.activity.getClass().getName(), "Activity");
4005 }
4006 }
4007 r.mPendingRemoveWindow = null;
4008 r.mPendingRemoveWindowManager = null;
4009 }
4010
Andrii Kulian446e8242017-10-26 15:17:29 -07004011 @Override
Andrii Kuliandfbf9712018-03-08 15:42:24 -08004012 public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004013 String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 // If we are getting ready to gc after going to the background, well
4015 // we are back active so skip it.
4016 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004017 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004018
Adam Powellcfbe9be2013-11-06 14:58:58 -08004019 // TODO Push resumeArgs into the activity for consideration
Andrii Kuliandfbf9712018-03-08 15:42:24 -08004020 final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004021 if (r == null) {
4022 // We didn't actually resume the activity, so skipping any follow-up actions.
4023 return;
4024 }
Riddle Hsu66b74a82018-07-26 00:20:12 +08004025 if (mActivitiesToBeDestroyed.containsKey(token)) {
4026 // Although the activity is resumed, it is going to be destroyed. So the following
4027 // UI operations are unnecessary and also prevents exception because its token may
4028 // be gone that window manager cannot recognize it. All necessary cleanup actions
4029 // performed below will be done while handling destruction.
4030 return;
4031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004033 final Activity a = r.activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004035 if (localLOGV) {
4036 Slog.v(TAG, "Resume " + r + " started activity: " + a.mStartedActivity
4037 + ", hideForNow: " + r.hideForNow + ", finished: " + a.mFinished);
4038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004040 final int forwardBit = isForward
4041 ? WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
Bob Leee5408332009-09-04 18:31:17 -07004042
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004043 // If the window hasn't yet been added to the window manager,
4044 // and this guy didn't finish itself or start another activity,
4045 // then go ahead and add the window.
4046 boolean willBeVisible = !a.mStartedActivity;
4047 if (!willBeVisible) {
4048 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004049 willBeVisible = ActivityTaskManager.getService().willActivityBeVisible(
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004050 a.getActivityToken());
4051 } catch (RemoteException e) {
4052 throw e.rethrowFromSystemServer();
4053 }
4054 }
4055 if (r.window == null && !a.mFinished && willBeVisible) {
4056 r.window = r.activity.getWindow();
4057 View decor = r.window.getDecorView();
4058 decor.setVisibility(View.INVISIBLE);
4059 ViewManager wm = a.getWindowManager();
4060 WindowManager.LayoutParams l = r.window.getAttributes();
4061 a.mDecor = decor;
4062 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
4063 l.softInputMode |= forwardBit;
4064 if (r.mPreserveWindow) {
4065 a.mWindowAdded = true;
4066 r.mPreserveWindow = false;
4067 // Normally the ViewRoot sets up callbacks with the Activity
4068 // in addView->ViewRootImpl#setView. If we are instead reusing
4069 // the decor view we have to notify the view root that the
4070 // callbacks may have changed.
4071 ViewRootImpl impl = decor.getViewRootImpl();
4072 if (impl != null) {
4073 impl.notifyChildRebuilt();
Dianne Hackborn061d58a2010-03-12 15:07:06 -08004074 }
4075 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004076 if (a.mVisibleFromClient) {
4077 if (!a.mWindowAdded) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004078 a.mWindowAdded = true;
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004079 wm.addView(decor, l);
4080 } else {
4081 // The activity will get a callback for this {@link LayoutParams} change
4082 // earlier. However, at that time the decor will not be set (this is set
4083 // in this method), so no action will be taken. This call ensures the
4084 // callback occurs with the decor set.
4085 a.onWindowAttributesChanged(l);
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004086 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004088
4089 // If the window has already been added, but during resume
4090 // we started another activity, then don't yet make the
Dianne Hackborn061d58a2010-03-12 15:07:06 -08004091 // window visible.
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004092 } else if (!willBeVisible) {
4093 if (localLOGV) Slog.v(TAG, "Launch " + r + " mStartedActivity set");
4094 r.hideForNow = true;
4095 }
4096
4097 // Get rid of anything left hanging around.
4098 cleanUpPendingRemoveWindows(r, false /* force */);
4099
4100 // The window is now visible if it has been added, we are not
4101 // simply finishing, and we are not starting another activity.
4102 if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) {
4103 if (r.newConfig != null) {
4104 performConfigurationChangedForActivity(r, r.newConfig);
4105 if (DEBUG_CONFIGURATION) {
4106 Slog.v(TAG, "Resuming activity " + r.activityInfo.name + " with newConfig "
4107 + r.activity.mCurrentConfig);
4108 }
4109 r.newConfig = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004110 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004111 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward=" + isForward);
4112 WindowManager.LayoutParams l = r.window.getAttributes();
4113 if ((l.softInputMode
4114 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
4115 != forwardBit) {
4116 l.softInputMode = (l.softInputMode
4117 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
4118 | forwardBit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004119 if (r.activity.mVisibleFromClient) {
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004120 ViewManager wm = a.getWindowManager();
4121 View decor = r.window.getDecorView();
4122 wm.updateViewLayout(decor, l);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004123 }
4124 }
4125
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004126 r.activity.mVisibleFromServer = true;
4127 mNumVisibleActivities++;
4128 if (r.activity.mVisibleFromClient) {
4129 r.activity.makeVisible();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004130 }
4131 }
Andrii Kuliand9e2acb2018-03-29 16:07:11 -07004132
4133 r.nextIdle = mNewActivities;
4134 mNewActivities = r;
4135 if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);
4136 Looper.myQueue().addIdleHandler(new Idler());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004137 }
4138
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004139
4140 @Override
4141 public void handleTopResumedActivityChanged(IBinder token, boolean onTop, String reason) {
4142 ActivityClientRecord r = mActivities.get(token);
4143 if (r == null || r.activity == null) {
4144 Slog.w(TAG, "Not found target activity to report position change for token: " + token);
4145 return;
4146 }
4147
4148 if (DEBUG_ORDER) {
4149 Slog.d(TAG, "Received position change to top: " + onTop + " for activity: " + r);
4150 }
4151
4152 if (r.isTopResumedActivity == onTop) {
4153 throw new IllegalStateException("Activity top position already set to onTop=" + onTop);
4154 }
4155
4156 r.isTopResumedActivity = onTop;
4157
4158 if (r.getLifecycleState() == ON_RESUME) {
4159 reportTopResumedActivityChanged(r, onTop);
4160 } else {
4161 if (DEBUG_ORDER) {
4162 Slog.d(TAG, "Won't deliver top position change in state=" + r.getLifecycleState());
4163 }
4164 }
4165 }
4166
4167 /**
4168 * Call {@link Activity#onTopResumedActivityChanged(boolean)} if its top resumed state changed
4169 * since the last report.
4170 */
4171 private void reportTopResumedActivityChanged(ActivityClientRecord r, boolean onTop) {
4172 if (r.lastReportedTopResumedState != onTop) {
4173 r.lastReportedTopResumedState = onTop;
4174 r.activity.onTopResumedActivityChanged(onTop);
4175 }
4176 }
4177
Andrii Kulian446e8242017-10-26 15:17:29 -07004178 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004179 public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
Andrii Kuliana6176e32018-02-27 11:51:18 -08004180 int configChanges, PendingTransactionActions pendingActions, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004181 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004182 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004183 if (userLeaving) {
4184 performUserLeavingActivity(r);
4185 }
Bob Leee5408332009-09-04 18:31:17 -07004186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004187 r.activity.mConfigChangeFlags |= configChanges;
Andrii Kuliand25680c2018-02-21 15:16:58 -08004188 performPauseActivity(r, finished, reason, pendingActions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004189
Dianne Hackbornaa93bcd2010-10-27 13:57:00 -07004190 // Make sure any pending writes are now committed.
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004191 if (r.isPreHoneycomb()) {
4192 QueuedWork.waitToFinish();
4193 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004194 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004195 }
4196 }
4197
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004198 final void performUserLeavingActivity(ActivityClientRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 mInstrumentation.callActivityOnUserLeaving(r.activity);
4200 }
4201
Andrii Kulian8ae79572018-01-26 15:36:06 -08004202 final Bundle performPauseActivity(IBinder token, boolean finished, String reason,
4203 PendingTransactionActions pendingActions) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004204 ActivityClientRecord r = mActivities.get(token);
Andrii Kulian8ae79572018-01-26 15:36:06 -08004205 return r != null ? performPauseActivity(r, finished, reason, pendingActions) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 }
4207
Andrii Kulian8ae79572018-01-26 15:36:06 -08004208 /**
4209 * Pause the activity.
4210 * @return Saved instance state for pre-Honeycomb apps if it was saved, {@code null} otherwise.
4211 */
4212 private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
4213 PendingTransactionActions pendingActions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004214 if (r.paused) {
Andrii Kulianc10482f2019-03-07 18:09:28 +00004215 if (r.activity.mFinished) {
4216 // If we are finishing, we won't call onResume() in certain cases.
4217 // So here we likewise don't want to call onPause() if the activity
4218 // isn't resumed.
4219 return null;
4220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 RuntimeException e = new RuntimeException(
4222 "Performing pause of activity that is not resumed: "
4223 + r.intent.getComponent().toShortString());
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08004224 Slog.e(TAG, e.getMessage(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004226 if (finished) {
4227 r.activity.mFinished = true;
4228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004229
Andrii Kulian8ae79572018-01-26 15:36:06 -08004230 // Pre-Honeycomb apps always save their state before pausing
4231 final boolean shouldSaveState = !r.activity.mFinished && r.isPreHoneycomb();
4232 if (shouldSaveState) {
4233 callActivityOnSaveInstanceState(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 }
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004235
4236 performPauseActivityIfNeeded(r, reason);
Jeff Hamilton52d32032011-01-08 15:31:26 -06004237
4238 // Notify any outstanding on paused listeners
4239 ArrayList<OnActivityPausedListener> listeners;
4240 synchronized (mOnPauseListeners) {
4241 listeners = mOnPauseListeners.remove(r.activity);
4242 }
4243 int size = (listeners != null ? listeners.size() : 0);
4244 for (int i = 0; i < size; i++) {
4245 listeners.get(i).onPaused(r.activity);
4246 }
4247
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004248 final Bundle oldState = pendingActions != null ? pendingActions.getOldState() : null;
4249 if (oldState != null) {
4250 // We need to keep around the original state, in case we need to be created again.
4251 // But we only do this for pre-Honeycomb apps, which always save their state when
4252 // pausing, so we can not have them save their state when restarting from a paused
4253 // state. For HC and later, we want to (and can) let the state be saved as the
4254 // normal part of stopping the activity.
4255 if (r.isPreHoneycomb()) {
4256 r.state = oldState;
4257 }
4258 }
4259
Andrii Kulian8ae79572018-01-26 15:36:06 -08004260 return shouldSaveState ? r.state : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 }
4262
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004263 private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
4264 if (r.paused) {
4265 // You are already paused silly...
4266 return;
4267 }
4268
Andrii Kuliand70cdb92019-01-08 15:03:50 -08004269 // Always reporting top resumed position loss when pausing an activity. If necessary, it
4270 // will be restored in performResumeActivity().
4271 reportTopResumedActivityChanged(r, false /* onTop */);
4272
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004273 try {
4274 r.activity.mCalled = false;
4275 mInstrumentation.callActivityOnPause(r.activity);
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004276 if (!r.activity.mCalled) {
4277 throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
4278 + " did not call through to super.onPause()");
4279 }
4280 } catch (SuperNotCalledException e) {
4281 throw e;
4282 } catch (Exception e) {
4283 if (!mInstrumentation.onException(r.activity, e)) {
4284 throw new RuntimeException("Unable to pause activity "
4285 + safeToComponentShortString(r.intent) + ": " + e.toString(), e);
4286 }
4287 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004288 r.setState(ON_PAUSE);
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004289 }
4290
Andrii Kulian829829c2018-03-19 18:19:05 -07004291 /** Called from {@link LocalActivityManager}. */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01004292 @UnsupportedAppUsage
Wale Ogunwalecd7043e2016-02-27 17:37:46 -08004293 final void performStopActivity(IBinder token, boolean saveState, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004294 ActivityClientRecord r = mActivities.get(token);
Andrii Kulian829829c2018-03-19 18:19:05 -07004295 performStopActivityInner(r, null /* stopInfo */, false /* keepShown */, saveState,
4296 false /* finalStateRequest */, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004297 }
4298
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004299 private static final class ProviderRefCount {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07004300 public final ContentProviderHolder holder;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004301 public final ProviderClientRecord client;
4302 public int stableCount;
4303 public int unstableCount;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08004304
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004305 // When this is set, the stable and unstable ref counts are 0 and
4306 // we have a pending operation scheduled to remove the ref count
4307 // from the activity manager. On the activity manager we are still
4308 // holding an unstable ref, though it is not reflected in the counts
4309 // here.
4310 public boolean removePending;
4311
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07004312 ProviderRefCount(ContentProviderHolder inHolder,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07004313 ProviderClientRecord inClient, int sCount, int uCount) {
4314 holder = inHolder;
4315 client = inClient;
4316 stableCount = sCount;
4317 unstableCount = uCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004318 }
4319 }
4320
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004321 /**
4322 * Core implementation of stopping an activity. Note this is a little
4323 * tricky because the server's meaning of stop is slightly different
4324 * than our client -- for the server, stop means to save state and give
4325 * it the result when it is done, but the window may still be visible.
4326 * For the client, we want to call onStop()/onStart() to indicate when
Wale Ogunwaleb5066fe2016-09-21 07:33:43 -07004327 * the activity's UI visibility changes.
Andrii Kulian829829c2018-03-19 18:19:05 -07004328 * @param r Target activity client record.
4329 * @param info Action that will report activity stop to server.
4330 * @param keepShown Flag indicating whether the activity is still shown.
4331 * @param saveState Flag indicating whether the activity state should be saved.
4332 * @param finalStateRequest Flag indicating if this call is handling final lifecycle state
4333 * request for a transaction.
4334 * @param reason Reason for performing this operation.
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004335 */
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004336 private void performStopActivityInner(ActivityClientRecord r, StopInfo info, boolean keepShown,
Andrii Kulian829829c2018-03-19 18:19:05 -07004337 boolean saveState, boolean finalStateRequest, String reason) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004338 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004339 if (r != null) {
Andrii Kulianc10482f2019-03-07 18:09:28 +00004340 if (!keepShown && r.stopped) {
4341 if (r.activity.mFinished) {
4342 // If we are finishing, we won't call onResume() in certain
4343 // cases. So here we likewise don't want to call onStop()
4344 // if the activity isn't resumed.
4345 return;
4346 }
4347 if (!finalStateRequest) {
4348 final RuntimeException e = new RuntimeException(
4349 "Performing stop of activity that is already stopped: "
4350 + r.intent.getComponent().toShortString());
4351 Slog.e(TAG, e.getMessage(), e);
4352 Slog.e(TAG, r.getStateString());
4353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004354 }
4355
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004356 // One must first be paused before stopped...
4357 performPauseActivityIfNeeded(r, reason);
4358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004359 if (info != null) {
4360 try {
4361 // First create a thumbnail for the activity...
Dianne Hackborn0500b3c2011-11-01 15:28:43 -07004362 // For now, don't create the thumbnail here; we are
4363 // doing that by doing a screen snapshot.
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004364 info.setDescription(r.activity.onCreateDescription());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004365 } catch (Exception e) {
4366 if (!mInstrumentation.onException(r.activity, e)) {
4367 throw new RuntimeException(
4368 "Unable to save state of activity "
4369 + r.intent.getComponent().toShortString()
4370 + ": " + e.toString(), e);
4371 }
4372 }
4373 }
4374
4375 if (!keepShown) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004376 callActivityOnStop(r, saveState, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004378 }
4379 }
4380
Andrii Kulian8ae79572018-01-26 15:36:06 -08004381 /**
4382 * Calls {@link Activity#onStop()} and {@link Activity#onSaveInstanceState(Bundle)}, and updates
4383 * the client record's state.
4384 * All calls to stop an activity must be done through this method to make sure that
4385 * {@link Activity#onSaveInstanceState(Bundle)} is also executed in the same call.
4386 */
4387 private void callActivityOnStop(ActivityClientRecord r, boolean saveState, String reason) {
Andrii Kulian391161f2018-01-29 10:50:02 -08004388 // Before P onSaveInstanceState was called before onStop, starting with P it's
4389 // called after. Before Honeycomb state was always saved before onPause.
Andrii Kulian8ae79572018-01-26 15:36:06 -08004390 final boolean shouldSaveState = saveState && !r.activity.mFinished && r.state == null
4391 && !r.isPreHoneycomb();
Andrii Kulian391161f2018-01-29 10:50:02 -08004392 final boolean isPreP = r.isPreP();
4393 if (shouldSaveState && isPreP) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004394 callActivityOnSaveInstanceState(r);
4395 }
4396
4397 try {
Garfield Tanc1681e62018-05-29 11:05:05 -07004398 r.activity.performStop(r.mPreserveWindow, reason);
Andrii Kulian8ae79572018-01-26 15:36:06 -08004399 } catch (SuperNotCalledException e) {
4400 throw e;
4401 } catch (Exception e) {
4402 if (!mInstrumentation.onException(r.activity, e)) {
4403 throw new RuntimeException(
4404 "Unable to stop activity "
4405 + r.intent.getComponent().toShortString()
4406 + ": " + e.toString(), e);
4407 }
4408 }
4409 r.setState(ON_STOP);
Andrii Kulian391161f2018-01-29 10:50:02 -08004410
4411 if (shouldSaveState && !isPreP) {
4412 callActivityOnSaveInstanceState(r);
4413 }
Andrii Kulian8ae79572018-01-26 15:36:06 -08004414 }
4415
Romain Guy65b345f2011-07-27 18:51:50 -07004416 private void updateVisibility(ActivityClientRecord r, boolean show) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004417 View v = r.activity.mDecor;
4418 if (v != null) {
4419 if (show) {
4420 if (!r.activity.mVisibleFromServer) {
4421 r.activity.mVisibleFromServer = true;
4422 mNumVisibleActivities++;
4423 if (r.activity.mVisibleFromClient) {
4424 r.activity.makeVisible();
4425 }
4426 }
4427 if (r.newConfig != null) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08004428 performConfigurationChangedForActivity(r, r.newConfig);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004429 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Updating activity vis "
Adam Lesinski082614c2016-03-04 14:33:47 -08004430 + r.activityInfo.name + " with new config "
4431 + r.activity.mCurrentConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004432 r.newConfig = null;
4433 }
4434 } else {
4435 if (r.activity.mVisibleFromServer) {
4436 r.activity.mVisibleFromServer = false;
4437 mNumVisibleActivities--;
4438 v.setVisibility(View.INVISIBLE);
4439 }
4440 }
4441 }
4442 }
4443
Andrii Kulian446e8242017-10-26 15:17:29 -07004444 @Override
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004445 public void handleStopActivity(IBinder token, boolean show, int configChanges,
Andrii Kulian829829c2018-03-19 18:19:05 -07004446 PendingTransactionActions pendingActions, boolean finalStateRequest, String reason) {
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004447 final ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004448 r.activity.mConfigChangeFlags |= configChanges;
4449
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004450 final StopInfo stopInfo = new StopInfo();
Andrii Kulian829829c2018-03-19 18:19:05 -07004451 performStopActivityInner(r, stopInfo, show, true /* saveState */, finalStateRequest,
4452 reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004453
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004454 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004455 TAG, "Finishing stop of " + r + ": show=" + show
4456 + " win=" + r.window);
4457
4458 updateVisibility(r, show);
Bob Leee5408332009-09-04 18:31:17 -07004459
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004460 // Make sure any pending writes are now committed.
4461 if (!r.isPreHoneycomb()) {
4462 QueuedWork.waitToFinish();
4463 }
4464
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004465 stopInfo.setActivity(r);
4466 stopInfo.setState(r.state);
4467 stopInfo.setPersistentState(r.persistentState);
4468 pendingActions.setStopInfo(stopInfo);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004469 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004470 }
4471
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004472 /**
4473 * Schedule the call to tell the activity manager we have stopped. We don't do this
4474 * immediately, because we want to have a chance for any other pending work (in particular
4475 * memory trim requests) to complete before you tell the activity manager to proceed and allow
4476 * us to go fully into the background.
4477 */
4478 @Override
4479 public void reportStop(PendingTransactionActions pendingActions) {
4480 mH.post(pendingActions.getStopInfo());
Filip Gruszczynskidb5dec22015-10-11 15:17:48 -07004481 }
4482
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004483 @Override
4484 public void performRestartActivity(IBinder token, boolean start) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004485 ActivityClientRecord r = mActivities.get(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004486 if (r.stopped) {
Andrii Kuliand25680c2018-02-21 15:16:58 -08004487 r.activity.performRestart(start, "performRestartActivity");
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004488 if (start) {
4489 r.setState(ON_START);
4490 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004491 }
4492 }
4493
Andrii Kulian446e8242017-10-26 15:17:29 -07004494 @Override
4495 public void handleWindowVisibility(IBinder token, boolean show) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004496 ActivityClientRecord r = mActivities.get(token);
Tim Murraye1e6c662015-04-07 13:24:14 -07004497
Dianne Hackbornbfddc0f2010-12-14 11:28:01 -08004498 if (r == null) {
4499 Log.w(TAG, "handleWindowVisibility: no activity for token " + token);
4500 return;
4501 }
Tim Murraye1e6c662015-04-07 13:24:14 -07004502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004503 if (!show && !r.stopped) {
Andrii Kulian829829c2018-03-19 18:19:05 -07004504 performStopActivityInner(r, null /* stopInfo */, show, false /* saveState */,
4505 false /* finalStateRequest */, "handleWindowVisibility");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004506 } else if (show && r.stopped) {
4507 // If we are getting ready to gc after going to the background, well
4508 // we are back active so skip it.
4509 unscheduleGcIdler();
4510
Andrii Kuliand25680c2018-02-21 15:16:58 -08004511 r.activity.performRestart(true /* start */, "handleWindowVisibility");
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004512 r.setState(ON_START);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004513 }
4514 if (r.activity.mDecor != null) {
Joe Onorato43a17652011-04-06 19:22:23 -07004515 if (false) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004516 TAG, "Handle window " + r + " visibility: " + show);
4517 updateVisibility(r, show);
4518 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004519 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520 }
4521
Wale Ogunwaleb5066fe2016-09-21 07:33:43 -07004522 // TODO: This method should be changed to use {@link #performStopActivityInner} to perform to
4523 // stop operation on the activity to reduce code duplication and the chance of fixing a bug in
4524 // one place and missing the other.
Romain Guy65b345f2011-07-27 18:51:50 -07004525 private void handleSleeping(IBinder token, boolean sleeping) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004526 ActivityClientRecord r = mActivities.get(token);
4527
4528 if (r == null) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08004529 Log.w(TAG, "handleSleeping: no activity for token " + token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004530 return;
4531 }
4532
4533 if (sleeping) {
Dianne Hackborn842e04b2011-01-22 13:00:12 -08004534 if (!r.stopped && !r.isPreHoneycomb()) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004535 callActivityOnStop(r, true /* saveState */, "sleeping");
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004536 }
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08004537
4538 // Make sure any pending writes are now committed.
4539 if (!r.isPreHoneycomb()) {
4540 QueuedWork.waitToFinish();
4541 }
4542
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004543 // Tell activity manager we slept.
4544 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004545 ActivityTaskManager.getService().activitySlept(r.token);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004546 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004547 throw ex.rethrowFromSystemServer();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004548 }
4549 } else {
4550 if (r.stopped && r.activity.mVisibleFromServer) {
Andrii Kuliand25680c2018-02-21 15:16:58 -08004551 r.activity.performRestart(true /* start */, "handleSleeping");
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004552 r.setState(ON_START);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004553 }
4554 }
4555 }
4556
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004557 private void handleSetCoreSettings(Bundle coreSettings) {
Craig Mautner88c05892013-06-28 09:47:45 -07004558 synchronized (mResourcesManager) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08004559 mCoreSettings = coreSettings;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004560 }
Jon Miranda836c0a82014-08-11 12:32:26 -07004561 onCoreSettingsChange();
4562 }
4563
4564 private void onCoreSettingsChange() {
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08004565 if (updateDebugViewAttributeState()) {
Jon Miranda836c0a82014-08-11 12:32:26 -07004566 // request all activities to relaunch for the changes to take place
Wale Ogunwale5527a502018-02-20 18:18:21 -08004567 relaunchAllActivities();
Fyodor Kupolovcb93d6f2017-05-04 17:27:16 -07004568 }
4569 }
4570
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08004571 private boolean updateDebugViewAttributeState() {
4572 boolean previousState = View.sDebugViewAttributes;
4573
4574 View.sDebugViewAttributesApplicationPackage = mCoreSettings.getString(
4575 Settings.Global.DEBUG_VIEW_ATTRIBUTES_APPLICATION_PACKAGE, "");
4576 String currentPackage = (mBoundApplication != null && mBoundApplication.appInfo != null)
4577 ? mBoundApplication.appInfo.packageName : "";
4578 View.sDebugViewAttributes =
4579 mCoreSettings.getInt(Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0
4580 || View.sDebugViewAttributesApplicationPackage.equals(currentPackage);
4581 return previousState != View.sDebugViewAttributes;
4582 }
4583
Wale Ogunwale5527a502018-02-20 18:18:21 -08004584 private void relaunchAllActivities() {
Fyodor Kupolovcb93d6f2017-05-04 17:27:16 -07004585 for (Map.Entry<IBinder, ActivityClientRecord> entry : mActivities.entrySet()) {
4586 final Activity activity = entry.getValue().activity;
4587 if (!activity.mFinished) {
Andrii Kulian320e3b52018-05-03 16:26:25 -07004588 scheduleRelaunchActivity(entry.getKey());
Jon Miranda836c0a82014-08-11 12:32:26 -07004589 }
4590 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004591 }
4592
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004593 private void handleUpdatePackageCompatibilityInfo(UpdateCompatibilityData data) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00004594 LoadedApk apk = peekPackageInfo(data.pkg, false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004595 if (apk != null) {
Craig Mautner48d0d182013-06-11 07:53:06 -07004596 apk.setCompatibilityInfo(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004597 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00004598 apk = peekPackageInfo(data.pkg, true);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004599 if (apk != null) {
Craig Mautner48d0d182013-06-11 07:53:06 -07004600 apk.setCompatibilityInfo(data.info);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004601 }
4602 handleConfigurationChanged(mConfiguration, data.info);
Jeff Brown98365d72012-08-19 20:30:52 -07004603 WindowManagerGlobal.getInstance().reportNewConfiguration(mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004604 }
4605
Andrii Kuliane55b0092018-04-19 15:29:22 -07004606 private void deliverResults(ActivityClientRecord r, List<ResultInfo> results, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004607 final int N = results.size();
4608 for (int i=0; i<N; i++) {
4609 ResultInfo ri = results.get(i);
4610 try {
4611 if (ri.mData != null) {
4612 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01004613 ri.mData.prepareToEnterProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004614 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004615 if (DEBUG_RESULTS) Slog.v(TAG,
Chris Tate8a7dc172009-03-24 20:11:42 -07004616 "Delivering result to activity " + r + " : " + ri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004617 r.activity.dispatchActivityResult(ri.mResultWho,
Andrii Kuliane55b0092018-04-19 15:29:22 -07004618 ri.mRequestCode, ri.mResultCode, ri.mData, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004619 } catch (Exception e) {
4620 if (!mInstrumentation.onException(r.activity, e)) {
4621 throw new RuntimeException(
4622 "Failure delivering result " + ri + " to activity "
4623 + r.intent.getComponent().toShortString()
4624 + ": " + e.toString(), e);
4625 }
4626 }
4627 }
4628 }
4629
Andrii Kulian446e8242017-10-26 15:17:29 -07004630 @Override
Andrii Kuliane55b0092018-04-19 15:29:22 -07004631 public void handleSendResult(IBinder token, List<ResultInfo> results, String reason) {
Andrii Kulian446e8242017-10-26 15:17:29 -07004632 ActivityClientRecord r = mActivities.get(token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004633 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004634 if (r != null) {
4635 final boolean resumed = !r.paused;
4636 if (!r.activity.mFinished && r.activity.mDecor != null
4637 && r.hideForNow && resumed) {
4638 // We had hidden the activity because it started another
4639 // one... we have gotten a result back and we are not
4640 // paused, so make sure our window is visible.
4641 updateVisibility(r, true);
4642 }
4643 if (resumed) {
4644 try {
4645 // Now we are idle.
4646 r.activity.mCalled = false;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004647 r.activity.mTemporaryPause = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004648 mInstrumentation.callActivityOnPause(r.activity);
4649 if (!r.activity.mCalled) {
4650 throw new SuperNotCalledException(
4651 "Activity " + r.intent.getComponent().toShortString()
4652 + " did not call through to super.onPause()");
4653 }
4654 } catch (SuperNotCalledException e) {
4655 throw e;
4656 } catch (Exception e) {
4657 if (!mInstrumentation.onException(r.activity, e)) {
4658 throw new RuntimeException(
4659 "Unable to pause activity "
4660 + r.intent.getComponent().toShortString()
4661 + ": " + e.toString(), e);
4662 }
4663 }
4664 }
Sudheer Shanka43b5ea42017-06-21 11:24:53 -07004665 checkAndBlockForNetworkAccess();
Andrii Kuliane55b0092018-04-19 15:29:22 -07004666 deliverResults(r, results, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004667 if (resumed) {
Andrii Kuliane55b0092018-04-19 15:29:22 -07004668 r.activity.performResume(false, reason);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004669 r.activity.mTemporaryPause = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004670 }
4671 }
4672 }
4673
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004674 /** Core implementation of activity destroy call. */
4675 ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
Bryce Leea33c13d2018-02-08 14:37:06 -08004676 int configChanges, boolean getNonConfigInstance, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004677 ActivityClientRecord r = mActivities.get(token);
Craig Mautner88c05892013-06-28 09:47:45 -07004678 Class<? extends Activity> activityClass = null;
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004679 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004680 if (r != null) {
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08004681 activityClass = r.activity.getClass();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 r.activity.mConfigChangeFlags |= configChanges;
4683 if (finishing) {
4684 r.activity.mFinished = true;
4685 }
Wale Ogunwale5dc6d652016-05-04 10:24:33 -07004686
4687 performPauseActivityIfNeeded(r, "destroy");
4688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004689 if (!r.stopped) {
Andrii Kulian8ae79572018-01-26 15:36:06 -08004690 callActivityOnStop(r, false /* saveState */, "destroy");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004691 }
4692 if (getNonConfigInstance) {
4693 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004694 r.lastNonConfigurationInstances
4695 = r.activity.retainNonConfigurationInstances();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004696 } catch (Exception e) {
4697 if (!mInstrumentation.onException(r.activity, e)) {
4698 throw new RuntimeException(
4699 "Unable to retain activity "
4700 + r.intent.getComponent().toShortString()
4701 + ": " + e.toString(), e);
4702 }
4703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004704 }
4705 try {
4706 r.activity.mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004707 mInstrumentation.callActivityOnDestroy(r.activity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004708 if (!r.activity.mCalled) {
4709 throw new SuperNotCalledException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004710 "Activity " + safeToComponentShortString(r.intent) +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004711 " did not call through to super.onDestroy()");
4712 }
4713 if (r.window != null) {
4714 r.window.closeAllPanels();
4715 }
4716 } catch (SuperNotCalledException e) {
4717 throw e;
4718 } catch (Exception e) {
4719 if (!mInstrumentation.onException(r.activity, e)) {
4720 throw new RuntimeException(
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004721 "Unable to destroy activity " + safeToComponentShortString(r.intent)
4722 + ": " + e.toString(), e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004723 }
4724 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08004725 r.setState(ON_DESTROY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004726 }
Tim Murray59f3dc12018-10-22 15:26:08 -07004727 schedulePurgeIdler();
Garfield Tan0443b372019-01-04 15:00:13 -08004728 // updatePendingActivityConfiguration() reads from mActivities to update
4729 // ActivityClientRecord which runs in a different thread. Protect modifications to
4730 // mActivities to avoid race.
4731 synchronized (mResourcesManager) {
4732 mActivities.remove(token);
4733 }
Brad Fitzpatrick5f8b5c12011-01-20 15:12:08 -08004734 StrictMode.decrementExpectedActivityCount(activityClass);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004735 return r;
4736 }
4737
Mitsuru Oshimad9aef732009-06-16 20:20:50 -07004738 private static String safeToComponentShortString(Intent intent) {
4739 ComponentName component = intent.getComponent();
4740 return component == null ? "[Unknown]" : component.toShortString();
4741 }
4742
Andrii Kulian446e8242017-10-26 15:17:29 -07004743 @Override
Riddle Hsud3062cb2018-06-30 02:06:42 +08004744 public Map<IBinder, ClientTransactionItem> getActivitiesToBeDestroyed() {
4745 return mActivitiesToBeDestroyed;
4746 }
4747
4748 @Override
Andrii Kulian446e8242017-10-26 15:17:29 -07004749 public void handleDestroyActivity(IBinder token, boolean finishing, int configChanges,
Bryce Leea33c13d2018-02-08 14:37:06 -08004750 boolean getNonConfigInstance, String reason) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004751 ActivityClientRecord r = performDestroyActivity(token, finishing,
Bryce Leea33c13d2018-02-08 14:37:06 -08004752 configChanges, getNonConfigInstance, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004753 if (r != null) {
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004754 cleanUpPendingRemoveWindows(r, finishing);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004755 WindowManager wm = r.activity.getWindowManager();
4756 View v = r.activity.mDecor;
4757 if (v != null) {
4758 if (r.activity.mVisibleFromServer) {
4759 mNumVisibleActivities--;
4760 }
4761 IBinder wtoken = v.getWindowToken();
4762 if (r.activity.mWindowAdded) {
Robert Carr77bdfb52016-05-02 18:18:31 -07004763 if (r.mPreserveWindow) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004764 // Hold off on removing this until the new activity's
4765 // window is being added.
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004766 r.mPendingRemoveWindow = r.window;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004767 r.mPendingRemoveWindowManager = wm;
Andrii Kulianeac0ea52016-05-11 15:50:24 -07004768 // We can only keep the part of the view hierarchy that we control,
4769 // everything else must be removed, because it might not be able to
4770 // behave properly when activity is relaunching.
4771 r.window.clearContentView();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004772 } else {
4773 wm.removeViewImmediate(v);
4774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004775 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004776 if (wtoken != null && r.mPendingRemoveWindow == null) {
Jeff Brown98365d72012-08-19 20:30:52 -07004777 WindowManagerGlobal.getInstance().closeAll(wtoken,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004778 r.activity.getClass().getName(), "Activity");
Andrii Kulianeac0ea52016-05-11 15:50:24 -07004779 } else if (r.mPendingRemoveWindow != null) {
4780 // We're preserving only one window, others should be closed so app views
4781 // will be detached before the final tear down. It should be done now because
4782 // some components (e.g. WebView) rely on detach callbacks to perform receiver
4783 // unregister and other cleanup.
4784 WindowManagerGlobal.getInstance().closeAllExceptView(token, v,
4785 r.activity.getClass().getName(), "Activity");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004786 }
4787 r.activity.mDecor = null;
4788 }
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004789 if (r.mPendingRemoveWindow == null) {
4790 // If we are delaying the removal of the activity window, then
4791 // we can't clean up all windows here. Note that we can't do
4792 // so later either, which means any windows that aren't closed
4793 // by the app will leak. Well we try to warning them a lot
4794 // about leaking windows, because that is a bug, so if they are
4795 // using this recreate facility then they get to live with leaks.
Jeff Brown98365d72012-08-19 20:30:52 -07004796 WindowManagerGlobal.getInstance().closeAll(token,
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004797 r.activity.getClass().getName(), "Activity");
4798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004799
4800 // Mocked out contexts won't be participating in the normal
4801 // process lifecycle, but if we're running with a proper
4802 // ApplicationContext we need to have it tear down things
4803 // cleanly.
4804 Context c = r.activity.getBaseContext();
Dianne Hackborn21556372010-02-04 16:34:40 -08004805 if (c instanceof ContextImpl) {
4806 ((ContextImpl) c).scheduleFinalCleanup(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004807 r.activity.getClass().getName(), "Activity");
4808 }
4809 }
4810 if (finishing) {
4811 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004812 ActivityTaskManager.getService().activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004813 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004814 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004815 }
4816 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004817 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004818 }
4819
Andrii Kulianb372da62018-01-18 10:46:24 -08004820 @Override
4821 public ActivityClientRecord prepareRelaunchActivity(IBinder token,
Dianne Hackborn85d558c2014-11-04 10:31:54 -08004822 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
Andrii Kulianb372da62018-01-18 10:46:24 -08004823 int configChanges, MergedConfiguration config, boolean preserveWindow) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004824 ActivityClientRecord target = null;
Andrii Kulianb372da62018-01-18 10:46:24 -08004825 boolean scheduleRelaunch = false;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004826
Craig Mautner88c05892013-06-28 09:47:45 -07004827 synchronized (mResourcesManager) {
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004828 for (int i=0; i<mRelaunchingActivities.size(); i++) {
4829 ActivityClientRecord r = mRelaunchingActivities.get(i);
Filip Gruszczynskic3b61792016-01-22 16:43:48 -08004830 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: " + this + ", trying: " + r);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004831 if (r.token == token) {
4832 target = r;
4833 if (pendingResults != null) {
4834 if (r.pendingResults != null) {
4835 r.pendingResults.addAll(pendingResults);
4836 } else {
4837 r.pendingResults = pendingResults;
4838 }
4839 }
4840 if (pendingNewIntents != null) {
4841 if (r.pendingIntents != null) {
4842 r.pendingIntents.addAll(pendingNewIntents);
4843 } else {
4844 r.pendingIntents = pendingNewIntents;
4845 }
4846 }
4847 break;
4848 }
4849 }
4850
4851 if (target == null) {
Andrii Kulianb372da62018-01-18 10:46:24 -08004852 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: target is null");
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004853 target = new ActivityClientRecord();
4854 target.token = token;
4855 target.pendingResults = pendingResults;
4856 target.pendingIntents = pendingNewIntents;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004857 target.mPreserveWindow = preserveWindow;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004858 mRelaunchingActivities.add(target);
Andrii Kulianb372da62018-01-18 10:46:24 -08004859 scheduleRelaunch = true;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004860 }
Andrii Kulianb372da62018-01-18 10:46:24 -08004861 target.createdConfig = config.getGlobalConfiguration();
4862 target.overrideConfig = config.getOverrideConfiguration();
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004863 target.pendingConfigChanges |= configChanges;
4864 }
Andrii Kulianb372da62018-01-18 10:46:24 -08004865
4866 return scheduleRelaunch ? target : null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004867 }
4868
Andrii Kulianb372da62018-01-18 10:46:24 -08004869 @Override
4870 public void handleRelaunchActivity(ActivityClientRecord tmp,
4871 PendingTransactionActions pendingActions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004872 // If we are getting ready to gc after going to the background, well
4873 // we are back active so skip it.
4874 unscheduleGcIdler();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07004875 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004876
4877 Configuration changedConfig = null;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004878 int configChanges = 0;
Bob Leee5408332009-09-04 18:31:17 -07004879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004880 // First: make sure we have the most recent configuration and most
4881 // recent version of the activity, or skip it if some previous call
4882 // had taken a more recent version.
Craig Mautner88c05892013-06-28 09:47:45 -07004883 synchronized (mResourcesManager) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004884 int N = mRelaunchingActivities.size();
4885 IBinder token = tmp.token;
4886 tmp = null;
4887 for (int i=0; i<N; i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004888 ActivityClientRecord r = mRelaunchingActivities.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004889 if (r.token == token) {
4890 tmp = r;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004891 configChanges |= tmp.pendingConfigChanges;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004892 mRelaunchingActivities.remove(i);
4893 i--;
4894 N--;
4895 }
4896 }
Bob Leee5408332009-09-04 18:31:17 -07004897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004898 if (tmp == null) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004899 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004900 return;
4901 }
Bob Leee5408332009-09-04 18:31:17 -07004902
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004903 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
4904 + tmp.token + " with configChanges=0x"
4905 + Integer.toHexString(configChanges));
4906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004907 if (mPendingConfiguration != null) {
4908 changedConfig = mPendingConfiguration;
4909 mPendingConfiguration = null;
4910 }
4911 }
Bob Leee5408332009-09-04 18:31:17 -07004912
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08004913 if (tmp.createdConfig != null) {
4914 // If the activity manager is passing us its current config,
4915 // assume that is really what we want regardless of what we
4916 // may have pending.
4917 if (mConfiguration == null
Dianne Hackborne36d6e22010-02-17 19:46:25 -08004918 || (tmp.createdConfig.isOtherSeqNewer(mConfiguration)
4919 && mConfiguration.diff(tmp.createdConfig) != 0)) {
4920 if (changedConfig == null
4921 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
4922 changedConfig = tmp.createdConfig;
4923 }
Dianne Hackborn871ecdc2009-12-11 15:24:33 -08004924 }
4925 }
Tim Murraye1e6c662015-04-07 13:24:14 -07004926
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004927 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004928 + tmp.token + ": changedConfig=" + changedConfig);
Tim Murraye1e6c662015-04-07 13:24:14 -07004929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004930 // If there was a pending configuration change, execute it first.
4931 if (changedConfig != null) {
Dianne Hackborn908aecc2012-07-31 16:37:34 -07004932 mCurDefaultDisplayDpi = changedConfig.densityDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -07004933 updateDefaultDensity();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004934 handleConfigurationChanged(changedConfig, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004935 }
Bob Leee5408332009-09-04 18:31:17 -07004936
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004937 ActivityClientRecord r = mActivities.get(tmp.token);
Dianne Hackborn399cccb2010-04-13 22:57:49 -07004938 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004939 if (r == null) {
4940 return;
4941 }
Bob Leee5408332009-09-04 18:31:17 -07004942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004943 r.activity.mConfigChangeFlags |= configChanges;
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07004944 r.mPreserveWindow = tmp.mPreserveWindow;
Bob Leee5408332009-09-04 18:31:17 -07004945
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004946 r.activity.mChangingConfigurations = true;
4947
Robert Carr23fa16b2016-01-13 13:19:58 -08004948 // If we are preserving the main window across relaunches we would also like to preserve
4949 // the children. However the client side view system does not support preserving
4950 // the child views so we notify the window manager to expect these windows to
4951 // be replaced and defer requests to destroy or hide them. This way we can achieve
4952 // visual continuity. It's important that we do this here prior to pause and destroy
4953 // as that is when we may hide or remove the child views.
Robert Carr77bdfb52016-05-02 18:18:31 -07004954 //
4955 // There is another scenario, if we have decided locally to relaunch the app from a
4956 // call to recreate, then none of the windows will be prepared for replacement or
4957 // preserved by the server, so we want to notify it that we are preparing to replace
4958 // everything
Robert Carr23fa16b2016-01-13 13:19:58 -08004959 try {
Andrii Kulianb372da62018-01-18 10:46:24 -08004960 if (r.mPreserveWindow) {
Robert Carr77bdfb52016-05-02 18:18:31 -07004961 WindowManagerGlobal.getWindowSession().prepareToReplaceWindows(
Andrii Kulianb372da62018-01-18 10:46:24 -08004962 r.token, true /* childrenOnly */);
Robert Carr23fa16b2016-01-13 13:19:58 -08004963 }
4964 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07004965 throw e.rethrowFromSystemServer();
Robert Carr23fa16b2016-01-13 13:19:58 -08004966 }
4967
Wale Ogunwale5527a502018-02-20 18:18:21 -08004968 handleRelaunchActivityInner(r, configChanges, tmp.pendingResults, tmp.pendingIntents,
4969 pendingActions, tmp.startsNotResumed, tmp.overrideConfig, "handleRelaunchActivity");
4970
4971 if (pendingActions != null) {
4972 // Only report a successful relaunch to WindowManager.
4973 pendingActions.setReportRelaunchToWindowManager(true);
Dianne Hackborne2b04802010-12-09 09:24:55 -08004974 }
Wale Ogunwale5527a502018-02-20 18:18:21 -08004975 }
4976
Andrii Kulian320e3b52018-05-03 16:26:25 -07004977 /**
4978 * Post a message to relaunch the activity. We do this instead of launching it immediately,
4979 * because this will destroy the activity from which it was called and interfere with the
4980 * lifecycle changes it was going through before. We need to make sure that we have finished
4981 * handling current transaction item before relaunching the activity.
4982 */
4983 void scheduleRelaunchActivity(IBinder token) {
4984 sendMessage(H.RELAUNCH_ACTIVITY, token);
4985 }
Bob Leee5408332009-09-04 18:31:17 -07004986
Andrii Kulian320e3b52018-05-03 16:26:25 -07004987 /** Performs the activity relaunch locally vs. requesting from system-server. */
4988 private void handleRelaunchActivityLocally(IBinder token) {
Wale Ogunwale5527a502018-02-20 18:18:21 -08004989 final ActivityClientRecord r = mActivities.get(token);
4990 if (r == null) {
Andrii Kulian320e3b52018-05-03 16:26:25 -07004991 Log.w(TAG, "Activity to relaunch no longer exists");
Wale Ogunwale5527a502018-02-20 18:18:21 -08004992 return;
4993 }
4994
4995 final int prevState = r.getLifecycleState();
4996
Andrii Kulian320e3b52018-05-03 16:26:25 -07004997 if (prevState < ON_RESUME || prevState > ON_STOP) {
4998 Log.w(TAG, "Activity state must be in [ON_RESUME..ON_STOP] in order to be relaunched,"
4999 + "current state is " + prevState);
Wale Ogunwale5527a502018-02-20 18:18:21 -08005000 return;
5001 }
5002
Wale Ogunwale5527a502018-02-20 18:18:21 -08005003
Andrii Kulian914aa7d2018-03-19 21:51:53 -07005004 // Initialize a relaunch request.
5005 final MergedConfiguration mergedConfiguration = new MergedConfiguration(
5006 r.createdConfig != null ? r.createdConfig : mConfiguration,
5007 r.overrideConfig);
5008 final ActivityRelaunchItem activityRelaunchItem = ActivityRelaunchItem.obtain(
5009 null /* pendingResults */, null /* pendingIntents */, 0 /* configChanges */,
5010 mergedConfiguration, r.mPreserveWindow);
5011 // Make sure to match the existing lifecycle state in the end of the transaction.
5012 final ActivityLifecycleItem lifecycleRequest =
5013 TransactionExecutorHelper.getLifecycleRequestForCurrentState(r);
5014 // Schedule the transaction.
5015 final ClientTransaction transaction = ClientTransaction.obtain(this.mAppThread, r.token);
5016 transaction.addCallback(activityRelaunchItem);
5017 transaction.setLifecycleStateRequest(lifecycleRequest);
5018 executeTransaction(transaction);
Wale Ogunwale5527a502018-02-20 18:18:21 -08005019 }
5020
5021 private void handleRelaunchActivityInner(ActivityClientRecord r, int configChanges,
5022 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingIntents,
5023 PendingTransactionActions pendingActions, boolean startsNotResumed,
5024 Configuration overrideConfig, String reason) {
Andrii Kulian770c4032018-05-02 18:40:59 -07005025 // Preserve last used intent, it may be set from Activity#setIntent().
5026 final Intent customIntent = r.activity.mIntent;
Wale Ogunwale5527a502018-02-20 18:18:21 -08005027 // Need to ensure state is saved.
5028 if (!r.paused) {
5029 performPauseActivity(r, false, reason, null /* pendingActions */);
5030 }
5031 if (!r.stopped) {
5032 callActivityOnStop(r, true /* saveState */, reason);
5033 }
5034
5035 handleDestroyActivity(r.token, false, configChanges, true, reason);
Bob Leee5408332009-09-04 18:31:17 -07005036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005037 r.activity = null;
5038 r.window = null;
5039 r.hideForNow = false;
5040 r.nextIdle = null;
The Android Open Source Project10592532009-03-18 17:39:46 -07005041 // Merge any pending results and pending intents; don't just replace them
Wale Ogunwale5527a502018-02-20 18:18:21 -08005042 if (pendingResults != null) {
The Android Open Source Project10592532009-03-18 17:39:46 -07005043 if (r.pendingResults == null) {
Wale Ogunwale5527a502018-02-20 18:18:21 -08005044 r.pendingResults = pendingResults;
The Android Open Source Project10592532009-03-18 17:39:46 -07005045 } else {
Wale Ogunwale5527a502018-02-20 18:18:21 -08005046 r.pendingResults.addAll(pendingResults);
The Android Open Source Project10592532009-03-18 17:39:46 -07005047 }
5048 }
Wale Ogunwale5527a502018-02-20 18:18:21 -08005049 if (pendingIntents != null) {
The Android Open Source Project10592532009-03-18 17:39:46 -07005050 if (r.pendingIntents == null) {
Wale Ogunwale5527a502018-02-20 18:18:21 -08005051 r.pendingIntents = pendingIntents;
The Android Open Source Project10592532009-03-18 17:39:46 -07005052 } else {
Wale Ogunwale5527a502018-02-20 18:18:21 -08005053 r.pendingIntents.addAll(pendingIntents);
The Android Open Source Project10592532009-03-18 17:39:46 -07005054 }
5055 }
Wale Ogunwale5527a502018-02-20 18:18:21 -08005056 r.startsNotResumed = startsNotResumed;
5057 r.overrideConfig = overrideConfig;
Bob Leee5408332009-09-04 18:31:17 -07005058
Andrii Kulian770c4032018-05-02 18:40:59 -07005059 handleLaunchActivity(r, pendingActions, customIntent);
Andrii Kulianb372da62018-01-18 10:46:24 -08005060 }
Jorim Jaggife89d122015-12-22 16:28:44 +01005061
Andrii Kulianb372da62018-01-18 10:46:24 -08005062 @Override
5063 public void reportRelaunch(IBinder token, PendingTransactionActions pendingActions) {
5064 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07005065 ActivityTaskManager.getService().activityRelaunched(token);
Andrii Kulianb372da62018-01-18 10:46:24 -08005066 final ActivityClientRecord r = mActivities.get(token);
5067 if (pendingActions.shouldReportRelaunchToWindowManager() && r != null
5068 && r.window != null) {
5069 r.window.reportActivityRelaunched();
Jorim Jaggife89d122015-12-22 16:28:44 +01005070 }
Andrii Kulianb372da62018-01-18 10:46:24 -08005071 } catch (RemoteException e) {
5072 throw e.rethrowFromSystemServer();
Jorim Jaggife89d122015-12-22 16:28:44 +01005073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005074 }
5075
Andrii Kulian8ae79572018-01-26 15:36:06 -08005076 private void callActivityOnSaveInstanceState(ActivityClientRecord r) {
Craig Mautnera0026042014-04-23 11:45:37 -07005077 r.state = new Bundle();
5078 r.state.setAllowFds(false);
5079 if (r.isPersistable()) {
5080 r.persistentState = new PersistableBundle();
5081 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state,
5082 r.persistentState);
5083 } else {
5084 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
5085 }
5086 }
5087
Dianne Hackborn73c14162012-09-19 15:45:06 -07005088 ArrayList<ComponentCallbacks2> collectComponentCallbacks(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005089 boolean allActivities, Configuration newConfig) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005090 ArrayList<ComponentCallbacks2> callbacks
5091 = new ArrayList<ComponentCallbacks2>();
Bob Leee5408332009-09-04 18:31:17 -07005092
Craig Mautner88c05892013-06-28 09:47:45 -07005093 synchronized (mResourcesManager) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005094 final int NAPP = mAllApplications.size();
5095 for (int i=0; i<NAPP; i++) {
Dianne Hackborn73c14162012-09-19 15:45:06 -07005096 callbacks.add(mAllApplications.get(i));
5097 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005098 final int NACT = mActivities.size();
5099 for (int i=0; i<NACT; i++) {
5100 ActivityClientRecord ar = mActivities.valueAt(i);
5101 Activity a = ar.activity;
5102 if (a != null) {
5103 Configuration thisConfig = applyConfigCompatMainThread(
5104 mCurDefaultDisplayDpi, newConfig,
Todd Kennedy233a0b12018-01-29 20:30:24 +00005105 ar.packageInfo.getCompatibilityInfo());
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005106 if (!ar.activity.mFinished && (allActivities || !ar.paused)) {
5107 // If the activity is currently resumed, its configuration
5108 // needs to change right now.
5109 callbacks.add(a);
5110 } else if (thisConfig != null) {
5111 // Otherwise, we will tell it about the change
5112 // the next time it is resumed or shown. Note that
5113 // the activity manager may, before then, decide the
5114 // activity needs to be destroyed to handle its new
5115 // configuration.
5116 if (DEBUG_CONFIGURATION) {
5117 Slog.v(TAG, "Setting activity "
5118 + ar.activityInfo.name + " newConfig=" + thisConfig);
Romain Guya998dff2012-03-23 18:58:36 -07005119 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005120 ar.newConfig = thisConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005121 }
5122 }
5123 }
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005124 final int NSVC = mServices.size();
5125 for (int i=0; i<NSVC; i++) {
5126 callbacks.add(mServices.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005127 }
5128 }
5129 synchronized (mProviderMap) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07005130 final int NPRV = mLocalProviders.size();
5131 for (int i=0; i<NPRV; i++) {
5132 callbacks.add(mLocalProviders.valueAt(i).mLocalProvider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005133 }
5134 }
Bob Leee5408332009-09-04 18:31:17 -07005135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005136 return callbacks;
5137 }
Bob Leee5408332009-09-04 18:31:17 -07005138
Adam Lesinski082614c2016-03-04 14:33:47 -08005139 /**
5140 * Updates the configuration for an Activity. The ActivityClientRecord's
5141 * {@link ActivityClientRecord#overrideConfig} is used to compute the final Configuration for
5142 * that Activity. {@link ActivityClientRecord#tmpConfig} is used as a temporary for delivering
5143 * the updated Configuration.
5144 * @param r ActivityClientRecord representing the Activity.
5145 * @param newBaseConfig The new configuration to use. This may be augmented with
5146 * {@link ActivityClientRecord#overrideConfig}.
Adam Lesinski082614c2016-03-04 14:33:47 -08005147 */
5148 private void performConfigurationChangedForActivity(ActivityClientRecord r,
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005149 Configuration newBaseConfig) {
5150 performConfigurationChangedForActivity(r, newBaseConfig,
Yohei Yukawa5281b6b2018-10-15 07:38:25 +08005151 r.activity.getDisplayId(), false /* movedToDifferentDisplay */);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005152 }
5153
5154 /**
5155 * Updates the configuration for an Activity. The ActivityClientRecord's
5156 * {@link ActivityClientRecord#overrideConfig} is used to compute the final Configuration for
5157 * that Activity. {@link ActivityClientRecord#tmpConfig} is used as a temporary for delivering
5158 * the updated Configuration.
5159 * @param r ActivityClientRecord representing the Activity.
5160 * @param newBaseConfig The new configuration to use. This may be augmented with
5161 * {@link ActivityClientRecord#overrideConfig}.
5162 * @param displayId The id of the display where the Activity currently resides.
5163 * @param movedToDifferentDisplay Indicates if the activity was moved to different display.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005164 * @return {@link Configuration} instance sent to client, null if not sent.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005165 */
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005166 private Configuration performConfigurationChangedForActivity(ActivityClientRecord r,
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005167 Configuration newBaseConfig, int displayId, boolean movedToDifferentDisplay) {
Adam Lesinski082614c2016-03-04 14:33:47 -08005168 r.tmpConfig.setTo(newBaseConfig);
5169 if (r.overrideConfig != null) {
5170 r.tmpConfig.updateFrom(r.overrideConfig);
5171 }
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005172 final Configuration reportedConfig = performActivityConfigurationChanged(r.activity,
5173 r.tmpConfig, r.overrideConfig, displayId, movedToDifferentDisplay);
Adam Lesinski082614c2016-03-04 14:33:47 -08005174 freeTextLayoutCachesIfNeeded(r.activity.mCurrentConfig.diff(r.tmpConfig));
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005175 return reportedConfig;
Adam Lesinski082614c2016-03-04 14:33:47 -08005176 }
5177
5178 /**
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -07005179 * Creates a new Configuration only if override would modify base. Otherwise returns base.
5180 * @param base The base configuration.
5181 * @param override The update to apply to the base configuration. Can be null.
5182 * @return A Configuration representing base with override applied.
5183 */
5184 private static Configuration createNewConfigAndUpdateIfNotNull(@NonNull Configuration base,
5185 @Nullable Configuration override) {
5186 if (override == null) {
5187 return base;
5188 }
5189 Configuration newConfig = new Configuration(base);
5190 newConfig.updateFrom(override);
5191 return newConfig;
5192 }
5193
5194 /**
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005195 * Decides whether to update a component's configuration and whether to inform it.
Adam Lesinski082614c2016-03-04 14:33:47 -08005196 * @param cb The component callback to notify of configuration change.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005197 * @param newConfig The new configuration.
5198 */
5199 private void performConfigurationChanged(ComponentCallbacks2 cb, Configuration newConfig) {
5200 if (!REPORT_TO_ACTIVITY) {
5201 return;
5202 }
5203
5204 // ContextThemeWrappers may override the configuration for that context. We must check and
5205 // apply any overrides defined.
5206 Configuration contextThemeWrapperOverrideConfig = null;
5207 if (cb instanceof ContextThemeWrapper) {
5208 final ContextThemeWrapper contextThemeWrapper = (ContextThemeWrapper) cb;
5209 contextThemeWrapperOverrideConfig = contextThemeWrapper.getOverrideConfiguration();
5210 }
5211
5212 // Apply the ContextThemeWrapper override if necessary.
5213 // NOTE: Make sure the configurations are not modified, as they are treated as immutable
5214 // in many places.
5215 final Configuration configToReport = createNewConfigAndUpdateIfNotNull(
5216 newConfig, contextThemeWrapperOverrideConfig);
5217 cb.onConfigurationChanged(configToReport);
5218 }
5219
5220 /**
5221 * Decides whether to update an Activity's configuration and whether to inform it.
5222 * @param activity The activity to notify of configuration change.
Adam Lesinski082614c2016-03-04 14:33:47 -08005223 * @param newConfig The new configuration.
Adam Lesinskic1b0ebf2016-06-09 11:17:10 -07005224 * @param amOverrideConfig The override config that differentiates the Activity's configuration
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005225 * from the base global configuration. This is supplied by
5226 * ActivityManager.
5227 * @param displayId Id of the display where activity currently resides.
5228 * @param movedToDifferentDisplay Indicates if the activity was moved to different display.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005229 * @return Configuration sent to client, null if no changes and not moved to different display.
Adam Lesinski082614c2016-03-04 14:33:47 -08005230 */
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005231 private Configuration performActivityConfigurationChanged(Activity activity,
5232 Configuration newConfig, Configuration amOverrideConfig, int displayId,
5233 boolean movedToDifferentDisplay) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005234 if (activity == null) {
5235 throw new IllegalArgumentException("No activity provided.");
5236 }
5237 final IBinder activityToken = activity.getActivityToken();
5238 if (activityToken == null) {
5239 throw new IllegalArgumentException("Activity token not set. Is the activity attached?");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005240 }
Bob Leee5408332009-09-04 18:31:17 -07005241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005242 boolean shouldChangeConfig = false;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005243 if (activity.mCurrentConfig == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005244 shouldChangeConfig = true;
5245 } else {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005246 // If the new config is the same as the config this Activity is already running with and
5247 // the override config also didn't change, then don't bother calling
5248 // onConfigurationChanged.
Bryce Lee658d9842017-07-28 08:33:36 -07005249 final int diff = activity.mCurrentConfig.diffPublicOnly(newConfig);
5250
Andrii Kulian3b3c9142016-07-18 19:15:56 -07005251 if (diff != 0 || !mResourcesManager.isSameResourcesOverrideConfig(activityToken,
5252 amOverrideConfig)) {
Chong Zhang4951f9d2016-06-23 13:15:08 -07005253 // Always send the task-level config changes. For system-level configuration, if
5254 // this activity doesn't handle any of the config changes, then don't bother
5255 // calling onConfigurationChanged as we're going to destroy it.
5256 if (!mUpdatingSystemConfig
5257 || (~activity.mActivityInfo.getRealConfigChanged() & diff) == 0
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005258 || !REPORT_TO_ACTIVITY) {
Chong Zhang4951f9d2016-06-23 13:15:08 -07005259 shouldChangeConfig = true;
5260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005261 }
5262 }
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005263 if (!shouldChangeConfig && !movedToDifferentDisplay) {
5264 // Nothing significant, don't proceed with updating and reporting.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005265 return null;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005266 }
5267
5268 // Propagate the configuration change to ResourcesManager and Activity.
5269
5270 // ContextThemeWrappers may override the configuration for that context. We must check and
5271 // apply any overrides defined.
5272 Configuration contextThemeWrapperOverrideConfig = activity.getOverrideConfiguration();
5273
5274 // We only update an Activity's configuration if this is not a global configuration change.
5275 // This must also be done before the callback, or else we violate the contract that the new
5276 // resources are available in ComponentCallbacks2#onConfigurationChanged(Configuration).
5277 // Also apply the ContextThemeWrapper override if necessary.
5278 // NOTE: Make sure the configurations are not modified, as they are treated as immutable in
5279 // many places.
5280 final Configuration finalOverrideConfig = createNewConfigAndUpdateIfNotNull(
5281 amOverrideConfig, contextThemeWrapperOverrideConfig);
5282 mResourcesManager.updateResourcesForActivity(activityToken, finalOverrideConfig,
5283 displayId, movedToDifferentDisplay);
5284
5285 activity.mConfigChangeFlags = 0;
5286 activity.mCurrentConfig = new Configuration(newConfig);
5287
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005288 // Apply the ContextThemeWrapper override if necessary.
5289 // NOTE: Make sure the configurations are not modified, as they are treated as immutable
5290 // in many places.
5291 final Configuration configToReport = createNewConfigAndUpdateIfNotNull(newConfig,
5292 contextThemeWrapperOverrideConfig);
5293
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005294 if (!REPORT_TO_ACTIVITY) {
5295 // Not configured to report to activity.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005296 return configToReport;
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005297 }
5298
5299 if (movedToDifferentDisplay) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005300 activity.dispatchMovedToDisplay(displayId, configToReport);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005301 }
Bob Leee5408332009-09-04 18:31:17 -07005302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005303 if (shouldChangeConfig) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005304 activity.mCalled = false;
5305 activity.onConfigurationChanged(configToReport);
5306 if (!activity.mCalled) {
5307 throw new SuperNotCalledException("Activity " + activity.getLocalClassName() +
5308 " did not call through to super.onConfigurationChanged()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005309 }
5310 }
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005311
5312 return configToReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005313 }
5314
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07005315 public final void applyConfigurationToResources(Configuration config) {
Craig Mautner88c05892013-06-28 09:47:45 -07005316 synchronized (mResourcesManager) {
5317 mResourcesManager.applyConfigurationToResourcesLocked(config, null);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07005318 }
5319 }
5320
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005321 final Configuration applyCompatConfiguration(int displayDensity) {
Dianne Hackborn836e2622011-10-04 18:32:39 -07005322 Configuration config = mConfiguration;
5323 if (mCompatConfiguration == null) {
5324 mCompatConfiguration = new Configuration();
5325 }
5326 mCompatConfiguration.setTo(mConfiguration);
Adam Lesinski082614c2016-03-04 14:33:47 -08005327 if (mResourcesManager.applyCompatConfigurationLocked(displayDensity,
5328 mCompatConfiguration)) {
Dianne Hackborn836e2622011-10-04 18:32:39 -07005329 config = mCompatConfiguration;
5330 }
5331 return config;
5332 }
5333
Andrii Kulian446e8242017-10-26 15:17:29 -07005334 @Override
5335 public void handleConfigurationChanged(Configuration config) {
5336 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "configChanged");
5337 mCurDefaultDisplayDpi = config.densityDpi;
5338 mUpdatingSystemConfig = true;
5339 try {
5340 handleConfigurationChanged(config, null /* compat */);
5341 } finally {
5342 mUpdatingSystemConfig = false;
5343 }
5344 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
5345 }
5346
5347 private void handleConfigurationChanged(Configuration config, CompatibilityInfo compat) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005348
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005349 int configDiff = 0;
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005350
Bryce Lee658d9842017-07-28 08:33:36 -07005351 // This flag tracks whether the new configuration is fundamentally equivalent to the
5352 // existing configuration. This is necessary to determine whether non-activity
5353 // callbacks should receive notice when the only changes are related to non-public fields.
5354 // We do not gate calling {@link #performActivityConfigurationChanged} based on this flag
5355 // as that method uses the same check on the activity config override as well.
5356 final boolean equivalent = config != null && mConfiguration != null
5357 && (0 == mConfiguration.diffPublicOnly(config));
Todd Kennedy35a9a382018-01-25 13:25:37 -08005358 final Theme systemTheme = getSystemContext().getTheme();
5359 final Theme systemUiTheme = getSystemUiContext().getTheme();
Bryce Lee658d9842017-07-28 08:33:36 -07005360
Craig Mautner88c05892013-06-28 09:47:45 -07005361 synchronized (mResourcesManager) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005362 if (mPendingConfiguration != null) {
5363 if (!mPendingConfiguration.isOtherSeqNewer(config)) {
5364 config = mPendingConfiguration;
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005365 mCurDefaultDisplayDpi = config.densityDpi;
Dianne Hackborndde331c2012-08-03 14:01:57 -07005366 updateDefaultDensity();
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005367 }
5368 mPendingConfiguration = null;
5369 }
5370
5371 if (config == null) {
5372 return;
5373 }
Tim Murraye1e6c662015-04-07 13:24:14 -07005374
Dianne Hackborn399cccb2010-04-13 22:57:49 -07005375 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle configuration changed: "
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005376 + config);
Craig Mautner88c05892013-06-28 09:47:45 -07005377
5378 mResourcesManager.applyConfigurationToResourcesLocked(config, compat);
Adam Lesinskib61e4052016-05-19 18:23:05 -07005379 updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
5380 mResourcesManager.getConfiguration().getLocales());
Craig Mautner88c05892013-06-28 09:47:45 -07005381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005382 if (mConfiguration == null) {
5383 mConfiguration = new Configuration();
5384 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04005385 if (!mConfiguration.isOtherSeqNewer(config) && compat == null) {
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005386 return;
5387 }
Alan Viverettee54d2452015-05-06 10:41:43 -07005388
5389 configDiff = mConfiguration.updateFrom(config);
Dianne Hackborn908aecc2012-07-31 16:37:34 -07005390 config = applyCompatConfiguration(mCurDefaultDisplayDpi);
Alan Viverette395cd012015-08-11 17:27:04 -04005391
Alan Viverette395cd012015-08-11 17:27:04 -04005392 if ((systemTheme.getChangingConfigurations() & configDiff) != 0) {
5393 systemTheme.rebase();
5394 }
Adam Lesinskia82b6262017-03-21 16:56:17 -07005395
Adam Lesinskia82b6262017-03-21 16:56:17 -07005396 if ((systemUiTheme.getChangingConfigurations() & configDiff) != 0) {
5397 systemUiTheme.rebase();
5398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005399 }
Dianne Hackborn73c14162012-09-19 15:45:06 -07005400
5401 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(false, config);
5402
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005403 freeTextLayoutCachesIfNeeded(configDiff);
5404
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005405 if (callbacks != null) {
5406 final int N = callbacks.size();
5407 for (int i=0; i<N; i++) {
Andrii Kulian701214b2016-04-07 09:36:33 -07005408 ComponentCallbacks2 cb = callbacks.get(i);
5409 if (cb instanceof Activity) {
5410 // If callback is an Activity - call corresponding method to consider override
5411 // config and avoid onConfigurationChanged if it hasn't changed.
5412 Activity a = (Activity) cb;
5413 performConfigurationChangedForActivity(mActivities.get(a.getActivityToken()),
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005414 config);
Bryce Lee658d9842017-07-28 08:33:36 -07005415 } else if (!equivalent) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005416 performConfigurationChanged(cb, config);
Andrii Kulian701214b2016-04-07 09:36:33 -07005417 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08005418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005419 }
5420 }
5421
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005422 void handleApplicationInfoChanged(@NonNull final ApplicationInfo ai) {
Adam Lesinskid33ef562017-01-19 14:49:59 -08005423 // Updates triggered by package installation go through a package update
5424 // receiver. Here we try to capture ApplicationInfo changes that are
5425 // caused by other sources, such as overlays. That means we want to be as conservative
5426 // about code changes as possible. Take the diff of the old ApplicationInfo and the new
5427 // to see if anything needs to change.
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005428 LoadedApk apk;
5429 LoadedApk resApk;
5430 // Update all affected loaded packages with new package information
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005431 synchronized (mResourcesManager) {
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005432 WeakReference<LoadedApk> ref = mPackages.get(ai.packageName);
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005433 apk = ref != null ? ref.get() : null;
Fyodor Kupolovb7865ce2017-05-05 15:08:03 -07005434 ref = mResourcePackages.get(ai.packageName);
5435 resApk = ref != null ? ref.get() : null;
5436 }
5437 if (apk != null) {
5438 final ArrayList<String> oldPaths = new ArrayList<>();
5439 LoadedApk.makePaths(this, apk.getApplicationInfo(), oldPaths);
5440 apk.updateApplicationInfo(ai, oldPaths);
5441 }
5442 if (resApk != null) {
5443 final ArrayList<String> oldPaths = new ArrayList<>();
5444 LoadedApk.makePaths(this, resApk.getApplicationInfo(), oldPaths);
5445 resApk.updateApplicationInfo(ai, oldPaths);
5446 }
5447 synchronized (mResourcesManager) {
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005448 // Update all affected Resources objects to use new ResourcesImpl
5449 mResourcesManager.applyNewResourceDirsLocked(ai.sourceDir, ai.resourceDirs);
5450 }
5451
5452 ApplicationPackageManager.configurationChanged();
5453
5454 // Trigger a regular Configuration change event, only with a different assetsSeq number
5455 // so that we actually call through to all components.
Adam Lesinskia82b6262017-03-21 16:56:17 -07005456 // TODO(adamlesinski): Change this to make use of ActivityManager's upcoming ability to
5457 // store configurations per-process.
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005458 Configuration newConfig = new Configuration();
Adam Lesinskia82b6262017-03-21 16:56:17 -07005459 newConfig.assetsSeq = (mConfiguration != null ? mConfiguration.assetsSeq : 0) + 1;
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005460 handleConfigurationChanged(newConfig, null);
5461
Wale Ogunwale5527a502018-02-20 18:18:21 -08005462 relaunchAllActivities();
MÃ¥rten Kongstad49a4a1d2017-01-12 08:36:37 +01005463 }
5464
Romain Guy46bfc482013-08-16 18:38:29 -07005465 static void freeTextLayoutCachesIfNeeded(int configDiff) {
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005466 if (configDiff != 0) {
5467 // Ask text layout engine to free its caches if there is a locale change
5468 boolean hasLocaleConfigChange = ((configDiff & ActivityInfo.CONFIG_LOCALE) != 0);
5469 if (hasLocaleConfigChange) {
5470 Canvas.freeTextLayoutCaches();
5471 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Cleared TextLayout Caches");
5472 }
5473 }
5474 }
5475
Garfield Tan0443b372019-01-04 15:00:13 -08005476 @Override
5477 public void updatePendingActivityConfiguration(IBinder activityToken,
5478 Configuration overrideConfig) {
5479 final ActivityClientRecord r;
5480 synchronized (mResourcesManager) {
5481 r = mActivities.get(activityToken);
5482 }
5483
5484 if (r == null) {
5485 if (DEBUG_CONFIGURATION) {
5486 Slog.w(TAG, "Not found target activity to update its pending config.");
5487 }
5488 return;
5489 }
5490
5491 synchronized (r) {
5492 r.mPendingOverrideConfig = overrideConfig;
5493 }
5494 }
5495
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005496 /**
5497 * Handle new activity configuration and/or move to a different display.
Andrii Kulian446e8242017-10-26 15:17:29 -07005498 * @param activityToken Target activity token.
5499 * @param overrideConfig Activity override config.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005500 * @param displayId Id of the display where activity was moved to, -1 if there was no move and
5501 * value didn't change.
5502 */
Andrii Kulian446e8242017-10-26 15:17:29 -07005503 @Override
5504 public void handleActivityConfigurationChanged(IBinder activityToken,
5505 Configuration overrideConfig, int displayId) {
5506 ActivityClientRecord r = mActivities.get(activityToken);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005507 // Check input params.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005508 if (r == null || r.activity == null) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005509 if (DEBUG_CONFIGURATION) Slog.w(TAG, "Not found target activity to report to: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005510 return;
5511 }
Andrii Kulian51c1b672017-04-07 18:39:32 -07005512 final boolean movedToDifferentDisplay = displayId != INVALID_DISPLAY
Yohei Yukawa5281b6b2018-10-15 07:38:25 +08005513 && displayId != r.activity.getDisplayId();
Bob Leee5408332009-09-04 18:31:17 -07005514
Garfield Tan0443b372019-01-04 15:00:13 -08005515 synchronized (r) {
5516 if (r.mPendingOverrideConfig != null
5517 && !r.mPendingOverrideConfig.isOtherSeqNewer(overrideConfig)) {
5518 overrideConfig = r.mPendingOverrideConfig;
5519 }
5520 r.mPendingOverrideConfig = null;
5521 }
5522
5523 if (r.overrideConfig != null && !r.overrideConfig.isOtherSeqNewer(overrideConfig)
5524 && !movedToDifferentDisplay) {
5525 if (DEBUG_CONFIGURATION) {
5526 Slog.v(TAG, "Activity already handled newer configuration so drop this"
5527 + " transaction. overrideConfig=" + overrideConfig + " r.overrideConfig="
5528 + r.overrideConfig);
5529 }
5530 return;
5531 }
5532
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005533 // Perform updates.
Andrii Kulian446e8242017-10-26 15:17:29 -07005534 r.overrideConfig = overrideConfig;
Stephen Kiazykf903b732017-03-20 16:23:45 -07005535 final ViewRootImpl viewRoot = r.activity.mDecor != null
5536 ? r.activity.mDecor.getViewRootImpl() : null;
5537
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005538 if (movedToDifferentDisplay) {
5539 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity moved to display, activity:"
5540 + r.activityInfo.name + ", displayId=" + displayId
Andrii Kulian446e8242017-10-26 15:17:29 -07005541 + ", config=" + overrideConfig);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005542
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005543 final Configuration reportedConfig = performConfigurationChangedForActivity(r,
5544 mCompatConfiguration, displayId, true /* movedToDifferentDisplay */);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005545 if (viewRoot != null) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005546 viewRoot.onMovedToDisplay(displayId, reportedConfig);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005547 }
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005548 } else {
5549 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handle activity config changed: "
Andrii Kulian446e8242017-10-26 15:17:29 -07005550 + r.activityInfo.name + ", config=" + overrideConfig);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08005551 performConfigurationChangedForActivity(r, mCompatConfiguration);
5552 }
Andrii Kulian44607962017-03-16 11:06:24 -07005553 // Notify the ViewRootImpl instance about configuration changes. It may have initiated this
5554 // update to make sure that resources are updated before updating itself.
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005555 if (viewRoot != null) {
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07005556 viewRoot.updateConfiguration(displayId);
Andrii Kuliance1ecf12017-03-17 14:58:36 -07005557 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07005558 mSomeActivitiesChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005559 }
5560
Jeff Hao1b012d32014-08-20 10:35:34 -07005561 final void handleProfilerControl(boolean start, ProfilerInfo profilerInfo, int profileType) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005562 if (start) {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005563 try {
Romain Guy7eabe552011-07-21 14:56:34 -07005564 switch (profileType) {
Jeff Hao1b012d32014-08-20 10:35:34 -07005565 default:
5566 mProfiler.setProfiler(profilerInfo);
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005567 mProfiler.startProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07005568 break;
5569 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005570 } catch (RuntimeException e) {
Jeff Hao1b012d32014-08-20 10:35:34 -07005571 Slog.w(TAG, "Profiling failed on path " + profilerInfo.profileFile
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005572 + " -- can the process access this path?");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -07005573 } finally {
Andreas Gampe2b073a02017-06-22 17:28:57 -07005574 profilerInfo.closeFd();
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005575 }
5576 } else {
Romain Guy7eabe552011-07-21 14:56:34 -07005577 switch (profileType) {
Romain Guy7eabe552011-07-21 14:56:34 -07005578 default:
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005579 mProfiler.stopProfiling();
Romain Guy7eabe552011-07-21 14:56:34 -07005580 break;
Romain Guy7eabe552011-07-21 14:56:34 -07005581 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -08005582 }
5583 }
Bob Leee5408332009-09-04 18:31:17 -07005584
Andreas Gampe4c79fea2016-01-28 20:11:41 -08005585 /**
5586 * Public entrypoint to stop profiling. This is required to end profiling when the app crashes,
5587 * so that profiler data won't be lost.
5588 *
5589 * @hide
5590 */
5591 public void stopProfiling() {
Amith Yamasanib1684432017-01-26 14:57:20 -08005592 if (mProfiler != null) {
5593 mProfiler.stopProfiling();
5594 }
Andreas Gampe4c79fea2016-01-28 20:11:41 -08005595 }
5596
Christopher Ferris8d652f82017-04-11 16:29:18 -07005597 static void handleDumpHeap(DumpHeapData dhd) {
Makoto Onuki4556b7b2017-07-07 14:58:58 -07005598 if (dhd.runGc) {
5599 System.gc();
5600 System.runFinalization();
5601 System.gc();
5602 }
Christopher Ferris8d652f82017-04-11 16:29:18 -07005603 if (dhd.managed) {
Andy McFadden824c5102010-07-09 16:26:57 -07005604 try {
5605 Debug.dumpHprofData(dhd.path, dhd.fd.getFileDescriptor());
5606 } catch (IOException e) {
5607 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
5608 + " -- can the process access this path?");
5609 } finally {
5610 try {
5611 dhd.fd.close();
5612 } catch (IOException e) {
5613 Slog.w(TAG, "Failure closing profile fd", e);
5614 }
5615 }
Christopher Ferris8d652f82017-04-11 16:29:18 -07005616 } else if (dhd.mallocInfo) {
5617 Debug.dumpNativeMallocInfo(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07005618 } else {
Andy McFadden06a6b552010-07-13 16:28:09 -07005619 Debug.dumpNativeHeap(dhd.fd.getFileDescriptor());
Andy McFadden824c5102010-07-09 16:26:57 -07005620 }
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005621 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005622 ActivityManager.getService().dumpHeapFinished(dhd.path);
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005623 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005624 throw e.rethrowFromSystemServer();
Dianne Hackbornb9a5e4a2015-03-03 17:04:12 -08005625 }
Makoto Onuki2c6657f2018-06-06 15:24:02 -07005626 if (dhd.finishCallback != null) {
5627 dhd.finishCallback.sendResult(null);
5628 }
Andy McFadden824c5102010-07-09 16:26:57 -07005629 }
5630
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005631 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005632 boolean hasPkgInfo = false;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005633 switch (cmd) {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005634 case ApplicationThreadConstants.PACKAGE_REMOVED:
5635 case ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL:
Todd Kennedy39bfee52016-02-24 10:28:21 -08005636 {
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005637 final boolean killApp = cmd == ApplicationThreadConstants.PACKAGE_REMOVED;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005638 if (packages == null) {
5639 break;
5640 }
5641 synchronized (mResourcesManager) {
5642 for (int i = packages.length - 1; i >= 0; i--) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005643 if (!hasPkgInfo) {
Todd Kennedy39bfee52016-02-24 10:28:21 -08005644 WeakReference<LoadedApk> ref = mPackages.get(packages[i]);
5645 if (ref != null && ref.get() != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005646 hasPkgInfo = true;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005647 } else {
5648 ref = mResourcePackages.get(packages[i]);
5649 if (ref != null && ref.get() != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005650 hasPkgInfo = true;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005651 }
5652 }
5653 }
5654 if (killApp) {
5655 mPackages.remove(packages[i]);
5656 mResourcePackages.remove(packages[i]);
5657 }
5658 }
5659 }
5660 break;
5661 }
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005662 case ApplicationThreadConstants.PACKAGE_REPLACED:
Todd Kennedy39bfee52016-02-24 10:28:21 -08005663 {
5664 if (packages == null) {
5665 break;
5666 }
5667 synchronized (mResourcesManager) {
5668 for (int i = packages.length - 1; i >= 0; i--) {
5669 WeakReference<LoadedApk> ref = mPackages.get(packages[i]);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005670 LoadedApk pkgInfo = ref != null ? ref.get() : null;
5671 if (pkgInfo != null) {
5672 hasPkgInfo = true;
mark_chen89764e32014-12-12 15:38:48 +08005673 } else {
5674 ref = mResourcePackages.get(packages[i]);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005675 pkgInfo = ref != null ? ref.get() : null;
5676 if (pkgInfo != null) {
5677 hasPkgInfo = true;
mark_chen89764e32014-12-12 15:38:48 +08005678 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005679 }
Todd Kennedy39bfee52016-02-24 10:28:21 -08005680 // If the package is being replaced, yet it still has a valid
5681 // LoadedApk object, the package was updated with _DONT_KILL.
5682 // Adjust it's internal references to the application info and
5683 // resources.
Todd Kennedy233a0b12018-01-29 20:30:24 +00005684 if (pkgInfo != null) {
Todd Kennedy39bfee52016-02-24 10:28:21 -08005685 try {
5686 final String packageName = packages[i];
5687 final ApplicationInfo aInfo =
5688 sPackageManager.getApplicationInfo(
5689 packageName,
Svet Ganov6ce92392017-09-27 16:04:10 -07005690 PackageManager.GET_SHARED_LIBRARY_FILES,
Todd Kennedy39bfee52016-02-24 10:28:21 -08005691 UserHandle.myUserId());
5692
5693 if (mActivities.size() > 0) {
5694 for (ActivityClientRecord ar : mActivities.values()) {
5695 if (ar.activityInfo.applicationInfo.packageName
5696 .equals(packageName)) {
5697 ar.activityInfo.applicationInfo = aInfo;
Todd Kennedy233a0b12018-01-29 20:30:24 +00005698 ar.packageInfo = pkgInfo;
Todd Kennedy39bfee52016-02-24 10:28:21 -08005699 }
5700 }
5701 }
Todd Kennedyb9656a92018-05-02 10:59:45 +01005702 final ArrayList<String> oldPaths = new ArrayList<>();
5703 LoadedApk.makePaths(this, pkgInfo.getApplicationInfo(), oldPaths);
Todd Kennedy233a0b12018-01-29 20:30:24 +00005704 pkgInfo.updateApplicationInfo(aInfo, oldPaths);
Todd Kennedy39bfee52016-02-24 10:28:21 -08005705 } catch (RemoteException e) {
5706 }
5707 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005708 }
5709 }
Todd Kennedy39bfee52016-02-24 10:28:21 -08005710 break;
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005711 }
5712 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00005713 ApplicationPackageManager.handlePackageBroadcast(cmd, packages, hasPkgInfo);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -07005714 }
Tim Murraye1e6c662015-04-07 13:24:14 -07005715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005716 final void handleLowMemory() {
Dianne Hackborn73c14162012-09-19 15:45:06 -07005717 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(true, null);
Bob Leee5408332009-09-04 18:31:17 -07005718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005719 final int N = callbacks.size();
5720 for (int i=0; i<N; i++) {
5721 callbacks.get(i).onLowMemory();
5722 }
5723
Chris Tatece229052009-03-25 16:44:52 -07005724 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
5725 if (Process.myUid() != Process.SYSTEM_UID) {
5726 int sqliteReleased = SQLiteDatabase.releaseMemory();
5727 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
5728 }
Bob Leee5408332009-09-04 18:31:17 -07005729
Mike Reedcaf0df12009-04-27 14:32:05 -04005730 // Ask graphics to free up as much as possible (font/image caches)
5731 Canvas.freeCaches();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005732
Fabrice Di Meglio30ca5cd2012-05-07 17:45:44 -07005733 // Ask text layout engine to free also as much as possible
5734 Canvas.freeTextLayoutCaches();
5735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 BinderInternal.forceGc("mem");
5737 }
5738
Jorim Jaggib29e3182018-04-30 18:51:56 +02005739 private void handleTrimMemory(int level) {
5740 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "trimMemory");
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07005741 if (DEBUG_MEMORY_TRIM) Slog.v(TAG, "Trimming memory to level: " + level);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005742
Dianne Hackborn73c14162012-09-19 15:45:06 -07005743 ArrayList<ComponentCallbacks2> callbacks = collectComponentCallbacks(true, null);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005744
5745 final int N = callbacks.size();
Romain Guya998dff2012-03-23 18:58:36 -07005746 for (int i = 0; i < N; i++) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07005747 callbacks.get(i).onTrimMemory(level);
5748 }
Romain Guy19f86e82012-04-23 15:19:07 -07005749
John Reckf47a5942014-06-30 16:20:04 -07005750 WindowManagerGlobal.getInstance().trimMemory(level);
Jorim Jaggib29e3182018-04-30 18:51:56 +02005751 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005752 }
5753
Jesse Hall317fa5a2017-05-23 15:46:55 -07005754 private void setupGraphicsSupport(Context context) {
Andreas Gampe4c8e5422016-05-18 11:58:47 -07005755 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setupGraphicsSupport");
Romain Guya9582652011-11-10 14:20:10 -08005756
Jesse Hall317fa5a2017-05-23 15:46:55 -07005757 // The system package doesn't have real data directories, so don't set up cache paths.
5758 if (!"android".equals(context.getPackageName())) {
5759 // This cache location probably points at credential-encrypted
5760 // storage which may not be accessible yet; assign it anyway instead
5761 // of pointing at device-encrypted storage.
5762 final File cacheDir = context.getCacheDir();
5763 if (cacheDir != null) {
5764 // Provide a usable directory for temporary files
5765 System.setProperty("java.io.tmpdir", cacheDir.getAbsolutePath());
5766 } else {
5767 Log.v(TAG, "Unable to initialize \"java.io.tmpdir\" property "
5768 + "due to missing cache directory");
Romain Guya9582652011-11-10 14:20:10 -08005769 }
Jesse Hall317fa5a2017-05-23 15:46:55 -07005770
5771 // Setup a location to store generated/compiled graphics code.
5772 final Context deviceContext = context.createDeviceProtectedStorageContext();
5773 final File codeCacheDir = deviceContext.getCodeCacheDir();
5774 if (codeCacheDir != null) {
5775 try {
5776 int uid = Process.myUid();
5777 String[] packages = getPackageManager().getPackagesForUid(uid);
5778 if (packages != null) {
John Reck8785ceb2018-10-29 16:45:58 -07005779 HardwareRenderer.setupDiskCache(codeCacheDir);
Romain Guycecbe072017-07-18 15:42:06 -07005780 RenderScriptCacheDir.setupDiskCache(codeCacheDir);
Jesse Hall317fa5a2017-05-23 15:46:55 -07005781 }
5782 } catch (RemoteException e) {
5783 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
5784 throw e.rethrowFromSystemServer();
5785 }
5786 } else {
5787 Log.w(TAG, "Unable to use shader/script cache: missing code-cache directory");
5788 }
Romain Guya9582652011-11-10 14:20:10 -08005789 }
Jesse Hall317fa5a2017-05-23 15:46:55 -07005790
Cody Northropdeb43282018-10-04 16:04:05 -06005791 GraphicsEnvironment.getInstance().setup(context, mCoreSettings);
Jesse Hall317fa5a2017-05-23 15:46:55 -07005792 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Dianne Hackborndde331c2012-08-03 14:01:57 -07005793 }
5794
5795 private void updateDefaultDensity() {
Alan Viverette2ac46f12016-02-04 16:58:14 -05005796 final int densityDpi = mCurDefaultDisplayDpi;
5797 if (!mDensityCompatMode
5798 && densityDpi != Configuration.DENSITY_DPI_UNDEFINED
5799 && densityDpi != DisplayMetrics.DENSITY_DEVICE) {
5800 DisplayMetrics.DENSITY_DEVICE = densityDpi;
5801 Bitmap.setDefaultDensity(densityDpi);
Dianne Hackborndde331c2012-08-03 14:01:57 -07005802 }
5803 }
5804
Todd Kennedye713efc2016-05-10 13:45:40 -07005805 /**
5806 * Returns the correct library directory for the current ABI.
5807 * <p>
5808 * If we're dealing with a multi-arch application that has both 32 and 64 bit shared
5809 * libraries, we might need to choose the secondary depending on what the current
5810 * runtime's instruction set is.
5811 */
5812 private String getInstrumentationLibrary(ApplicationInfo appInfo, InstrumentationInfo insInfo) {
Patrick Baumanneb595802018-04-17 09:49:55 -07005813 if (appInfo.primaryCpuAbi != null && appInfo.secondaryCpuAbi != null
5814 && appInfo.secondaryCpuAbi.equals(insInfo.secondaryCpuAbi)) {
Todd Kennedye713efc2016-05-10 13:45:40 -07005815 // Get the instruction set supported by the secondary ABI. In the presence
5816 // of a native bridge this might be different than the one secondary ABI used.
5817 String secondaryIsa =
5818 VMRuntime.getInstructionSet(appInfo.secondaryCpuAbi);
5819 final String secondaryDexCodeIsa =
5820 SystemProperties.get("ro.dalvik.vm.isa." + secondaryIsa);
5821 secondaryIsa = secondaryDexCodeIsa.isEmpty() ? secondaryIsa : secondaryDexCodeIsa;
5822
5823 final String runtimeIsa = VMRuntime.getRuntime().vmInstructionSet();
5824 if (runtimeIsa.equals(secondaryIsa)) {
5825 return insInfo.secondaryNativeLibraryDir;
5826 }
5827 }
5828 return insInfo.nativeLibraryDir;
5829 }
5830
Adam Lesinskib61e4052016-05-19 18:23:05 -07005831 /**
5832 * The LocaleList set for the app's resources may have been shuffled so that the preferred
5833 * Locale is at position 0. We must find the index of this preferred Locale in the
5834 * original LocaleList.
5835 */
5836 private void updateLocaleListFromAppContext(Context context, LocaleList newLocaleList) {
5837 final Locale bestLocale = context.getResources().getConfiguration().getLocales().get(0);
5838 final int newLocaleListSize = newLocaleList.size();
5839 for (int i = 0; i < newLocaleListSize; i++) {
5840 if (bestLocale.equals(newLocaleList.get(i))) {
5841 LocaleList.setDefault(newLocaleList, i);
5842 return;
5843 }
5844 }
Adam Lesinski27d30162016-05-25 16:45:14 -07005845
5846 // The app may have overridden the LocaleList with its own Locale
5847 // (not present in the available list). Push the chosen Locale
5848 // to the front of the list.
5849 LocaleList.setDefault(new LocaleList(bestLocale, newLocaleList));
Adam Lesinskib61e4052016-05-19 18:23:05 -07005850 }
5851
Mathew Inwood61e8ae62018-08-14 14:17:44 +01005852 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07005853 private void handleBindApplication(AppBindData data) {
Calin Juravle8f5770d2016-04-12 14:12:04 +01005854 // Register the UI Thread as a sensitive thread to the runtime.
5855 VMRuntime.registerSensitiveThread();
Man Caocfa78b22015-06-11 20:14:34 -07005856 if (data.trackAllocation) {
5857 DdmVmInternal.enableRecentAllocations(true);
5858 }
5859
Dianne Hackbornd98885c2016-03-01 17:13:03 -08005860 // Note when this process has started.
5861 Process.setStartTimes(SystemClock.elapsedRealtime(), SystemClock.uptimeMillis());
5862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005863 mBoundApplication = data;
5864 mConfiguration = new Configuration(data.config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07005865 mCompatConfiguration = new Configuration(data.config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005866
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005867 mProfiler = new Profiler();
Andreas Gampeab8a63b2018-01-05 13:55:15 -08005868 String agent = null;
Jeff Hao1b012d32014-08-20 10:35:34 -07005869 if (data.initProfilerInfo != null) {
5870 mProfiler.profileFile = data.initProfilerInfo.profileFile;
5871 mProfiler.profileFd = data.initProfilerInfo.profileFd;
5872 mProfiler.samplingInterval = data.initProfilerInfo.samplingInterval;
5873 mProfiler.autoStopProfiler = data.initProfilerInfo.autoStopProfiler;
Shukang Zhou6ffd4f92017-01-25 16:07:57 -08005874 mProfiler.streamingOutput = data.initProfilerInfo.streamingOutput;
Andreas Gampeab8a63b2018-01-05 13:55:15 -08005875 if (data.initProfilerInfo.attachAgentDuringBind) {
5876 agent = data.initProfilerInfo.agent;
5877 }
Jeff Hao1b012d32014-08-20 10:35:34 -07005878 }
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005880 // send up app name; do this *before* waiting for debugger
Christopher Tate8ee038d2009-11-06 11:30:20 -08005881 Process.setArgV0(data.processName);
Siva Velusamyd693dfa2012-09-10 14:36:58 -07005882 android.ddm.DdmHandleAppName.setAppName(data.processName,
5883 UserHandle.myUserId());
Mathew Inwood37b6ca82018-05-02 10:42:23 +01005884 VMRuntime.setProcessPackageName(data.appInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005885
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07005886 if (mProfiler.profileFd != null) {
5887 mProfiler.startProfiling();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07005888 }
5889
Joe Onoratod630f102011-03-17 18:42:26 -07005890 // If the app is Honeycomb MR1 or earlier, switch its AsyncTask
5891 // implementation to use the pool executor. Normally, we use the
5892 // serialized executor as the default. This has to happen in the
5893 // main thread so the main looper is set right.
Dianne Hackborn81e92762011-10-09 16:00:21 -07005894 if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
Joe Onoratod630f102011-03-17 18:42:26 -07005895 AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
5896 }
5897
Dianne Hackborn7895bc22014-09-05 15:09:03 -07005898 Message.updateCheckRecycle(data.appInfo.targetSdkVersion);
5899
Leon Scroggins III8290eab2018-03-19 10:51:44 -04005900 // Prior to P, internal calls to decode Bitmaps used BitmapFactory,
5901 // which may scale up to account for density. In P, we switched to
5902 // ImageDecoder, which skips the upscale to save memory. ImageDecoder
5903 // needs to still scale up in older apps, in case they rely on the
5904 // size of the Bitmap without considering its density.
5905 ImageDecoder.sApiLevel = data.appInfo.targetSdkVersion;
5906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005907 /*
5908 * Before spawning a new process, reset the time zone to be the system time zone.
5909 * This needs to be done because the system time zone could have changed after the
5910 * the spawning of this process. Without doing this this process would have the incorrect
5911 * system time zone.
5912 */
5913 TimeZone.setDefault(null);
5914
Adam Lesinskib61e4052016-05-19 18:23:05 -07005915 /*
5916 * Set the LocaleList. This may change once we create the App Context.
5917 */
5918 LocaleList.setDefault(data.config.getLocales());
5919
5920 synchronized (mResourcesManager) {
5921 /*
5922 * Update the system configuration since its preloaded and might not
5923 * reflect configuration changes. The configuration object passed
5924 * in AppBindData can be safely assumed to be up to date
5925 */
5926 mResourcesManager.applyConfigurationToResourcesLocked(data.config, data.compatInfo);
5927 mCurDefaultDisplayDpi = data.config.densityDpi;
5928
5929 // This calls mResourcesManager so keep it within the synchronized block.
5930 applyCompatConfiguration(mCurDefaultDisplayDpi);
5931 }
5932
Todd Kennedy233a0b12018-01-29 20:30:24 +00005933 data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005934
Andreas Gampeab8a63b2018-01-05 13:55:15 -08005935 if (agent != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005936 handleAttachAgent(agent, data.info);
Andreas Gampeab8a63b2018-01-05 13:55:15 -08005937 }
5938
Dianne Hackborndde331c2012-08-03 14:01:57 -07005939 /**
5940 * Switch this process to density compatibility mode if needed.
5941 */
5942 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
5943 == 0) {
5944 mDensityCompatMode = true;
5945 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
5946 }
5947 updateDefaultDensity();
5948
Neil Fullerc66ec402016-11-14 16:06:42 +00005949 final String use24HourSetting = mCoreSettings.getString(Settings.System.TIME_12_24);
5950 Boolean is24Hr = null;
5951 if (use24HourSetting != null) {
5952 is24Hr = "24".equals(use24HourSetting) ? Boolean.TRUE : Boolean.FALSE;
5953 }
5954 // null : use locale default for 12/24 hour formatting,
5955 // false : use 12 hour format,
5956 // true : use 24 hour format.
Narayan Kamathccb2a0862013-12-19 14:49:36 +00005957 DateFormat.set24HourTimePref(is24Hr);
5958
Aurimas Liutikas8f004c82019-01-17 17:20:10 -08005959 updateDebugViewAttributeState();
Jon Miranda836c0a82014-08-11 12:32:26 -07005960
Jeff Sharkey89182982017-11-01 19:02:56 -06005961 StrictMode.initThreadDefaults(data.appInfo);
5962 StrictMode.initVmDefaults(data.appInfo);
Jeff Sharkey344744b2016-01-28 19:03:30 -07005963
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005964 if (data.debugMode != ApplicationThreadConstants.DEBUG_OFF) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005965 // XXX should have option to change the port.
5966 Debug.changeDebugPort(8100);
Sudheer Shankacc6418f2016-10-13 12:03:44 -07005967 if (data.debugMode == ApplicationThreadConstants.DEBUG_WAIT) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005968 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005969 + " is waiting for the debugger on port 8100...");
5970
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005971 IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 try {
5973 mgr.showWaitingForDebugger(mAppThread, true);
5974 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005975 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 }
5977
5978 Debug.waitForDebugger();
5979
5980 try {
5981 mgr.showWaitingForDebugger(mAppThread, false);
5982 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07005983 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005984 }
5985
5986 } else {
Todd Kennedy233a0b12018-01-29 20:30:24 +00005987 Slog.w(TAG, "Application " + data.info.getPackageName()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005988 + " can be debugged on port 8100...");
5989 }
5990 }
5991
Chris Craikce030282018-10-16 14:33:11 -07005992 // Allow binder tracing, and application-generated systrace messages if we're profileable.
5993 boolean isAppProfileable = data.appInfo.isProfileableByShell();
5994 Trace.setAppTracingAllowed(isAppProfileable);
5995 if (isAppProfileable && data.enableBinderTracking) {
Rahul Chaturvedi52613f92015-06-17 23:54:08 -04005996 Binder.enableTracing();
5997 }
Jamie Gennisf9c7d6b2013-03-25 14:18:25 -07005998
Ryan Savitskicfdc1512018-12-14 16:20:52 +00005999 // Initialize heap profiling.
6000 if (isAppProfileable || Build.IS_DEBUGGABLE) {
6001 nInitZygoteChildHeapProfiling();
6002 }
6003
Chris Craikce030282018-10-16 14:33:11 -07006004 // Allow renderer debugging features if we're debuggable.
6005 boolean isAppDebuggable = (data.appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
John Reck8785ceb2018-10-29 16:45:58 -07006006 HardwareRenderer.setDebuggingEnabled(isAppDebuggable || Build.IS_DEBUGGABLE);
6007 HardwareRenderer.setPackageName(data.appInfo.packageName);
Chris Craikce030282018-10-16 14:33:11 -07006008
Robert Greenwalt434203a2010-10-11 16:00:27 -07006009 /**
6010 * Initialize the default http proxy in this process for the reasons we set the time zone.
6011 */
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006012 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Setup proxies");
Alan Viverettebe64eae2015-09-03 14:56:04 -04006013 final IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08006014 if (b != null) {
6015 // In pre-boot mode (doing initial launch to collect password), not
6016 // all system is up. This includes the connectivity service, so don't
6017 // crash if we can't get it.
Alan Viverettebe64eae2015-09-03 14:56:04 -04006018 final IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08006019 try {
Irina Dumitrescu18622d32018-12-05 16:19:47 +00006020 Proxy.setHttpProxySystemProperty(service.getProxyForNetwork(null));
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006021 } catch (RemoteException e) {
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006022 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006023 throw e.rethrowFromSystemServer();
6024 }
Dianne Hackbornd4d32c52011-11-08 17:33:59 -08006025 }
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006026 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Robert Greenwalt434203a2010-10-11 16:00:27 -07006027
Alan Viverette2107d692015-09-03 14:55:27 -04006028 // Instrumentation info affects the class loader, so load it before
6029 // setting up the app context.
6030 final InstrumentationInfo ii;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 if (data.instrumentationName != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006032 try {
Alan Viverette2107d692015-09-03 14:55:27 -04006033 ii = new ApplicationPackageManager(null, getPackageManager())
6034 .getInstrumentationInfo(data.instrumentationName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006035 } catch (PackageManager.NameNotFoundException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006036 throw new RuntimeException(
Alan Viverette2107d692015-09-03 14:55:27 -04006037 "Unable to find instrumentation info for: " + data.instrumentationName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006038 }
6039
Patrick Baumanneb595802018-04-17 09:49:55 -07006040 // Warn of potential ABI mismatches.
6041 if (!Objects.equals(data.appInfo.primaryCpuAbi, ii.primaryCpuAbi)
6042 || !Objects.equals(data.appInfo.secondaryCpuAbi, ii.secondaryCpuAbi)) {
6043 Slog.w(TAG, "Package uses different ABI(s) than its instrumentation: "
6044 + "package[" + data.appInfo.packageName + "]: "
6045 + data.appInfo.primaryCpuAbi + ", " + data.appInfo.secondaryCpuAbi
6046 + " instrumentation[" + ii.packageName + "]: "
6047 + ii.primaryCpuAbi + ", " + ii.secondaryCpuAbi);
6048 }
6049
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07006050 mInstrumentationPackageName = ii.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006051 mInstrumentationAppDir = ii.sourceDir;
Jeff Sharkey8a4c9722014-06-16 13:48:42 -07006052 mInstrumentationSplitAppDirs = ii.splitSourceDirs;
Todd Kennedye713efc2016-05-10 13:45:40 -07006053 mInstrumentationLibDir = getInstrumentationLibrary(data.appInfo, ii);
Todd Kennedy233a0b12018-01-29 20:30:24 +00006054 mInstrumentedAppDir = data.info.getAppDir();
6055 mInstrumentedSplitAppDirs = data.info.getSplitAppDirs();
6056 mInstrumentedLibDir = data.info.getLibDir();
Alan Viverette2107d692015-09-03 14:55:27 -04006057 } else {
6058 ii = null;
6059 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006060
Todd Kennedy233a0b12018-01-29 20:30:24 +00006061 final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
Adam Lesinskib61e4052016-05-19 18:23:05 -07006062 updateLocaleListFromAppContext(appContext,
6063 mResourcesManager.getConfiguration().getLocales());
Seigo Nonakac14dd782016-03-30 23:09:16 +09006064
Jesse Hall317fa5a2017-05-23 15:46:55 -07006065 if (!Process.isIsolated()) {
Jeff Sharkey89182982017-11-01 19:02:56 -06006066 final int oldMask = StrictMode.allowThreadDiskWritesMask();
6067 try {
6068 setupGraphicsSupport(appContext);
6069 } finally {
6070 StrictMode.setThreadPolicyMask(oldMask);
6071 }
John Reck56428472018-03-16 17:27:17 -07006072 } else {
John Reck8785ceb2018-10-29 16:45:58 -07006073 HardwareRenderer.setIsolatedProcess(true);
Michael Lentine2ba303f2016-02-01 20:44:34 -06006074 }
Michael Lentine03d8f7682016-01-31 15:37:11 -06006075
Chad Brubaker78d47122015-11-17 22:26:58 -08006076 // Install the Network Security Config Provider. This must happen before the application
6077 // code is loaded to prevent issues with instances of TLS objects being created before
6078 // the provider is installed.
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006079 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "NetworkSecurityConfigProvider.install");
Chad Brubaker276ee962016-06-08 12:57:46 -07006080 NetworkSecurityConfigProvider.install(appContext);
Andreas Gampe4c8e5422016-05-18 11:58:47 -07006081 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Chad Brubaker78d47122015-11-17 22:26:58 -08006082
Alan Viverette2107d692015-09-03 14:55:27 -04006083 // Continue loading instrumentation.
6084 if (ii != null) {
Dianne Hackbornf4ef6eb2017-12-07 13:57:21 -08006085 ApplicationInfo instrApp;
6086 try {
6087 instrApp = getPackageManager().getApplicationInfo(ii.packageName, 0,
6088 UserHandle.myUserId());
6089 } catch (RemoteException e) {
6090 instrApp = null;
6091 }
6092 if (instrApp == null) {
6093 instrApp = new ApplicationInfo();
6094 }
Jeff Sharkey15447792015-11-05 16:18:51 -08006095 ii.copyTo(instrApp);
Fyodor Kupolovaf38b8e2015-12-02 16:16:07 -08006096 instrApp.initForUser(UserHandle.myUserId());
Todd Kennedy233a0b12018-01-29 20:30:24 +00006097 final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
Dianne Hackbornfee756f2014-07-16 17:31:10 -07006098 appContext.getClassLoader(), false, true, false);
Makoto Onuki4becc352019-01-30 13:30:41 -08006099
6100 // The test context's op package name == the target app's op package name, because
6101 // the app ops manager checks the op package name against the real calling UID,
6102 // which is what the target package name is associated with.
6103 final ContextImpl instrContext = ContextImpl.createAppContext(this, pi,
6104 appContext.getOpPackageName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105
6106 try {
Alan Viverettebe64eae2015-09-03 14:56:04 -04006107 final ClassLoader cl = instrContext.getClassLoader();
Dan Sandler07fe63e2017-08-15 16:41:11 -04006108 mInstrumentation = (Instrumentation)
6109 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006110 } catch (Exception e) {
6111 throw new RuntimeException(
6112 "Unable to instantiate instrumentation "
6113 + data.instrumentationName + ": " + e.toString(), e);
6114 }
6115
Alan Viverettebe64eae2015-09-03 14:56:04 -04006116 final ComponentName component = new ComponentName(ii.packageName, ii.name);
6117 mInstrumentation.init(this, instrContext, appContext, component,
6118 data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006119
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07006120 if (mProfiler.profileFile != null && !ii.handleProfiling
6121 && mProfiler.profileFd == null) {
6122 mProfiler.handlingProfiling = true;
Alan Viverettebe64eae2015-09-03 14:56:04 -04006123 final File file = new File(mProfiler.profileFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006124 file.getParentFile().mkdirs();
6125 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
6126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006127 } else {
6128 mInstrumentation = new Instrumentation();
Jason Monka80bfb52017-11-16 17:15:37 -05006129 mInstrumentation.basicInit(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006130 }
6131
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08006132 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
Dianne Hackbornde398512011-01-18 18:45:21 -08006133 dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
Mathieu Chartier24cee072015-01-08 14:42:20 -08006134 } else {
6135 // Small heap, clamp to the current growth limit and let the heap release
6136 // pages after the growth limit to the non growth limit capacity. b/18387825
6137 dalvik.system.VMRuntime.getRuntime().clampGrowthLimit();
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08006138 }
6139
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006140 // Allow disk access during application and provider setup. This could
Jeff Sharkey7c501672012-02-28 12:08:37 -08006141 // block processing ordered broadcasts, but later processing would
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006142 // probably end up doing the same disk access.
Kurt Nelson5e154362017-06-29 17:20:56 -07006143 Application app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08006144 final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
Kurt Nelson571c3f62017-07-10 11:09:04 -07006145 final StrictMode.ThreadPolicy writesAllowedPolicy = StrictMode.getThreadPolicy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006146 try {
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006147 // If the app is being launched for full backup or restore, bring it up in
6148 // a restricted environment with the base application class.
Todd Kennedy233a0b12018-01-29 20:30:24 +00006149 app = data.info.makeApplication(data.restrictedBackupMode, null);
Svetoslav Ganov24c90452017-12-27 15:17:14 -08006150
6151 // Propagate autofill compat state
Felipe Lemea4f39cd2019-02-19 15:08:59 -08006152 app.setAutofillOptions(data.autofillOptions);
Svetoslav Ganov24c90452017-12-27 15:17:14 -08006153
Felipe Leme326f15a2019-02-19 09:42:24 -08006154 // Propagate Content Capture options
6155 app.setContentCaptureOptions(data.contentCaptureOptions);
6156
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006157 mInitialApplication = app;
Jeff Sharkey7c501672012-02-28 12:08:37 -08006158
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006159 // don't bring up providers in restricted mode; they may depend on the
6160 // app's custom Application class
6161 if (!data.restrictedBackupMode) {
Jeff Sharkey3e195892016-03-05 19:48:59 -07006162 if (!ArrayUtils.isEmpty(data.providers)) {
6163 installContentProviders(app, data.providers);
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006164 }
6165 }
6166
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006167 // Do this after providers, since instrumentation tests generally start their
6168 // test thread at this point, and we don't want that racing.
6169 try {
6170 mInstrumentation.onCreate(data.instrumentationArgs);
6171 }
6172 catch (Exception e) {
6173 throw new RuntimeException(
6174 "Exception thrown in onCreate() of "
6175 + data.instrumentationName + ": " + e.toString(), e);
6176 }
Kurt Nelson571c3f62017-07-10 11:09:04 -07006177 try {
6178 mInstrumentation.callApplicationOnCreate(app);
6179 } catch (Exception e) {
6180 if (!mInstrumentation.onException(app, e)) {
6181 throw new RuntimeException(
6182 "Unable to create application " + app.getClass().getName()
6183 + ": " + e.toString(), e);
6184 }
6185 }
Jeff Sharkey6bff62c2012-02-29 12:26:36 -08006186 } finally {
Kurt Nelson571c3f62017-07-10 11:09:04 -07006187 // If the app targets < O-MR1, or doesn't change the thread policy
6188 // during startup, clobber the policy to maintain behavior of b/36951662
Jeff Sharkeyaa1a9112018-04-10 15:18:12 -06006189 if (data.appInfo.targetSdkVersion < Build.VERSION_CODES.O_MR1
Kurt Nelson571c3f62017-07-10 11:09:04 -07006190 || StrictMode.getThreadPolicy().equals(writesAllowedPolicy)) {
6191 StrictMode.setThreadPolicy(savedPolicy);
Kurt Nelson5e154362017-06-29 17:20:56 -07006192 }
6193 }
6194
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00006195 // Preload fonts resources
Seigo Nonaka54084b62017-04-24 14:46:23 -07006196 FontsContract.setApplicationContextForResources(appContext);
Torne (Richard Coles)85ecae52018-01-30 18:13:00 -05006197 if (!Process.isIsolated()) {
6198 try {
6199 final ApplicationInfo info =
6200 getPackageManager().getApplicationInfo(
6201 data.appInfo.packageName,
6202 PackageManager.GET_META_DATA /*flags*/,
6203 UserHandle.myUserId());
6204 if (info.metaData != null) {
6205 final int preloadedFontsResource = info.metaData.getInt(
6206 ApplicationInfo.METADATA_PRELOADED_FONTS, 0);
6207 if (preloadedFontsResource != 0) {
6208 data.info.getResources().preloadFonts(preloadedFontsResource);
6209 }
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00006210 }
Torne (Richard Coles)85ecae52018-01-30 18:13:00 -05006211 } catch (RemoteException e) {
6212 throw e.rethrowFromSystemServer();
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00006213 }
Clara Bayarri4b5a4d22017-01-27 20:15:45 +00006214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215 }
6216
6217 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006218 IActivityManager am = ActivityManager.getService();
Jeff Sharkey3ad9d002011-09-15 15:51:54 -07006219 if (mProfiler.profileFile != null && mProfiler.handlingProfiling
6220 && mProfiler.profileFd == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006221 Debug.stopMethodTracing();
6222 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006223 //Slog.i(TAG, "am: " + ActivityManager.getService()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006224 // + ", app thr: " + mAppThread);
6225 try {
6226 am.finishInstrumentation(mAppThread, resultCode, results);
6227 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006228 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006229 }
6230 }
6231
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006232 @UnsupportedAppUsage
Romain Guy65b345f2011-07-27 18:51:50 -07006233 private void installContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006234 Context context, List<ProviderInfo> providers) {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006235 final ArrayList<ContentProviderHolder> results = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006236
Romain Guya998dff2012-03-23 18:58:36 -07006237 for (ProviderInfo cpi : providers) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08006238 if (DEBUG_PROVIDER) {
6239 StringBuilder buf = new StringBuilder(128);
6240 buf.append("Pub ");
6241 buf.append(cpi.authority);
6242 buf.append(": ");
6243 buf.append(cpi.name);
6244 Log.i(TAG, buf.toString());
6245 }
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006246 ContentProviderHolder cph = installProvider(context, null, cpi,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006247 false /*noisy*/, true /*noReleaseNeeded*/, true /*stable*/);
6248 if (cph != null) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006249 cph.noReleaseNeeded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250 results.add(cph);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 }
6252 }
6253
6254 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006255 ActivityManager.getService().publishContentProviders(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006256 getApplicationThread(), results);
6257 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006258 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 }
6260 }
6261
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006262 @UnsupportedAppUsage
Jeff Sharkey6d515712012-09-20 16:06:08 -07006263 public final IContentProvider acquireProvider(
6264 Context c, String auth, int userId, boolean stable) {
Wale Ogunwale1d646122015-04-24 14:45:14 -07006265 final IContentProvider provider = acquireExistingProvider(c, auth, userId, stable);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006266 if (provider != null) {
6267 return provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268 }
6269
Wale Ogunwale1d646122015-04-24 14:45:14 -07006270 // There is a possible race here. Another thread may try to acquire
6271 // the same provider at the same time. When this happens, we want to ensure
6272 // that the first one wins.
6273 // Note that we cannot hold the lock while acquiring and installing the
6274 // provider since it might take a long time to run and it could also potentially
6275 // be re-entrant in the case where the provider is in the same process.
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006276 ContentProviderHolder holder = null;
Wale Ogunwale1d646122015-04-24 14:45:14 -07006277 try {
Makoto Onukib6c79ea2018-05-31 11:03:56 -07006278 synchronized (getGetProviderLock(auth, userId)) {
6279 holder = ActivityManager.getService().getContentProvider(
Dianne Hackborn24bbe582018-12-17 11:58:31 -08006280 getApplicationThread(), c.getOpPackageName(), auth, userId, stable);
Makoto Onukib6c79ea2018-05-31 11:03:56 -07006281 }
Wale Ogunwale1d646122015-04-24 14:45:14 -07006282 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006283 throw ex.rethrowFromSystemServer();
Wale Ogunwale67fe0a42015-04-24 14:44:54 -07006284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006285 if (holder == null) {
Jeff Sharkey6d515712012-09-20 16:06:08 -07006286 Slog.e(TAG, "Failed to find provider info for " + auth);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006287 return null;
6288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006289
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006290 // Install provider will increment the reference count for us, and break
6291 // any ties in the race.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006292 holder = installProvider(c, holder, holder.info,
6293 true /*noisy*/, holder.noReleaseNeeded, stable);
6294 return holder.provider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006295 }
6296
Makoto Onukib6c79ea2018-05-31 11:03:56 -07006297 private Object getGetProviderLock(String auth, int userId) {
6298 final ProviderKey key = new ProviderKey(auth, userId);
6299 synchronized (mGetProviderLocks) {
6300 Object lock = mGetProviderLocks.get(key);
6301 if (lock == null) {
6302 lock = key;
6303 mGetProviderLocks.put(key, lock);
6304 }
6305 return lock;
6306 }
6307 }
6308
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006309 private final void incProviderRefLocked(ProviderRefCount prc, boolean stable) {
6310 if (stable) {
6311 prc.stableCount += 1;
6312 if (prc.stableCount == 1) {
6313 // We are acquiring a new stable reference on the provider.
6314 int unstableDelta;
6315 if (prc.removePending) {
6316 // We have a pending remove operation, which is holding the
6317 // last unstable reference. At this point we are converting
6318 // that unstable reference to our new stable reference.
6319 unstableDelta = -1;
6320 // Cancel the removal of the provider.
6321 if (DEBUG_PROVIDER) {
6322 Slog.v(TAG, "incProviderRef: stable "
6323 + "snatched provider from the jaws of death");
6324 }
6325 prc.removePending = false;
Guobin Zhang9e3e52662013-03-21 13:57:11 +08006326 // There is a race! It fails to remove the message, which
6327 // will be handled in completeRemoveProvider().
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006328 mH.removeMessages(H.REMOVE_PROVIDER, prc);
6329 } else {
6330 unstableDelta = 0;
6331 }
6332 try {
6333 if (DEBUG_PROVIDER) {
6334 Slog.v(TAG, "incProviderRef Now stable - "
6335 + prc.holder.info.name + ": unstableDelta="
6336 + unstableDelta);
6337 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006338 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006339 prc.holder.connection, 1, unstableDelta);
6340 } catch (RemoteException e) {
6341 //do nothing content provider object is dead any way
6342 }
6343 }
6344 } else {
6345 prc.unstableCount += 1;
6346 if (prc.unstableCount == 1) {
6347 // We are acquiring a new unstable reference on the provider.
6348 if (prc.removePending) {
6349 // Oh look, we actually have a remove pending for the
6350 // provider, which is still holding the last unstable
6351 // reference. We just need to cancel that to take new
6352 // ownership of the reference.
6353 if (DEBUG_PROVIDER) {
6354 Slog.v(TAG, "incProviderRef: unstable "
6355 + "snatched provider from the jaws of death");
6356 }
6357 prc.removePending = false;
6358 mH.removeMessages(H.REMOVE_PROVIDER, prc);
6359 } else {
6360 // First unstable ref, increment our count in the
6361 // activity manager.
6362 try {
6363 if (DEBUG_PROVIDER) {
6364 Slog.v(TAG, "incProviderRef: Now unstable - "
6365 + prc.holder.info.name);
6366 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006367 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006368 prc.holder.connection, 0, 1);
6369 } catch (RemoteException e) {
6370 //do nothing content provider object is dead any way
6371 }
6372 }
6373 }
6374 }
6375 }
6376
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006377 @UnsupportedAppUsage
Jeff Sharkey6d515712012-09-20 16:06:08 -07006378 public final IContentProvider acquireExistingProvider(
6379 Context c, String auth, int userId, boolean stable) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006380 synchronized (mProviderMap) {
Wale Ogunwale1d646122015-04-24 14:45:14 -07006381 final ProviderKey key = new ProviderKey(auth, userId);
Jeff Sharkey6d515712012-09-20 16:06:08 -07006382 final ProviderClientRecord pr = mProviderMap.get(key);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006383 if (pr == null) {
6384 return null;
6385 }
6386
6387 IContentProvider provider = pr.mProvider;
6388 IBinder jBinder = provider.asBinder();
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006389 if (!jBinder.isBinderAlive()) {
6390 // The hosting process of the provider has died; we can't
6391 // use this one.
Wale Ogunwale1d646122015-04-24 14:45:14 -07006392 Log.i(TAG, "Acquiring provider " + auth + " for user " + userId
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006393 + ": existing object's process dead");
6394 handleUnstableProviderDiedLocked(jBinder, true);
6395 return null;
6396 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006397
6398 // Only increment the ref count if we have one. If we don't then the
6399 // provider is not reference counted and never needs to be released.
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006400 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006401 if (prc != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006402 incProviderRefLocked(prc, stable);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006403 }
6404 return provider;
6405 }
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006406 }
6407
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006408 @UnsupportedAppUsage
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006409 public final boolean releaseProvider(IContentProvider provider, boolean stable) {
6410 if (provider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 return false;
6412 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006414 IBinder jBinder = provider.asBinder();
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006415 synchronized (mProviderMap) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006417 if (prc == null) {
6418 // The provider has no ref count, no release is needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006419 return false;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006420 }
6421
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006422 boolean lastRef = false;
6423 if (stable) {
6424 if (prc.stableCount == 0) {
6425 if (DEBUG_PROVIDER) Slog.v(TAG,
6426 "releaseProvider: stable ref count already 0, how?");
6427 return false;
6428 }
6429 prc.stableCount -= 1;
6430 if (prc.stableCount == 0) {
6431 // What we do at this point depends on whether there are
6432 // any unstable refs left: if there are, we just tell the
6433 // activity manager to decrement its stable count; if there
6434 // aren't, we need to enqueue this provider to be removed,
6435 // and convert to holding a single unstable ref while
6436 // doing so.
6437 lastRef = prc.unstableCount == 0;
6438 try {
6439 if (DEBUG_PROVIDER) {
6440 Slog.v(TAG, "releaseProvider: No longer stable w/lastRef="
6441 + lastRef + " - " + prc.holder.info.name);
6442 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006443 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006444 prc.holder.connection, -1, lastRef ? 1 : 0);
6445 } catch (RemoteException e) {
6446 //do nothing content provider object is dead any way
6447 }
6448 }
6449 } else {
6450 if (prc.unstableCount == 0) {
6451 if (DEBUG_PROVIDER) Slog.v(TAG,
6452 "releaseProvider: unstable ref count already 0, how?");
6453 return false;
6454 }
6455 prc.unstableCount -= 1;
6456 if (prc.unstableCount == 0) {
6457 // If this is the last reference, we need to enqueue
6458 // this provider to be removed instead of telling the
6459 // activity manager to remove it at this point.
6460 lastRef = prc.stableCount == 0;
6461 if (!lastRef) {
6462 try {
6463 if (DEBUG_PROVIDER) {
6464 Slog.v(TAG, "releaseProvider: No longer unstable - "
6465 + prc.holder.info.name);
6466 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006467 ActivityManager.getService().refContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006468 prc.holder.connection, 0, -1);
6469 } catch (RemoteException e) {
6470 //do nothing content provider object is dead any way
6471 }
6472 }
6473 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006474 }
6475
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006476 if (lastRef) {
6477 if (!prc.removePending) {
6478 // Schedule the actual remove asynchronously, since we don't know the context
6479 // this will be called in.
6480 // TODO: it would be nice to post a delayed message, so
6481 // if we come back and need the same provider quickly
6482 // we will still have it available.
6483 if (DEBUG_PROVIDER) {
6484 Slog.v(TAG, "releaseProvider: Enqueueing pending removal - "
6485 + prc.holder.info.name);
6486 }
6487 prc.removePending = true;
6488 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, prc);
6489 mH.sendMessage(msg);
6490 } else {
6491 Slog.w(TAG, "Duplicate remove pending of provider " + prc.holder.info.name);
6492 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006493 }
6494 return true;
6495 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006496 }
6497
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006498 final void completeRemoveProvider(ProviderRefCount prc) {
6499 synchronized (mProviderMap) {
6500 if (!prc.removePending) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006501 // There was a race! Some other client managed to acquire
6502 // the provider before the removal was completed.
6503 // Abort the removal. We will do it later.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006504 if (DEBUG_PROVIDER) Slog.v(TAG, "completeRemoveProvider: lost the race, "
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006505 + "provider still in use");
6506 return;
6507 }
6508
Guobin Zhang9e3e52662013-03-21 13:57:11 +08006509 // More complicated race!! Some client managed to acquire the
6510 // provider and release it before the removal was completed.
6511 // Continue the removal, and abort the next remove message.
6512 prc.removePending = false;
6513
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006514 final IBinder jBinder = prc.holder.provider.asBinder();
6515 ProviderRefCount existingPrc = mProviderRefCountMap.get(jBinder);
6516 if (existingPrc == prc) {
6517 mProviderRefCountMap.remove(jBinder);
6518 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006519
Dianne Hackbornadd005c2013-07-17 18:43:12 -07006520 for (int i=mProviderMap.size()-1; i>=0; i--) {
6521 ProviderClientRecord pr = mProviderMap.valueAt(i);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006522 IBinder myBinder = pr.mProvider.asBinder();
6523 if (myBinder == jBinder) {
Dianne Hackbornadd005c2013-07-17 18:43:12 -07006524 mProviderMap.removeAt(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006525 }
6526 }
6527 }
6528
6529 try {
6530 if (DEBUG_PROVIDER) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006531 Slog.v(TAG, "removeProvider: Invoking ActivityManagerService."
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006532 + "removeContentProvider(" + prc.holder.info.name + ")");
6533 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006534 ActivityManager.getService().removeContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006535 prc.holder.connection, false);
6536 } catch (RemoteException e) {
6537 //do nothing content provider object is dead any way
6538 }
6539 }
6540
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006541 @UnsupportedAppUsage
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006542 final void handleUnstableProviderDied(IBinder provider, boolean fromClient) {
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006543 synchronized (mProviderMap) {
6544 handleUnstableProviderDiedLocked(provider, fromClient);
6545 }
6546 }
6547
6548 final void handleUnstableProviderDiedLocked(IBinder provider, boolean fromClient) {
6549 ProviderRefCount prc = mProviderRefCountMap.get(provider);
6550 if (prc != null) {
6551 if (DEBUG_PROVIDER) Slog.v(TAG, "Cleaning up dead provider "
6552 + provider + " " + prc.holder.info.name);
6553 mProviderRefCountMap.remove(provider);
You Kimbc74de62013-10-01 00:13:26 +09006554 for (int i=mProviderMap.size()-1; i>=0; i--) {
6555 ProviderClientRecord pr = mProviderMap.valueAt(i);
6556 if (pr != null && pr.mProvider.asBinder() == provider) {
6557 Slog.i(TAG, "Removing dead content provider:" + pr.mProvider.toString());
6558 mProviderMap.removeAt(i);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006559 }
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006560 }
You Kimbc74de62013-10-01 00:13:26 +09006561
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006562 if (fromClient) {
6563 // We found out about this due to execution in our client
6564 // code. Tell the activity manager about it now, to ensure
6565 // that the next time we go to do anything with the provider
6566 // it knows it is dead (so we don't race with its death
6567 // notification).
6568 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006569 ActivityManager.getService().unstableProviderDied(
Dianne Hackbornc428aae2012-10-03 16:38:22 -07006570 prc.holder.connection);
6571 } catch (RemoteException e) {
6572 //do nothing content provider object is dead any way
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006573 }
Dianne Hackborn9bfb7072009-09-22 11:37:40 -07006574 }
6575 }
6576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006577
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006578 final void appNotRespondingViaProvider(IBinder provider) {
6579 synchronized (mProviderMap) {
6580 ProviderRefCount prc = mProviderRefCountMap.get(provider);
6581 if (prc != null) {
6582 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006583 ActivityManager.getService()
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006584 .appNotRespondingViaProvider(prc.holder.connection);
6585 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006586 throw e.rethrowFromSystemServer();
Jeff Sharkey7aa76012013-09-30 14:26:27 -07006587 }
6588 }
6589 }
6590 }
6591
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006592 private ProviderClientRecord installProviderAuthoritiesLocked(IContentProvider provider,
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006593 ContentProvider localProvider, ContentProviderHolder holder) {
Andreas Gampe18e99c12015-03-06 15:29:06 -08006594 final String auths[] = holder.info.authority.split(";");
Jeff Sharkey6d515712012-09-20 16:06:08 -07006595 final int userId = UserHandle.getUserId(holder.info.applicationInfo.uid);
6596
Jeff Sharkey0a17db12016-11-04 11:23:46 -06006597 if (provider != null) {
6598 // If this provider is hosted by the core OS and cannot be upgraded,
6599 // then I guess we're okay doing blocking calls to it.
6600 for (String auth : auths) {
6601 switch (auth) {
6602 case ContactsContract.AUTHORITY:
6603 case CallLog.AUTHORITY:
6604 case CallLog.SHADOW_AUTHORITY:
6605 case BlockedNumberContract.AUTHORITY:
6606 case CalendarContract.AUTHORITY:
6607 case Downloads.Impl.AUTHORITY:
Jeff Sharkeycb621622016-11-11 14:04:32 -07006608 case "telephony":
Jeff Sharkey0a17db12016-11-04 11:23:46 -06006609 Binder.allowBlocking(provider.asBinder());
6610 }
6611 }
6612 }
6613
Jeff Sharkey6d515712012-09-20 16:06:08 -07006614 final ProviderClientRecord pcr = new ProviderClientRecord(
6615 auths, provider, localProvider, holder);
6616 for (String auth : auths) {
6617 final ProviderKey key = new ProviderKey(auth, userId);
6618 final ProviderClientRecord existing = mProviderMap.get(key);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006619 if (existing != null) {
6620 Slog.w(TAG, "Content provider " + pcr.mHolder.info.name
Jeff Sharkey6d515712012-09-20 16:06:08 -07006621 + " already published as " + auth);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006622 } else {
Jeff Sharkey6d515712012-09-20 16:06:08 -07006623 mProviderMap.put(key, pcr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006624 }
6625 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006626 return pcr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006627 }
6628
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006629 /**
6630 * Installs the provider.
6631 *
6632 * Providers that are local to the process or that come from the system server
6633 * may be installed permanently which is indicated by setting noReleaseNeeded to true.
6634 * Other remote providers are reference counted. The initial reference count
6635 * for all reference counted providers is one. Providers that are not reference
6636 * counted do not have a reference count (at all).
6637 *
6638 * This method detects when a provider has already been installed. When this happens,
6639 * it increments the reference count of the existing provider (if appropriate)
6640 * and returns the existing provider. This can happen due to concurrent
6641 * attempts to acquire the same provider.
6642 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006643 @UnsupportedAppUsage
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006644 private ContentProviderHolder installProvider(Context context,
6645 ContentProviderHolder holder, ProviderInfo info,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006646 boolean noisy, boolean noReleaseNeeded, boolean stable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006647 ContentProvider localProvider = null;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006648 IContentProvider provider;
Dianne Hackborn5f48fca2012-05-30 11:06:31 -07006649 if (holder == null || holder.provider == null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006650 if (DEBUG_PROVIDER || noisy) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006651 Slog.d(TAG, "Loading provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006652 + info.name);
6653 }
6654 Context c = null;
6655 ApplicationInfo ai = info.applicationInfo;
6656 if (context.getPackageName().equals(ai.packageName)) {
6657 c = context;
6658 } else if (mInitialApplication != null &&
6659 mInitialApplication.getPackageName().equals(ai.packageName)) {
6660 c = mInitialApplication;
6661 } else {
6662 try {
6663 c = context.createPackageContext(ai.packageName,
6664 Context.CONTEXT_INCLUDE_CODE);
6665 } catch (PackageManager.NameNotFoundException e) {
Romain Guy65b345f2011-07-27 18:51:50 -07006666 // Ignore
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 }
6668 }
6669 if (c == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08006670 Slog.w(TAG, "Unable to get context for package " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006671 ai.packageName +
6672 " while loading content provider " +
6673 info.name);
6674 return null;
6675 }
Adam Lesinski4e862812016-11-21 16:02:24 -08006676
6677 if (info.splitName != null) {
6678 try {
6679 c = c.createContextForSplit(info.splitName);
6680 } catch (NameNotFoundException e) {
6681 throw new RuntimeException(e);
6682 }
6683 }
6684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006685 try {
6686 final java.lang.ClassLoader cl = c.getClassLoader();
Todd Kennedy233a0b12018-01-29 20:30:24 +00006687 LoadedApk packageInfo = peekPackageInfo(ai.packageName, true);
6688 if (packageInfo == null) {
Jason Monka80bfb52017-11-16 17:15:37 -05006689 // System startup case.
Todd Kennedy233a0b12018-01-29 20:30:24 +00006690 packageInfo = getSystemContext().mPackageInfo;
Jason Monka80bfb52017-11-16 17:15:37 -05006691 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00006692 localProvider = packageInfo.getAppFactory()
Jason Monka80bfb52017-11-16 17:15:37 -05006693 .instantiateProvider(cl, info.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006694 provider = localProvider.getIContentProvider();
6695 if (provider == null) {
Dianne Hackbornc9421ba2010-03-11 22:23:46 -08006696 Slog.e(TAG, "Failed to instantiate class " +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006697 info.name + " from sourceDir " +
6698 info.applicationInfo.sourceDir);
6699 return null;
6700 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006701 if (DEBUG_PROVIDER) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006702 TAG, "Instantiating local provider " + info.name);
6703 // XXX Need to create the correct context for this provider.
6704 localProvider.attachInfo(c, info);
6705 } catch (java.lang.Exception e) {
6706 if (!mInstrumentation.onException(null, e)) {
6707 throw new RuntimeException(
6708 "Unable to get provider " + info.name
6709 + ": " + e.toString(), e);
6710 }
6711 return null;
6712 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006713 } else {
6714 provider = holder.provider;
6715 if (DEBUG_PROVIDER) Slog.v(TAG, "Installing external provider " + info.authority + ": "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006716 + info.name);
6717 }
6718
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006719 ContentProviderHolder retHolder;
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006720
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006721 synchronized (mProviderMap) {
6722 if (DEBUG_PROVIDER) Slog.v(TAG, "Checking to add " + provider
6723 + " / " + info.name);
6724 IBinder jBinder = provider.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006725 if (localProvider != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006726 ComponentName cname = new ComponentName(info.packageName, info.name);
6727 ProviderClientRecord pr = mLocalProvidersByName.get(cname);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006728 if (pr != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006729 if (DEBUG_PROVIDER) {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006730 Slog.v(TAG, "installProvider: lost the race, "
6731 + "using existing local provider");
6732 }
6733 provider = pr.mProvider;
6734 } else {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07006735 holder = new ContentProviderHolder(info);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006736 holder.provider = provider;
6737 holder.noReleaseNeeded = true;
6738 pr = installProviderAuthoritiesLocked(provider, localProvider, holder);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006739 mLocalProviders.put(jBinder, pr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006740 mLocalProvidersByName.put(cname, pr);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006741 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006742 retHolder = pr.mHolder;
6743 } else {
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006744 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
6745 if (prc != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006746 if (DEBUG_PROVIDER) {
6747 Slog.v(TAG, "installProvider: lost the race, updating ref count");
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006748 }
Wale Ogunwale1d646122015-04-24 14:45:14 -07006749 // We need to transfer our new reference to the existing
6750 // ref count, releasing the old one... but only if
6751 // release is needed (that is, it is not running in the
6752 // system process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006753 if (!noReleaseNeeded) {
6754 incProviderRefLocked(prc, stable);
Wale Ogunwale1d646122015-04-24 14:45:14 -07006755 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006756 ActivityManager.getService().removeContentProvider(
Wale Ogunwale1d646122015-04-24 14:45:14 -07006757 holder.connection, stable);
6758 } catch (RemoteException e) {
6759 //do nothing content provider object is dead any way
6760 }
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006761 }
6762 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006763 ProviderClientRecord client = installProviderAuthoritiesLocked(
6764 provider, localProvider, holder);
6765 if (noReleaseNeeded) {
6766 prc = new ProviderRefCount(holder, client, 1000, 1000);
6767 } else {
6768 prc = stable
6769 ? new ProviderRefCount(holder, client, 1, 0)
6770 : new ProviderRefCount(holder, client, 0, 1);
6771 }
6772 mProviderRefCountMap.put(jBinder, prc);
Jeff Brownddaa9ac2011-11-11 20:16:14 -08006773 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006774 retHolder = prc.holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006775 }
6776 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006777 return retHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006778 }
6779
Torne (Richard Coles)466cbe42017-05-31 14:09:14 -04006780 private void handleRunIsolatedEntryPoint(String entryPoint, String[] entryPointArgs) {
6781 try {
6782 Method main = Class.forName(entryPoint).getMethod("main", String[].class);
6783 main.invoke(null, new Object[]{entryPointArgs});
6784 } catch (ReflectiveOperationException e) {
6785 throw new AndroidRuntimeException("runIsolatedEntryPoint failed", e);
6786 }
6787 // The process will be empty after this method returns; exit the VM now.
6788 System.exit(0);
6789 }
6790
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006791 @UnsupportedAppUsage
Sudheer Shankaf6690102017-10-16 10:20:32 -07006792 private void attach(boolean system, long startSeq) {
Jeff Sharkey66a017b2013-01-17 18:18:22 -08006793 sCurrentActivityThread = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006794 mSystemThread = system;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006795 if (!system) {
Siva Velusamyd693dfa2012-09-10 14:36:58 -07006796 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
6797 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006798 RuntimeInit.setApplicationObject(mAppThread.asBinder());
Sudheer Shankadc589ac2016-11-10 15:30:17 -08006799 final IActivityManager mgr = ActivityManager.getService();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006800 try {
Sudheer Shankaf6690102017-10-16 10:20:32 -07006801 mgr.attachApplication(mAppThread, startSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006802 } catch (RemoteException ex) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006803 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006804 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006805 // Watch for getting close to heap limit.
6806 BinderInternal.addGcWatcher(new Runnable() {
6807 @Override public void run() {
6808 if (!mSomeActivitiesChanged) {
6809 return;
6810 }
6811 Runtime runtime = Runtime.getRuntime();
6812 long dalvikMax = runtime.maxMemory();
6813 long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
6814 if (dalvikUsed > ((3*dalvikMax)/4)) {
6815 if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
6816 + " total=" + (runtime.totalMemory()/1024)
6817 + " used=" + (dalvikUsed/1024));
6818 mSomeActivitiesChanged = false;
6819 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07006820 ActivityTaskManager.getService().releaseSomeActivities(mAppThread);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006821 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07006822 throw e.rethrowFromSystemServer();
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006823 }
6824 }
6825 }
6826 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006827 } else {
6828 // Don't set application object here -- if the system crashes,
6829 // we can't display an alert, we just want to die die die.
Siva Velusamyd693dfa2012-09-10 14:36:58 -07006830 android.ddm.DdmHandleAppName.setAppName("system_process",
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006831 UserHandle.myUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006832 try {
6833 mInstrumentation = new Instrumentation();
Jason Monka80bfb52017-11-16 17:15:37 -05006834 mInstrumentation.basicInit(this);
Jeff Browndefd4a62014-03-10 21:24:37 -07006835 ContextImpl context = ContextImpl.createAppContext(
Todd Kennedy233a0b12018-01-29 20:30:24 +00006836 this, getSystemContext().mPackageInfo);
6837 mInitialApplication = context.mPackageInfo.makeApplication(true, null);
Jeff Brown7fc8e352014-09-16 18:06:47 -07006838 mInitialApplication.onCreate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006839 } catch (Exception e) {
6840 throw new RuntimeException(
6841 "Unable to instantiate Application():" + e.toString(), e);
6842 }
6843 }
Geremy Condrab7faaf42012-09-19 18:07:42 -07006844
Andrii Kulian44607962017-03-16 11:06:24 -07006845 ViewRootImpl.ConfigChangedCallback configChangedCallback
6846 = (Configuration globalConfig) -> {
6847 synchronized (mResourcesManager) {
6848 // We need to apply this change to the resources immediately, because upon returning
6849 // the view hierarchy will be informed about it.
6850 if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,
6851 null /* compat */)) {
6852 updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
6853 mResourcesManager.getConfiguration().getLocales());
Adam Lesinskib61e4052016-05-19 18:23:05 -07006854
Andrii Kulian44607962017-03-16 11:06:24 -07006855 // This actually changed the resources! Tell everyone about it.
6856 if (mPendingConfiguration == null
6857 || mPendingConfiguration.isOtherSeqNewer(globalConfig)) {
6858 mPendingConfiguration = globalConfig;
6859 sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
Dianne Hackborne36d6e22010-02-17 19:46:25 -08006860 }
6861 }
Dianne Hackborne36d6e22010-02-17 19:46:25 -08006862 }
Andrii Kulian44607962017-03-16 11:06:24 -07006863 };
6864 ViewRootImpl.addConfigCallback(configChangedCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006865 }
6866
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006867 @UnsupportedAppUsage
Romain Guy5e9120d2012-01-30 12:17:22 -08006868 public static ActivityThread systemMain() {
Alan Viverette5e1565e2014-07-29 16:14:25 -07006869 // The system process on low-memory devices do not get to use hardware
6870 // accelerated drawing, since this can add too much overhead to the
6871 // process.
6872 if (!ActivityManager.isHighEndGfx()) {
John Reck51aaf902015-12-02 15:08:07 -08006873 ThreadedRenderer.disable(true);
John Reck73840ea2014-09-22 07:39:18 -07006874 } else {
John Reck51aaf902015-12-02 15:08:07 -08006875 ThreadedRenderer.enableForegroundTrimming();
Alan Viverette5e1565e2014-07-29 16:14:25 -07006876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006877 ActivityThread thread = new ActivityThread();
Sudheer Shankaf6690102017-10-16 10:20:32 -07006878 thread.attach(true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006879 return thread;
6880 }
6881
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006882 @UnsupportedAppUsage
Jeff Brown10e89712011-07-08 18:52:57 -07006883 public final void installSystemProviders(List<ProviderInfo> providers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006884 if (providers != null) {
Jeff Brown10e89712011-07-08 18:52:57 -07006885 installContentProviders(mInitialApplication, providers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006886 }
6887 }
6888
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006889 public int getIntCoreSetting(String key, int defaultValue) {
Craig Mautner88c05892013-06-28 09:47:45 -07006890 synchronized (mResourcesManager) {
Svetoslav Ganov9aa597e2011-03-03 18:17:41 -08006891 if (mCoreSettings != null) {
6892 return mCoreSettings.getInt(key, defaultValue);
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006893 }
Craig Mautner88c05892013-06-28 09:47:45 -07006894 return defaultValue;
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006895 }
6896 }
6897
Jeff Sharkeybc2ae002018-07-31 10:45:37 -06006898 private static class AndroidOs extends ForwardingOs {
6899 /**
6900 * Install selective syscall interception. For example, this is used to
6901 * implement special filesystem paths that will be redirected to
6902 * {@link ContentResolver#openFileDescriptor(Uri, String)}.
6903 */
6904 public static void install() {
6905 // If feature is disabled, we don't need to install
6906 if (!DEPRECATE_DATA_COLUMNS) return;
6907
6908 // If app is modern enough, we don't need to install
6909 if (VMRuntime.getRuntime().getTargetSdkVersion() >= Build.VERSION_CODES.Q) return;
6910
6911 // Install interception and make sure it sticks!
6912 Os def = null;
6913 do {
6914 def = Os.getDefault();
6915 } while (!Os.compareAndSetDefault(def, new AndroidOs(def)));
6916 }
6917
6918 private AndroidOs(Os os) {
6919 super(os);
6920 }
6921
6922 private FileDescriptor openDeprecatedDataPath(String path, int mode) throws ErrnoException {
6923 final Uri uri = ContentResolver.translateDeprecatedDataPath(path);
6924 Log.v(TAG, "Redirecting " + path + " to " + uri);
6925
6926 final ContentResolver cr = currentActivityThread().getApplication()
6927 .getContentResolver();
6928 try {
6929 final FileDescriptor fd = new FileDescriptor();
6930 fd.setInt$(cr.openFileDescriptor(uri,
6931 FileUtils.translateModePosixToString(mode)).detachFd());
6932 return fd;
Jeff Sharkeyb50f51e2019-02-27 13:55:38 -07006933 } catch (SecurityException e) {
6934 throw new ErrnoException(e.getMessage(), OsConstants.EACCES);
Jeff Sharkeybc2ae002018-07-31 10:45:37 -06006935 } catch (FileNotFoundException e) {
6936 throw new ErrnoException(e.getMessage(), OsConstants.ENOENT);
6937 }
6938 }
6939
Jeff Sharkey416d4622019-02-27 22:14:16 -07006940 private void deleteDeprecatedDataPath(String path) throws ErrnoException {
6941 final Uri uri = ContentResolver.translateDeprecatedDataPath(path);
6942 Log.v(TAG, "Redirecting " + path + " to " + uri);
6943
6944 final ContentResolver cr = currentActivityThread().getApplication()
6945 .getContentResolver();
6946 try {
6947 if (cr.delete(uri, null, null) == 0) {
6948 throw new FileNotFoundException();
6949 }
6950 } catch (SecurityException e) {
6951 throw new ErrnoException(e.getMessage(), OsConstants.EACCES);
6952 } catch (FileNotFoundException e) {
6953 throw new ErrnoException(e.getMessage(), OsConstants.ENOENT);
6954 }
6955 }
6956
Jeff Sharkeybc2ae002018-07-31 10:45:37 -06006957 @Override
6958 public boolean access(String path, int mode) throws ErrnoException {
6959 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
6960 // If we opened it okay, then access check succeeded
6961 IoUtils.closeQuietly(
6962 openDeprecatedDataPath(path, FileUtils.translateModeAccessToPosix(mode)));
6963 return true;
6964 } else {
6965 return super.access(path, mode);
6966 }
6967 }
6968
6969 @Override
6970 public FileDescriptor open(String path, int flags, int mode) throws ErrnoException {
6971 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
6972 return openDeprecatedDataPath(path, mode);
6973 } else {
6974 return super.open(path, flags, mode);
6975 }
6976 }
6977
6978 @Override
6979 public StructStat stat(String path) throws ErrnoException {
6980 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
6981 final FileDescriptor fd = openDeprecatedDataPath(path, OsConstants.O_RDONLY);
6982 try {
6983 return android.system.Os.fstat(fd);
6984 } finally {
6985 IoUtils.closeQuietly(fd);
6986 }
6987 } else {
6988 return super.stat(path);
Narayan Kamath7f062242015-04-08 13:24:13 +01006989 }
6990 }
Jeff Sharkey416d4622019-02-27 22:14:16 -07006991
6992 @Override
6993 public void unlink(String path) throws ErrnoException {
6994 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
6995 deleteDeprecatedDataPath(path);
6996 } else {
6997 super.unlink(path);
6998 }
6999 }
7000
7001 @Override
7002 public void remove(String path) throws ErrnoException {
7003 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7004 deleteDeprecatedDataPath(path);
7005 } else {
7006 super.remove(path);
7007 }
7008 }
7009
7010 @Override
7011 public void rename(String oldPath, String newPath) throws ErrnoException {
7012 try {
7013 super.rename(oldPath, newPath);
7014 } catch (ErrnoException e) {
7015 if (e.errno == OsConstants.EXDEV) {
7016 Log.v(TAG, "Recovering failed rename " + oldPath + " to " + newPath);
7017 try {
7018 Files.move(new File(oldPath).toPath(), new File(newPath).toPath());
7019 } catch (IOException e2) {
7020 throw e;
7021 }
7022 } else {
7023 throw e;
7024 }
7025 }
7026 }
Geremy Condrab7faaf42012-09-19 18:07:42 -07007027 }
7028
Romain Guy65b345f2011-07-27 18:51:50 -07007029 public static void main(String[] args) {
Narayan Kamathfbb32f62015-06-12 15:34:35 +01007030 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
Bob Leee5408332009-09-04 18:31:17 -07007031
Jeff Sharkeybc2ae002018-07-31 10:45:37 -06007032 // Install selective syscall interception
7033 AndroidOs.install();
7034
Brad Fitzpatrick4d9e6d22010-11-15 08:49:51 -08007035 // CloseGuard defaults to true and can be quite spammy. We
7036 // disable it here, but selectively enable it later (via
7037 // StrictMode) on debug builds, but using DropBox, not logs.
7038 CloseGuard.setEnabled(false);
7039
Andreas Gamped281b422016-07-08 03:50:27 +00007040 Environment.initForCurrentUser();
Jeff Sharkeyb049e212012-09-07 23:16:01 -07007041
Robin Lee3d076af2014-04-25 14:57:49 +01007042 // Make sure TrustedCertificateStore looks in the right place for CA certificates
7043 final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
7044 TrustedCertificateStore.setDefaultUserDirectory(configDir);
7045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007046 Process.setArgV0("<pre-initialized>");
7047
7048 Looper.prepareMainLooper();
7049
Sudheer Shankaf6690102017-10-16 10:20:32 -07007050 // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
7051 // It will be in the format "seq=114"
7052 long startSeq = 0;
7053 if (args != null) {
7054 for (int i = args.length - 1; i >= 0; --i) {
7055 if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
7056 startSeq = Long.parseLong(
7057 args[i].substring(PROC_START_SEQ_IDENT.length()));
7058 }
7059 }
7060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007061 ActivityThread thread = new ActivityThread();
Sudheer Shankaf6690102017-10-16 10:20:32 -07007062 thread.attach(false, startSeq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007063
Vairavan Srinivasan7335cfd2012-08-18 18:36:03 -07007064 if (sMainThreadHandler == null) {
7065 sMainThreadHandler = thread.getHandler();
7066 }
7067
Dianne Hackborn287952c2010-09-22 22:34:31 -07007068 if (false) {
7069 Looper.myLooper().setMessageLogging(new
7070 LogPrinter(Log.DEBUG, "ActivityThread"));
7071 }
7072
Narayan Kamathfbb32f62015-06-12 15:34:35 +01007073 // End of event ActivityThreadMain.
7074 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007075 Looper.loop();
7076
Jeff Brown10e89712011-07-08 18:52:57 -07007077 throw new RuntimeException("Main thread loop unexpectedly exited");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007078 }
Chris Craikfc294242016-12-13 18:10:46 -08007079
7080 // ------------------ Regular JNI ------------------------
Tim Murray59f3dc12018-10-22 15:26:08 -07007081 private native void nPurgePendingResources();
Chris Craikfc294242016-12-13 18:10:46 -08007082 private native void nDumpGraphicsInfo(FileDescriptor fd);
Ryan Savitskicfdc1512018-12-14 16:20:52 +00007083 private native void nInitZygoteChildHeapProfiling();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007084}